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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -4237,6 +4237,40 @@ object SQLConf {
       .checkValue(v => Set(1, 2, 3, 4).contains(v), "Valid versions are 1, 2, 
3, and 4")
       .createWithDefault(2)
 
+  val STREAMING_JOIN_CHECKPOINT_WATERMARK_SEMANTICS_VERSION =
+    buildConf("spark.sql.streaming.join.checkpointWatermarkSemanticsVersion")
+      .internal()
+      .doc("Checkpoint generation for stream-stream join watermark semantics, 
persisted in " +
+        "the offset log. Older generations are accepted only when the query 
plan proves that " +
+        "its state and output watermark semantics are unchanged. The 
generation validates " +
+        "compatibility; it does not select a legacy execution path.")
+      .version("4.4.0")
+      .withBindingPolicy(ConfigBindingPolicy.NOT_APPLICABLE)
+      .intConf
+      .checkValue(v => v >= 0 && v <= 2, "Supported versions are 0 through 2")
+      .createWithDefault(2)
+
+  val STREAMING_JOIN_CHECK_FINALIZATION_ENABLED =
+    buildConf("spark.sql.streaming.join.checkFinalization.enabled")
+      .internal()
+      .doc("When true, a stream-stream left outer, right outer, full outer or 
left semi join " +
+        "fails analysis unless the watermarks and time constraints let Spark 
finalize the " +
+        "rows of each input whose unmatched rows it outputs or whose state it 
must bound for " +
+        "a semi join: such an input needs a bound derived from the other 
input's watermark. " +
+        "When false, Spark logs a warning instead and runs the query, as long 
as the join " +
+        "has a watermarked equality key or a range bound for a finalized 
input, which earlier " +
+        "versions required; other joins still fail analysis. Unmatched rows 
are " +
+        "still finalized only with that bound, so such a query keeps the 
input's state " +
+        "without bound, and an outer join never outputs the rows that the 
bound would " +
+        "finalize. Before Spark 4.4, a weaker check that ignored the direction 
of each " +
+        "watermark admitted some of these joins. The conf also controls the 
start-time check " +

Review Comment:
   **Nit (P3):** This doc and the migration guide's paragraph on the conf name 
the analysis check and the start-time check for append-mode aggregations after 
a join. `checkEventTimeCopyKeysPlanned` in `IncrementalExecution` also reads 
this conf and, when it is `false`, only logs 
`STREAMING_JOIN_EVENT_TIME_KEY_NOT_PLANNED` instead of failing. Someone who 
sets the conf to `false` to run one of the documented checks as a warning thus 
also lets a legacy-mode outer or left semi join start without the bound its 
copy key was meant to give. That join keeps the state without bound and never 
outputs those unmatched rows.
   
   **Verification:**
   - **Inspection:** The doc of the finalization conf and the migration guide's 
paragraph on it name the analysis check, the start-time check for aggregations 
after a join and the legacy-mode start-time check for planned keys, and say 
what setting the conf to false does for each.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala:
##########
@@ -721,14 +987,77 @@ 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. 
One that uses its
+        // input watermark reads the inputs that the tracer names, or both 
inputs when it cannot
+        // be traced. An operator uses it when an input carries an event-time 
column, when it
+        // fires event-time timeouts, or when it passes the watermark to user 
code, as
+        // transformWithState does in every time mode. The join's output 
watermark changes
+        // nothing for any other operator, such as an update-mode count on a 
key.
+        def usesInputWatermark(operator: StatefulOperator): Boolean = operator 
match {
+          case _: TransformWithStateExec | _: TransformWithStateInPySparkExec 
=> true
+          case f: FlatMapGroupsWithStateExec if f.timeoutConf == 
EventTimeTimeout => true
+          case f: FlatMapGroupsInPandasWithStateExec if f.timeoutConf == 
EventTimeTimeout => true
+          case _ => operator.children.exists(
+            _.output.exists(_.metadata.contains(EventTimeWatermark.delayKey)))
+        }
+        val joinsBelowStatefulOperators = planWithStateOpId.collect {
+          case s: StatefulOperator if usesInputWatermark(s) => 
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))
+            case _ => Set.empty
+          }
+        planWithStateOpId.foreach {
+          case j: StreamingSymmetricHashJoinExec
+              if 
!StreamingSymmetricHashJoinHelper.isWatermarkCheckpointCompatible(
+                j.left.output, j.right.output, j.leftKeys, j.rightKeys, 
j.condition.full,
+                consumedSides(j)) =>
+            // Name the side of each equality key; both inputs often use the 
same column names.
+            val keyConditions = j.leftKeys.zip(j.rightKeys).map { case (left, 
right) =>
+              s"left.${left.sql} = right.${right.sql}"
+            }
+            val conditions = keyConditions ++ j.condition.full.map(_.sql)
+            val joinCondition = if (conditions.isEmpty) "none" else 
conditions.mkString(" AND ")
+            throw new AnalysisException(
+              errorClass = "STREAMING_JOIN_CHECKPOINT_INCOMPATIBLE",
+              messageParameters = Map(
+                "joinCondition" -> joinCondition,
+                "leftWatermarkColumns" -> watermarkColumns(j.left),
+                "rightWatermarkColumns" -> watermarkColumns(j.right)))
+          case _ =>
+        }
+      }
+      // Like the checkpoint check, this runs before state metadata is written 
or state opened.
+      // With a single global watermark, the join's output watermark does not 
reach the consumers.
+      if (isFirstBatch && allowMultipleStatefulOperators) {
+        checkJoinOutputWatermarkConsumers(planWithStateOpId)
+      }
+      if (isFirstBatch && eventTimeCopies.pairs.nonEmpty) {

Review Comment:
   **Non-blocking (P2):** The analysis check computes the copy pairs from the 
plan it checks, while `IncrementalExecution` computes them again from each 
batch's analyzed plan, which `MicroBatchExecution` rebuilds for every batch. 
Both rely on `TIME_WINDOW_SOURCE_TAG` reaching that plan intact. `copyTagsFrom` 
copies only onto an untagged node, and the tag holds raw expression IDs, which 
`dedupRight` already leaves stale when a self-join renews them. This check runs 
only when execution's own pairs are non-empty and flags only keys among them, 
so it cannot catch a key that the analysis accepted but execution no longer 
recognizes. In that case a left outer join on `lk = rk AND lw = rw` gets no 
state predicate for its left input, keeps that state forever and never outputs 
its unmatched left rows, and nothing fails. Reading the code, no rewrite 
between the two readers drops the tag today, so this is a check that fails open 
rather than an observed wrong result. The comments here and in `Uns
 upportedOperationChecker` also say that both readers use the same analyzed 
plan, but each reads its own.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60280#discussion_r4537719964).
   
   See **Shared repair plan 1** in the review body.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -17,36 +17,395 @@
 
 package org.apache.spark.sql.catalyst.analysis
 
+import java.util.Locale
+
 import scala.util.control.NonFatal
 
 import org.apache.spark.internal.Logging
 import org.apache.spark.internal.LogKeys._
 import org.apache.spark.sql.catalyst.expressions._
-import org.apache.spark.sql.catalyst.planning.ExtractEquiJoinKeys
-import org.apache.spark.sql.catalyst.plans.logical.{EventTimeWatermark, 
LogicalPlan}
+import org.apache.spark.sql.catalyst.plans.logical.{EventTimeWatermark, 
Expand, Filter, Join, LogicalPlan, Project, SubqueryAlias, Union}
 import org.apache.spark.sql.catalyst.plans.logical.EventTimeWatermark._
-import org.apache.spark.sql.catalyst.util.DateTimeConstants.MICROS_PER_DAY
+import org.apache.spark.sql.catalyst.util.DateTimeConstants.{MICROS_PER_DAY, 
MICROS_PER_HOUR, MICROS_PER_MILLIS, MICROS_PER_MINUTE, MICROS_PER_SECOND}
 import org.apache.spark.sql.types._
 import org.apache.spark.unsafe.types.CalendarInterval
 
+/**
+ * Pairs of attributes `(key, eventTime)` where `key` is a copy of 
`eventTime`, or a tumbling or
+ * sliding time window over it, in every row of every stream-stream join input 
that outputs both.
+ * See [[StreamingJoinHelper.findEventTimeCopies]].
+ */
+case class EventTimeCopies(pairs: Set[(ExprId, ExprId)]) {
+  def isCopyOf(key: Expression, eventTime: Attribute): Boolean = key match {
+    case a: Attribute => pairs.contains((a.exprId, eventTime.exprId))
+    case _ => false
+  }
+
+  def keys: Set[ExprId] = pairs.map(_._1)
+}
+
+object EventTimeCopies {
+  val empty: EventTimeCopies = EventTimeCopies(Set.empty)
+}
+
 /**
  * Helper object for stream joins. See [[StreamingSymmetricHashJoinExec]] in 
SQL for more details.
  */
 object StreamingJoinHelper extends PredicateHelper with Logging {
 
   /**
-   * Check the provided logical plan to see if its join keys contain a 
watermark attribute.
-   *
-   * Will return false if the plan is not an equijoin.
-   * @param plan the logical plan to check
+   * Find the equality key filtered by this input's watermark. Its ordinal can 
be used to
+   * evict the opposite input's state, whose equality keys have the same 
ordering.
+   * For leftTime = rightTime, a watermark on rightTime bounds leftTime even 
when leftTime
+   * has no watermark. It does not bound right-side state without a watermark 
on leftTime.
+   * A key computed from the event time by adding constant intervals, such as
+   * leftTime = rightTime + INTERVAL 10 SECONDS or leftTime = 
timestampadd(HOUR, 1, rightTime),
+   * is bounded too if the solver can count the intervals exactly or they 
never move a time
+   * backward; see [[getStateKeyWatermark]]. The result does not depend on the 
session time zone,
+   * so neither does the V4 state layout.
+   */
+  def getStateKeyWatermarkOrdinal(
+      keys: Seq[Expression],
+      inputAttributes: Seq[Attribute],
+      eventTimeCopies: EventTimeCopies = EventTimeCopies.empty): Option[Int] = 
{
+    getEventTimeKeyOrdinal(keys, inputAttributes, eventTimeCopies).orElse {
+      keys.indices.find(getStateKeyWatermark(keys, inputAttributes, _, 
Some(0L)).isDefined)
+    }
+  }
+
+  /**
+   * Find the equality key that is this input's event-time column itself, or 
else one that
+   * `eventTimeCopies` names as a copy of that column or a time window over 
it. Such a key is
+   * above the watermark in every row that passes late filtering, as the 
column is: a window
+   * ends after every time it contains.
+   */
+  def getEventTimeKeyOrdinal(
+      keys: Seq[Expression],
+      inputAttributes: Seq[Attribute],
+      eventTimeCopies: EventTimeCopies = EventTimeCopies.empty): Option[Int] = 
{
+    // When multiple stateful operators are disabled, late filtering uses the 
first event-time
+    // column. Otherwise, execution rejects multiple distinct event-time 
columns.
+    inputAttributes.find(_.metadata.contains(delayKey)).flatMap { eventTime =>
+      Seq(keys.indexWhere(_.semanticEquals(eventTime)),
+        keys.indexWhere(eventTimeCopies.isCopyOf(_, eventTime))).find(_ >= 0)
+    }
+  }
+
+  /**
+   * In legacy mode 
(spark.sql.streaming.statefulOperator.allowMultiple=false), an input can keep
+   * its event time and a copy of it or a time window over it, all 
watermarked, and it filters
+   * late rows by the first of them. Find, for each stream-stream join input 
in `plan`, which of
+   * its watermarked columns are a copy of, or a tumbling or sliding time 
window over, another of
+   * them. A pair counts only if every join input that outputs both columns 
builds it that way,
+   * so the result does not depend on how a physical join is matched to its 
logical one: the
+   * physical inputs output the same values under the same expression IDs, or 
fewer columns.
+   */
+  def findEventTimeCopies(plan: LogicalPlan): EventTimeCopies = {
+    val verdicts = plan.collect {
+      case j: Join if j.left.isStreaming && j.right.isStreaming => Seq(j.left, 
j.right)
+    }.flatten.flatMap { input =>
+      val watermarked = 
input.output.filter(_.metadata.contains(delayKey)).map(_.exprId).distinct
+      for (key <- watermarked; eventTime <- watermarked if key != eventTime) 
yield {
+        (key, eventTime) -> isCopyOrWindowOf(input, key, eventTime, 
allowWindow = true)
+      }
+    }
+    val rejected = verdicts.collect { case (pair, false) => pair }.toSet
+    EventTimeCopies(verdicts.collect { case (pair, true) if !rejected(pair) => 
pair }.toSet)
+  }
+
+  /**
+   * Whether `key` is `eventTime`, or a tumbling or sliding time window over 
it when
+   * `allowWindow`, in every row of `plan`. The walk follows both columns down 
by expression ID
+   * through nodes that pass values on unchanged, to the same positions in 
every input of a union,
+   * and to the node that [[TimeWindowResolution.TIME_WINDOW_SOURCE_TAG]] 
marks as building the
+   * window from an attribute, which must then be a copy of `eventTime`. Any 
other node, or any
+   * other expression, such as a shifted time, a session window or a window 
over another column,
+   * gives false.
    */
-  def isWatermarkInJoinKeys(plan: LogicalPlan): Boolean = {
-    plan match {
-      case ExtractEquiJoinKeys(_, leftKeys, rightKeys, _, _, _, _, _) =>
-        (leftKeys ++ rightKeys).exists {
-          case a: AttributeReference => 
a.metadata.contains(EventTimeWatermark.delayKey)
-          case _ => false
+  private def isCopyOrWindowOf(
+      plan: LogicalPlan,
+      key: ExprId,
+      eventTime: ExprId,
+      allowWindow: Boolean): Boolean = {
+    def passedOn(e: Expression): Option[ExprId] = e match {
+      case a: Attribute => Some(a.exprId)
+      case Alias(a: Attribute, _) => Some(a.exprId)
+      case _ => None
+    }
+    // The time column that the node tagged by the window rewrite builds 
`window` from.
+    def timeColumnOf(node: LogicalPlan, window: ExprId): Option[ExprId] =
+      node.getTagValue(TimeWindowResolution.TIME_WINDOW_SOURCE_TAG).collect {
+        case (id, timeColumn) if allowWindow && id == window => timeColumn
+      }
+    if (key == eventTime) {
+      true
+    } else {
+      plan match {
+        case p: Project =>
+          val keyEntry = p.projectList.find(_.exprId == key)
+          val eventTimeEntry = p.projectList.find(_.exprId == eventTime)
+          (keyEntry, eventTimeEntry.flatMap(passedOn)) match {
+            case (Some(entry), Some(childEventTime)) => passedOn(entry) match {
+              case Some(childKey) =>
+                isCopyOrWindowOf(p.child, childKey, childEventTime, 
allowWindow)
+              case None => timeColumnOf(p, key).exists { timeColumn =>
+                entry.references.map(_.exprId).toSet == Set(timeColumn) &&
+                  isCopyOrWindowOf(p.child, timeColumn, childEventTime, 
allowWindow = false)
+              }
+            }
+            case _ => false
+          }
+        case e: Expand =>
+          // The rewrite of a sliding window puts one window per projection 
beside the child's
+          // columns, which every projection passes on.
+          val keyIndex = e.output.indexWhere(_.exprId == key)
+          val eventTimeIndex = e.output.indexWhere(_.exprId == eventTime)
+          lazy val childEventTimes = e.projections.map(p => 
passedOn(p(eventTimeIndex))).distinct
+          keyIndex >= 0 && eventTimeIndex >= 0 && childEventTimes.size == 1 &&
+            childEventTimes.head.isDefined && timeColumnOf(e, key).exists { 
timeColumn =>
+              e.projections.forall(_(keyIndex).references.map(_.exprId).toSet 
== Set(timeColumn)) &&
+                isCopyOrWindowOf(e.child, timeColumn, childEventTimes.head.get,
+                  allowWindow = false)
+            }
+        case u: Union =>
+          val keyIndex = u.output.indexWhere(_.exprId == key)
+          val eventTimeIndex = u.output.indexWhere(_.exprId == eventTime)
+          keyIndex >= 0 && eventTimeIndex >= 0 && u.children.forall { child =>
+            isCopyOrWindowOf(child, child.output(keyIndex).exprId,
+              child.output(eventTimeIndex).exprId, allowWindow)
+          }
+        case _: Filter | _: SubqueryAlias | _: EventTimeWatermark =>
+          isCopyOrWindowOf(plan.children.head, key, eventTime, allowWindow)
+        case _ => false

Review Comment:
   **Blocking (P1):** Reading the code with 
`spark.sql.streaming.statefulOperator.allowMultiple=false`: build each input as 
`withWatermark("t", ...).withColumn("w", window($"t", "10 seconds"))` and add 
`.repartition(10)` to the right input. A left outer join on `lk = rk AND lw = 
rw` then reaches this `case _ => false` at the `Repartition`, so `(rw, rt)` is 
rejected, no right key bounds the left state, and the join fails analysis. On 
the base branch the join was admitted and both inputs were evicted at the 
window end. That drops nothing a later row can match, because legacy mode 
filters late rows on `t` at the same watermark and every window ends after its 
`t`.
   
   The same rejection happens when the key passes through a temporary view 
referenced from SQL (`View` stays in the analyzed plan), a typed filter, 
`observe`, a hint or the streaming side of a stream-static join. It also 
happens in a stream-stream self-join, where `dedupRight` renews the right 
input's IDs while the copied tag still names the old time column, and for a 
session window, whose rewrite sets no tag although each session starts at its 
`t` and ends after it. With 
`spark.sql.streaming.join.checkFinalization.enabled=false` these joins run but 
never output the finalized input's unmatched rows. Their inner forms keep the 
other input's state for the life of the query without any message. Each of 
these shapes either passes both columns through unchanged or builds the window 
from the late-filtered column itself, so a walk can recognize them.
   
   This extends existing discussions 
[1](https://github.com/apache/spark/pull/60280#issuecomment-6885547060), 
[2](https://github.com/apache/spark/pull/60280#discussion_r4537719964).
   
   **Recommended change:** In legacy mode, let a later watermarked equality key 
bound the other input's state whenever every path builds it from the 
late-filtered column itself. Make isCopyOrWindowOf follow any unary node that 
outputs both columns with its child's expression IDs, such as a repartition, 
the view of a temporary view, a typed filter, observe or a hint, and the 
streaming input of a stream-static join, whose columns the join passes through; 
follow an Expand that does not build the window only when every projection 
passes both columns through unchanged. Record the window rewrite's tag without 
expression IDs, as the window column's position in the tagged node, and take 
the time column from the window expression's single attribute reference, so a 
self-join's renewed IDs still match; accept that entry only while it is still 
the window the rewrite built. Tag the session-window rewrite the same way when 
its time column is an attribute, since every session starts at that column 
 and ends after it. Keep rejecting a window over a shifted time or over another 
input's event time and a union whose inputs differ. Update the legacy window 
hint in the analysis error and the migration guide's legacy-mode paragraph, 
which now say that only projections, filters and unions are followed and that 
session windows fail, and turn the legacy-key tests that expect a session 
window to be rejected into tests that it bounds state.
   
   **Why this works:** Within a unary node, Spark keeps a column's expression 
ID only while the node passes the column's value through unchanged, an 
aggregation passing each group's value of a grouping column; a union keeps its 
first input's IDs for the values of every input and an Expand chooses values 
per projection, which is why both keep their own checks. So a key that reaches 
the join with the IDs the rewrite gave it, next to the event time with its own 
ID, is still each row's copy of, or window over, the column the input filters 
late rows by, and evicting at that key drops no row that a later row can match, 
exactly as on the base branch. A position in the tagged node survives the ID 
renewal that DeduplicateRelations applies to a self-join, so the tag keeps 
marking the same window.
   
   **Scope:** Broaden the legacy-mode copy and window recognition of the 
stream-stream join helper, make the window tag survive expression ID renewal, 
tag session windows, and update the legacy hint, the migration guide and the 
legacy-mode tests.
   
   **Compatibility:** Joins run with multiple stateful operators allowed, and 
every legacy-mode shape that the current rule rejects because it recomputes the 
key or the event time, keep their current behavior.
   
   **Risks:** Following every unary node that keeps its child's IDs also 
follows operators such as an aggregation or a deduplication before the join; 
each output row keeps its key and event time, so the copy relation still holds, 
but the tests should include one such shape. A position-based tag relies on no 
later rewrite moving the window within the tagged node; if one does, the marker 
and single-reference checks reject the entry, which keeps today's behavior of 
no bound rather than evicting early.
   
   **Constraints:** The analysis check and execution must keep calling the same 
recognition function, so both accept the same pairs. A key whose path 
recomputes either column, a window over a shifted time or over another input's 
event time, and a union whose inputs differ must still give no bound. At a 
tagged node, accept the key only when its entry is the window the rewrite 
built: an alias that carries the time-window or session-window marker and whose 
expression references exactly one attribute, the time column.
   
   **Exclusions:**
   - Making the start-time check fail when execution does not see a pair that 
the analysis accepted is a separate repair.
   - Keys not built from the late-filtered column, such as a window over 
another column, stay without a bound, because the base branch evicted them too 
early.
   
   **Success:** In legacy mode, outer and left semi joins on a copy of, or a 
tumbling, sliding or constant-gap session window over, the late-filtered event 
time pass analysis and output their unmatched rows when the key reaches the 
join through a repartition, a temporary view referenced from SQL, a typed 
filter, observe, a hint or the streaming side of a stream-static join, and in 
stream-stream self-joins. The inner forms of those joins evict both inputs' 
state at the key, as on the base branch. Windows over a shifted time or over 
another input's event time, and unions whose inputs build the key differently, 
still give no bound.
   
   **Verification:**
   - **Behavior:** Legacy-mode joins on a copy of, and on a tumbling, sliding 
and constant-gap session window over, the late-filtered event time, reached 
through a repartition, a SQL temporary view, a typed filter, observe and a 
hint, and in a stream-stream self-join, pass analysis for every outer and left 
semi join type, output the expected unmatched rows, and keep only the bounded 
number of state rows across batches.
   - **Regression:** A legacy-mode left outer join on equal keys and equal 
ten-second windows over each input's late-filtered event time, with a 
repartition on the right input, passes analysis and evicts both inputs at the 
window end instead of failing analysis.
   - **Compatibility:** Windows over a shifted time or over another input's 
event time and unions whose inputs differ still fail analysis for outer joins 
and keep state for inner joins, and joins run with multiple stateful operators 
allowed behave as before.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -705,33 +715,138 @@ object UnsupportedOperationChecker extends Logging {
       plan = operator)
   }
 
-  private def checkForStreamStreamJoinWatermark(join: Join): Unit = {
-    val watermarkInJoinKeys = StreamingJoinHelper.isWatermarkInJoinKeys(join)
-
-    // Check if the nullable side has a watermark, and there's a range 
condition which
-    // implies a state value watermark on the first side.
-    val hasValidWatermarkRange = join.joinType match {
-      case LeftOuter | LeftSemi => StreamingJoinHelper.getStateValueWatermark(
-        join.left.outputSet, join.right.outputSet, join.condition, 
Some(1000000)).isDefined
-      case RightOuter => StreamingJoinHelper.getStateValueWatermark(
-        join.right.outputSet, join.left.outputSet, join.condition, 
Some(1000000)).isDefined
-      case FullOuter =>
-        Seq((join.left.outputSet, join.right.outputSet),
-          (join.right.outputSet, join.left.outputSet)).exists {
-          case (attributesToFindStateWatermarkFor, 
attributesWithEventWatermark) =>
-            
StreamingJoinHelper.getStateValueWatermark(attributesToFindStateWatermarkFor,
-              attributesWithEventWatermark, join.condition, 
Some(1000000)).isDefined
-        }
+  private def checkForStreamStreamJoinWatermark(
+      join: Join,
+      eventTimeCopies: EventTimeCopies): Unit = {
+    val keys = ExtractEquiJoinKeys.unapply(join)
+    val leftKeys = keys.map(_._2).getOrElse(Nil)
+    val rightKeys = keys.map(_._3).getOrElse(Nil)
+
+    // TODO(SPARK-61347): this accepts a range bound on an input without its 
own watermark,
+    //   which eviction does not finalize yet.
+    // TODO(SPARK-61348): this also accepts a range bound on a column that is 
not TIMESTAMP,
+    //   which eviction never finalizes.
+    // TODO(SPARK-61349): this also accepts a bound that uses only constants, 
which does not
+    //   follow the other input's watermark and so cannot finalize unmatched 
state.
+    def canEvictState(
+        stateInput: LogicalPlan,
+        otherInput: LogicalPlan,
+        otherKeys: Seq[Expression]): Boolean = {
+      val eventTime = 
otherInput.output.find(_.metadata.contains(EventTimeWatermark.delayKey))
+      StreamingJoinHelper.getStateKeyWatermarkOrdinal(
+        otherKeys, otherInput.output, eventTimeCopies).isDefined ||
+        StreamingJoinHelper.getStateValueWatermark(stateInput.outputSet,
+          AttributeSet(eventTime.toSeq), join.condition, 
Some(1000000)).isDefined
+    }
+
+    // The rule of Spark versions before 4.4: a watermarked equality key, or a 
range bound that the
+    // solver finds for a finalized input. Disabling the finalization check 
never goes below it.
+    def admittedBeforeFinalizationCheck: Boolean = {
+      def hasRangeBound(stateInput: LogicalPlan, otherInput: LogicalPlan): 
Boolean =
+        StreamingJoinHelper.getStateValueWatermark(stateInput.outputSet, 
otherInput.outputSet,
+          join.condition, Some(1000000)).isDefined
+      (leftKeys ++ rightKeys).exists {
+        case a: AttributeReference => 
a.metadata.contains(EventTimeWatermark.delayKey)
+        case _ => false
+      } || (join.joinType match {
+        case LeftOuter | LeftSemi => hasRangeBound(join.left, join.right)
+        case RightOuter => hasRangeBound(join.right, join.left)
+        case _ => hasRangeBound(join.left, join.right) || 
hasRangeBound(join.right, join.left)
+      })
+    }
+
+    val leftCanEvict = canEvictState(join.left, join.right, rightKeys)
+    val rightCanEvict = canEvictState(join.right, join.left, leftKeys)
+    val hasRequiredWatermarks = join.joinType match {
+      case LeftOuter | LeftSemi => leftCanEvict
+      case RightOuter => rightCanEvict
+      case FullOuter => leftCanEvict && rightCanEvict
       case _ =>
         throwError(
           s"Join type ${join.joinType} is not supported with streaming 
DataFrame/Dataset")(join)
     }
 
-    if (!watermarkInJoinKeys && !hasValidWatermarkRange) {
-      throwError(
+    if (!hasRequiredWatermarks) {
+      val requirement = join.joinType match {
+        case FullOuter => "watermarks on both inputs and time constraints in 
both directions"
+        case RightOuter => "a watermark on the left input and a time 
constraint"
+        case _ => "a watermark on the right input and a time constraint"
+      }
+      // The join holds back its output watermark for an input whose state is 
unbounded.
+      val downstreamRequirement = join.joinType match {
+        case LeftOuter => Some(("right", "left"))
+        case RightOuter => Some(("left", "right"))
+        case _ => None
+      }
+      // The error says that such an aggregation fails at start. The warning 
is logged only with
+      // the finalization check disabled, which lets the query start, so it 
never emits instead.
+      def downstreamNote(aggregationOutcome: String): String =

Review Comment:
   **Nit (P3):** This note goes into the error and the warning in every mode. 
With `spark.sql.streaming.statefulOperator.allowMultiple=false`, 
`IncrementalExecution` skips `checkJoinOutputWatermarkConsumers`, and 
`WatermarkPropagator` uses `UseSingleWatermarkPropagator`, which ignores the 
join's output watermark. So the aggregation neither fails at start nor stalls, 
and `StreamingJoinOutputWatermarkSuite`'s one-global-watermark test shows it 
emitting. A legacy-mode user who hits this error, for example together with the 
window hint, is asked to add watermarks and constraints for a failure that 
cannot occur. Appending the note only when multiple stateful operators are 
allowed would match what the query does.
   
   **Verification:**
   - **Behavior:** In legacy mode, a left outer join that fails the directional 
check fails analysis with a message that has no downstream note, and with the 
finalization check disabled its warning has no downstream note either.
   - **Compatibility:** With multiple stateful operators allowed, the analysis 
error still says that such an aggregation fails at start and the warning says 
that it never emits results.



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationsSuite.scala:
##########
@@ -511,52 +517,338 @@ class UnsupportedOperationsSuite extends SparkFunSuite 
with SQLHelper {
       Seq("is not supported in Complete output mode", allowedModesMsg))
   }
 
-  // Left outer, right outer, full outer, left semi joins
-  Seq(LeftOuter, RightOuter, FullOuter, LeftSemi).foreach { joinType =>
-    // Stream-stream allowed with join on watermark attribute
-    // Note that the attribute need not be watermarked on both sides.
-    assertSupportedInStreamingPlan(
-      s"$joinType join with stream-stream relations and join on attribute with 
left watermark",
-      streamRelation.join(streamRelation, joinType = joinType,
-        condition = Some(attributeWithWatermark === attribute)),
-      OutputMode.Append())
-    assertSupportedInStreamingPlan(
-      s"$joinType join with stream-stream relations and join on attribute with 
right watermark",
-      streamRelation.join(streamRelation, joinType = joinType,
-        condition = Some(attribute === attributeWithWatermark)),
-      OutputMode.Append())
-    assertNotSupportedInStreamingPlan(
-      s"$joinType join with stream-stream relations and join on 
non-watermarked attribute",
-      streamRelation.join(streamRelation, joinType = joinType,
-        condition = Some(attribute === attribute)),
-      OutputMode.Append(),
-      Seq("without a watermark in the join keys"))
-
-    val timeWithWatermark =
-      AttributeReference("b", IntegerType)().withMetadata(watermarkMetadata)
-    val relationWithWatermark = new TestStreamingRelation(timeWithWatermark)
-    val (leftRelation, rightRelation) =
-      if (joinType == RightOuter) {
-        (relationWithWatermark, streamRelation)
-      } else {
-        (streamRelation, relationWithWatermark)
+  for {
+    joinType <- Seq(LeftOuter, RightOuter, FullOuter, LeftSemi)
+    leftWatermark <- Seq(false, true)
+    rightWatermark <- Seq(false, true)
+    conditionType <- Seq("equality", "range", "left bound", "right bound")
+  } {
+    val leftTime = AttributeReference("leftTime", TimestampType)()
+    val rightTime = AttributeReference("rightTime", TimestampType)()
+    val left = if (leftWatermark) leftTime.withMetadata(watermarkMetadata) 
else leftTime
+    val right = if (rightWatermark) rightTime.withMetadata(watermarkMetadata) 
else rightTime
+    val condition = conditionType match {
+      case "equality" => left === right
+      case "range" => left > right - 10 && left < right + 10
+      case "left bound" => left > right - 10
+      case "right bound" => left < right + 10
+    }
+    val leftCanEvict = rightWatermark && conditionType != "right bound"
+    val rightCanEvict = leftWatermark && conditionType != "left bound"
+    val correctedSupported = joinType match {
+      case LeftOuter | LeftSemi => leftCanEvict
+      case RightOuter => rightCanEvict
+      case FullOuter => leftCanEvict && rightCanEvict
+      case _ => false
+    }
+    val plan = new TestStreamingRelation(left).join(new 
TestStreamingRelation(right),
+      joinType = joinType, condition = Some(condition))
+    val name = s"$joinType $conditionType with watermarks " +
+      s"left=$leftWatermark right=$rightWatermark"
+    if (correctedSupported) {
+      assertSupportedInStreamingPlan(name, plan, OutputMode.Append())
+    } else {
+      assertNotSupportedInStreamingPlan(name, plan, OutputMode.Append(),
+        Seq("requires", "allow unmatched state to be finalized"))
+    }
+  }
+
+  {
+    val leftTime = AttributeReference("leftTime", TimestampType)()
+    val leftOther = AttributeReference("leftOther", TimestampType)()
+      .withMetadata(watermarkMetadata)
+    val rightTime = AttributeReference("rightTime", TimestampType)()
+      .withMetadata(watermarkMetadata)
+    val rightOther = AttributeReference("rightOther", TimestampType)()
+    val left = new TestStreamingRelation(Seq(leftTime, leftOther))
+    val right = new TestStreamingRelation(Seq(rightTime, rightOther))
+
+    // Each side's state is evicted by the key that the opposite watermark 
bounds.
+    assertSupportedInStreamingPlan("full outer with different watermark key 
ordinals",
+      left.join(right, joinType = FullOuter,
+        condition = Some(leftTime === rightTime && leftOther === rightOther)), 
OutputMode.Append())
+  }
+
+  {
+    val leftTime = AttributeReference("leftTime", TimestampType)()
+      .withMetadata(watermarkMetadata)
+    val rightTime = AttributeReference("rightTime", TimestampType)()
+      .withMetadata(watermarkMetadata)
+    val rightOther = AttributeReference("rightOther", TimestampType)()
+    val left = new TestStreamingRelation(leftTime)
+    val right = new TestStreamingRelation(Seq(rightTime, rightOther))
+
+    def shift(time: Expression, seconds: Int): Expression =
+      TimestampAddInterval(time, Literal(Duration.ofSeconds(seconds)))
+
+    // A key computed from the opposite event time by a constant is bounded by 
its watermark.
+    Seq(10, -10).foreach { offset =>
+      Seq(LeftOuter, RightOuter, FullOuter, LeftSemi).foreach { joinType =>
+        assertSupportedInStreamingPlan(s"$joinType with a key shifted by 
$offset",
+          left.join(right, joinType = joinType,
+            condition = Some(leftTime === shift(rightTime, offset))), 
OutputMode.Append())
       }
+      assertNotSupportedInStreamingPlan(
+        s"LeftOuter with a key shifted by $offset from an unwatermarked 
column",
+        left.join(right, joinType = LeftOuter,
+          condition = Some(leftTime === shift(rightOther, offset))), 
OutputMode.Append(),
+        Seq("requires a watermark on the right input"))
+    }
 
-    // stream-stream allowed with range condition yielding state value 
watermark
-    assertSupportedInStreamingPlan(
-      s"$joinType join with stream-stream relations and state value watermark",
-      leftRelation.join(rightRelation, joinType = joinType,
-        condition = Some(attribute > timeWithWatermark + 10)),
-      OutputMode.Append())
+    // The admission check sees the analyzed plan, where an interval 
expression such as
+    // INTERVAL 1 HOUR * 2 is not folded yet. It is bounded as its value is.
+    val twoHours = MultiplyDTInterval(Literal(Duration.ofHours(1)), Literal(2))
+    Seq(LeftOuter, FullOuter, LeftSemi).foreach { joinType =>
+      assertSupportedInStreamingPlan(s"$joinType with a key shifted by an 
interval expression",
+        left.join(right, joinType = joinType,
+          condition = Some(leftTime === TimestampAddInterval(rightTime, 
twoHours, Some("UTC")))),
+        OutputMode.Append())
+    }
+    Seq(
+      "minus two days" -> TimestampAddInterval(rightTime,
+        MultiplyDTInterval(Literal(Duration.ofDays(1)), Literal(-2)), 
Some("UTC")),
+      "minus two months" -> TimestampAddYMInterval(rightTime,
+        MultiplyYMInterval(Literal(Period.ofMonths(1)), Literal(-2)), 
Some("UTC")),
+      "an unwatermarked column" -> TimestampAddInterval(rightOther, twoHours, 
Some("UTC")),
+      "a truncated time" -> TimestampAddInterval(
+        rightTime.cast(LongType).cast(TimestampType), twoHours, 
Some("UTC"))).foreach {
+      case (name, key) =>
+        assertNotSupportedInStreamingPlan(
+          s"LeftOuter with a key shifted by an interval expression: $name",
+          left.join(right, joinType = LeftOuter, condition = Some(leftTime === 
key)),
+          OutputMode.Append(), Seq("requires a watermark on the right input"))
+    }
 
-    // stream-stream not allowed with insufficient range condition
-    assertNotSupportedInStreamingPlan(
-      s"$joinType join with stream-stream relations and state value watermark",
-      leftRelation.join(rightRelation, joinType = joinType,
-        condition = Some(attribute < timeWithWatermark + 10)),
-      OutputMode.Append(),
-      Seq("is not supported without a watermark in the join keys, or a 
watermark on " +
-        "the nullable side and an appropriate range condition"))
+    // timestampadd is a shift too: exact for a sub-day unit, and forward-only 
for days, weeks,
+    // months, quarters and years with a non-negative amount.
+    Seq(
+      ("one hour", TimestampAdd("HOUR", Literal(1), rightTime, Some("UTC")), 
true),
+      ("one day", TimestampAdd("DAY", Literal(1), rightTime, 
Some("America/Los_Angeles")), true),
+      ("minus one day", TimestampAdd("DAY", Literal(-1), rightTime, 
Some("UTC")), false),
+      ("one hour of an unwatermarked column",
+        TimestampAdd("HOUR", Literal(1), rightOther, Some("UTC")), 
false)).foreach {
+      case (name, key, supported) =>
+        Seq(LeftOuter, FullOuter, LeftSemi).foreach { joinType =>
+          val plan = left.join(right, joinType = joinType, condition = 
Some(leftTime === key))
+          val testName = s"$joinType with a key shifted by timestampadd of 
$name"
+          if (supported) {
+            assertSupportedInStreamingPlan(testName, plan, OutputMode.Append())
+          } else {
+            val requirement = if (joinType == FullOuter) {
+              "watermarks on both inputs"
+            } else {
+              "a watermark on the right input"
+            }
+            assertNotSupportedInStreamingPlan(testName, plan, 
OutputMode.Append(),
+              Seq(s"requires $requirement"))
+          }
+        }
+    }
+
+    // Whole days are added in the session time zone, where a day can be 23 or 
25 hours, and
+    // months vary in length. A shift that never moves a time backward still 
bounds the key, in
+    // every time zone; one that can move a time backward does not.
+    for {
+      zone <- Seq("UTC", "America/Los_Angeles")
+      (name, interval, supported) <- Seq(
+        ("one day", Literal(Duration.ofDays(1)), true),
+        ("minus one day", Literal(Duration.ofDays(-1)), false),
+        ("one month", Literal(Period.ofMonths(1)), true),
+        ("minus one month", Literal(Period.ofMonths(-1)), false))
+    } {
+      val shifted = interval.dataType match {
+        case _: YearMonthIntervalType => TimestampAddYMInterval(rightTime, 
interval, Some(zone))
+        case _ => TimestampAddInterval(rightTime, interval, Some(zone))
+      }
+      Seq(LeftOuter, LeftSemi, FullOuter).foreach { joinType =>
+        val plan = left.join(right, joinType = joinType, condition = 
Some(leftTime === shifted))
+        val testName = s"$joinType with a key shifted by $name in $zone"
+        if (supported) {
+          assertSupportedInStreamingPlan(testName, plan, OutputMode.Append())
+        } else {
+          val requirement = if (joinType == FullOuter) {
+            "watermarks on both inputs"
+          } else {
+            "a watermark on the right input"
+          }
+          assertNotSupportedInStreamingPlan(testName, plan, 
OutputMode.Append(),
+            Seq(s"requires $requirement"))
+        }
+      }
+    }
+
+    // Truncation can map a future right row below the watermark, so it does 
not bound the key.
+    assertNotSupportedInStreamingPlan("LeftOuter with a key truncated from the 
right event time",
+      left.join(right, joinType = LeftOuter,
+        condition = Some(leftTime === 
rightTime.cast(LongType).cast(TimestampType))),
+      OutputMode.Append(), Seq("requires a watermark on the right input"))
+  }
+
+  // With allowMultiple=false, late rows are filtered by an input's first 
watermarked column, so
+  // a time window key after it bounds the opposite state only when the input 
builds the window
+  // from that column, which a relation that outputs both does not show.
+  {
+    val windowType = new StructType().add("start", TimestampType).add("end", 
TimestampType)
+    val windowMetadata = new MetadataBuilder()
+      .withMetadata(watermarkMetadata)
+      .putBoolean(TimeWindow.marker, true)
+      .build()
+    def windowJoin(joinType: JoinType, windowFirst: Boolean): LogicalPlan = {
+      def input(side: String): (LogicalPlan, Attribute, Attribute) = {
+        val key = AttributeReference(s"${side}Key", IntegerType)()
+        val time = AttributeReference(s"${side}Time", TimestampType)()
+          .withMetadata(watermarkMetadata)
+        val window = AttributeReference(s"${side}Window", windowType)()
+          .withMetadata(windowMetadata)
+        val output = if (windowFirst) Seq(key, window, time) else Seq(key, 
time, window)
+        (TestStreamingRelation(output), key, window)
+      }
+      val (left, leftKey, leftWindow) = input("left")
+      val (right, rightKey, rightWindow) = input("right")
+      left.join(right, joinType = joinType,
+        condition = Some(leftKey === rightKey && leftWindow === rightWindow))
+    }
+    val legacyMode = SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key -> "false"
+    Seq(
+      LeftOuter -> Seq("right"),
+      LeftSemi -> Seq("right"),
+      RightOuter -> Seq("left"),
+      FullOuter -> Seq("left", "right")).foreach { case (joinType, sides) =>
+      test(s"$joinType on a window after its event time in legacy mode names 
the column order") {
+        val error = intercept[AnalysisException] {
+          withSQLConf(legacyMode) {
+            UnsupportedOperationChecker.checkForStreaming(
+              wrapInStreaming(windowJoin(joinType, windowFirst = false)), 
OutputMode.Append())
+          }
+        }
+        sides.foreach { side =>
+          assert(error.getMessage.contains(s"the $side input filters late rows 
by its first " +
+            s"watermarked column, ${side}Time, so its window key ${side}Window 
is a time " +
+            "constraint only if that input computes it as a tumbling or 
sliding window over " +
+            s"${side}Time itself, through projections, filters and unions 
only. Otherwise, put " +
+            s"${side}Window before ${side}Time in that input's columns, or 
drop ${side}Time"))
+        }
+        Seq("left", "right").diff(sides).foreach { side =>
+          assert(!error.getMessage.contains(s"the $side input filters late 
rows"))
+        }
+      }
+
+      test(s"$joinType on a window after its event time in the default mode 
has no window hint") {
+        val error = intercept[AnalysisException] {
+          UnsupportedOperationChecker.checkForStreaming(
+            wrapInStreaming(windowJoin(joinType, windowFirst = false)), 
OutputMode.Append())
+        }
+        assert(error.getMessage.contains("allow unmatched state to be 
finalized"))
+        
assert(!error.getMessage.contains(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key))
+      }
+
+      assertSupportedInStreamingPlan(s"$joinType on a window before its event 
time in legacy mode",
+        windowJoin(joinType, windowFirst = true), OutputMode.Append(), 
legacyMode)
+    }
+  }
+
+  // Disabling the finalization check turns the admission failure into a 
warning.
+  Seq(LeftOuter, LeftSemi).foreach { joinType =>
+    val leftTime = AttributeReference("leftTime", 
TimestampType)().withMetadata(watermarkMetadata)
+    val rightTime = AttributeReference("rightTime", TimestampType)()
+    val plan = new TestStreamingRelation(leftTime).join(new 
TestStreamingRelation(rightTime),
+      joinType = joinType, condition = Some(leftTime === rightTime))
+    val checkConf = SQLConf.STREAMING_JOIN_CHECK_FINALIZATION_ENABLED.key
+    assertNotSupportedInStreamingPlan(s"$joinType without a right watermark",
+      plan, OutputMode.Append(), Seq("requires a watermark on the right 
input", checkConf))
+    assertSupportedInStreamingPlan(s"$joinType without a right watermark and 
$checkConf=false",
+      plan, OutputMode.Append(), checkConf -> "false")
+
+    // Joins that earlier versions rejected still fail, and the error does not 
offer the conf.
+    val noWatermark = AttributeReference("leftTime", TimestampType)()
+    val noWatermarkRight = AttributeReference("rightTime", TimestampType)()
+    val unsupported = new TestStreamingRelation(noWatermark).join(
+      new TestStreamingRelation(noWatermarkRight), joinType = joinType,
+      condition = Some(noWatermark === noWatermarkRight))
+    Seq("true", "false").foreach { enabled =>
+      test(s"$joinType without any watermark fails analysis when 
$checkConf=$enabled") {
+        withSQLConf(checkConf -> enabled) {
+          val e = intercept[AnalysisException] {
+            UnsupportedOperationChecker.checkForStreaming(
+              wrapInStreaming(unsupported), OutputMode.Append())
+          }
+          assert(e.getMessage.contains("requires a watermark on the right 
input"))
+          assert(!e.getMessage.contains(checkConf))
+        }
+      }
+    }
+
+    test(s"$joinType without a right watermark logs a warning when 
$checkConf=false") {
+      val appender = new LogAppender("finalization check")
+      withLogAppender(appender, level = Some(Level.WARN)) {
+        withSQLConf(checkConf -> "false") {
+          UnsupportedOperationChecker.checkForStreaming(wrapInStreaming(plan), 
OutputMode.Append())
+        }
+      }
+      val warnings = 
appender.loggingEvents.map(_.getMessage.getFormattedMessage)
+        .filter(_.contains("requires a watermark on the right input"))
+      assert(warnings.nonEmpty)
+      // The query starts with the check disabled, so the aggregation that the 
error says fails at
+      // start never emits instead.
+      if (joinType == LeftOuter) {
+        assert(warnings.forall { message =>
+          message.contains("an append-mode aggregation over that event time 
never emits results") &&
+            !message.contains("fails at start")
+        })
+      }
+    }
+  }
+
+  // The range-bound arm of the check that earlier versions applied keeps a 
join runnable with the
+  // conf false only when the range bounds the state of every input the join 
must finalize.

Review Comment:
   **Nit (P3):** `admittedBeforeFinalizationCheck` keeps a full outer join 
runnable when a range bounds either input (`hasRangeBound(join.left, 
join.right) || hasRangeBound(join.right, join.left)`), and the full outer test 
below expects a join bounded in one direction to log a warning and run. A 
maintainer who trusts this comment could tighten that arm and turn those joins 
back into failures with the conf `false`.
   
   ```suggestion
     // The range-bound arm of the check that earlier versions applied keeps a 
join runnable with the
     // conf false when the range bounds the state of any input the join must 
finalize.
   ```
   
   **Verification:**
   - **Inspection:** The comment above the range-bound tests says that a bound 
on one finalized input suffices, including for a full outer join, as the 
admission floor and the tests below it expect.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala:
##########
@@ -630,6 +671,231 @@ 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 =>
+          Seq(f.child)
+        case t: TransformWithStateExec if t.timeMode == TimeMode.EventTime() 
=> Seq(t.child)
+        case t: TransformWithStateInPySparkExec if t.timeMode == 
TimeMode.EventTime() =>
+          Seq(t.child)
+        case _ => Nil
+      }
+
+      plan.flatMap { consumer =>
+        watermarkedInputs(consumer).flatMap { input =>
+          Try(WatermarkSupport.findEventTimeColumn(input.output,
+            allowMultipleEventTimeColumns = 
false)).toOption.flatten.toSeq.flatMap { column =>
+            findJoinSides(input, column).map { case (joinOperatorId, side, 
joinEventTime) =>
+              JoinWatermarkConsumer(consumer, joinOperatorId, side, 
joinEventTime)
+            }
+          }
+        }
+      }
+    }
+
+    /**
+     * Tell each stream-stream join which inputs' event times reach the 
stateful operator that
+     * consumes its output watermark, so that the join holds back that 
watermark only for those
+     * inputs' state. A join without a traced consumer holds back for both 
inputs.
+     */
+    private def withJoinOutputWatermarkSides(plan: SparkPlan): SparkPlan = {
+      val sides = 
joinWatermarkConsumers(plan).groupMap(_.joinOperatorId)(_.side)
+      if (sides.isEmpty) {
+        plan
+      } else {
+        plan transform {
+          case j: StreamingSymmetricHashJoinExec
+              if j.stateInfo.exists(info => sides.contains(info.operatorId)) =>
+            j.copy(outputWatermarkSides = 
Some(sides(j.stateInfo.get.operatorId).toSet))
+        }
+      }
+    }
+
+    /**
+     * Reject an append-mode aggregation whose event time comes from a 
stream-stream join input
+     * that the join cannot bound: the join holds back its output watermark 
for that input, so
+     * the aggregation would never emit a result. Only an aggregation that the 
tracer of
+     * [[joinWatermarkConsumers]] reaches fails; with the finalization check 
disabled, it is only
+     * logged.
+     */
+    private def checkJoinOutputWatermarkConsumers(plan: SparkPlan): Unit = {

Review Comment:
   **Nit (P3):** The PR description and an earlier reply defer the other 
operators that stall behind a held output watermark to SPARK-61509: a later 
outer join, event-time timeouts in `flatMapGroupsWithState` or 
`transformWithState`, and an aggregation behind a later join. SPARK-61509 
appears nowhere in the code. Without a TODO here, like the TODO(SPARK-61347), 
TODO(SPARK-61348) and TODO(SPARK-61349) comments at the range-bound deferrals, 
a reader cannot tell that these operators stall because of a tracked gap rather 
than by design, so the check could be narrowed further or the follow-up dropped 
without anyone noticing.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60280#issuecomment-6816317254).
   
   **Verification:**
   - **Inspection:** The docstring of the start-time check carries a TODO 
naming SPARK-61509 and each kind of operator the check does not yet reject.



##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinEqualityWatermarkSuite.scala:
##########
@@ -0,0 +1,409 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.streaming
+
+import org.apache.logging.log4j.Level
+
+import org.apache.spark.sql.{DataFrame, Row}
+import org.apache.spark.sql.catalyst.analysis.StreamingJoinHelper
+import 
org.apache.spark.sql.execution.streaming.operators.stateful.join.StreamingSymmetricHashJoinExec
+import 
org.apache.spark.sql.execution.streaming.operators.stateful.join.StreamingSymmetricHashJoinHelper.{JoinStateKeyWatermarkPredicate,
 JoinStateValueWatermarkPredicate}
+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._
+import org.apache.spark.sql.internal.SQLConf
+
+class StreamingJoinEqualityWatermarkSuite extends StreamTest {
+  import testImplicits._
+
+  for {
+    version <- Seq(2, 3, 4)
+    restart <- Seq(false, true)
+  } {
+    test(s"equality eviction follows the opposite watermark, V$version 
restart=$restart") {
+      withSQLConf(
+        SQLConf.STREAMING_JOIN_STATE_FORMAT_VERSION.key -> version.toString,
+        SQLConf.STATE_STORE_PROVIDER_CLASS.key -> 
classOf[RocksDBStateStoreProvider].getName,
+        SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> "false") {
+        val leftInput = MemoryStream[(Int, Int)]
+        val rightInput = MemoryStream[(Int, Int)]
+        val left = leftInput.toDF().toDF("a", "b")
+          .select(timestamp_seconds($"a").as("la"), 
timestamp_seconds($"b").as("lb"))
+          .withWatermark("la", "10 seconds")
+        val right = rightInput.toDF().toDF("a", "b")
+          .select(timestamp_seconds($"a").as("ra"), 
timestamp_seconds($"b").as("rb"))
+          .withWatermark("rb", "10 seconds")
+        val joined = left.join(right, expr("la = ra AND lb = rb"), 
"full_outer")
+          .select($"la".cast("int"), $"lb".cast("int"),
+            $"ra".cast("int"), $"rb".cast("int"))
+        withTempDir { checkpoint =>
+          val restartActions = if (restart) {
+            Seq(StopStream, StartStream(checkpointLocation = 
checkpoint.getCanonicalPath))
+          } else {
+            Nil
+          }
+          testStream(joined)((Seq(
+            StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+            MultiAddData(leftInput, (5, 50))(rightInput, (80, 50)),
+            CheckNewAnswer(),
+            MultiAddData(leftInput, (60, 100))(rightInput, (70, 50)),
+            CheckNewAnswer(),
+            AddData(leftInput, (70, 100)),
+            // At watermark 40, left (5, 50) can still match fresh right input 
on rb=50.
+            CheckNewAnswer()) ++ restartActions ++ Seq(
+            AddData(rightInput, (5, 50)),
+            CheckNewAnswer(Row(5, 50, 5, 50)),
+            // Fresh on la, but already expired on lb: V4 must visit it below 
the old cutoff.
+            AddData(leftInput, (90, 10)),
+            CheckNewAnswer(Row(90, 10, null, null)),
+            MultiAddData(leftInput, (200, 200))(rightInput, (200, 200)),
+            CheckNewAnswer(Row(200, 200, 200, 200)),
+            MultiAddData(leftInput, (210, 210))(rightInput, (210, 210)),
+            CheckNewAnswer(Row(210, 210, 210, 210), Row(60, 100, null, null),
+              Row(70, 100, null, null), Row(null, null, 80, 50), Row(null, 
null, 70, 50))
+          )): _*)
+        }
+      }
+    }
+  }
+
+  test("V4 window equality retains state for future unwatermarked input") {
+    withSQLConf(
+      SQLConf.STREAMING_JOIN_STATE_FORMAT_VERSION.key -> "4",
+      SQLConf.STATE_STORE_PROVIDER_CLASS.key -> 
classOf[RocksDBStateStoreProvider].getName) {
+      val leftInput = MemoryStream[Int]
+      val rightInput = MemoryStream[Int]
+      val left = leftInput.toDF()
+        .select($"value".as("key"), timestamp_seconds($"value").as("time"))
+        .withWatermark("time", "10 seconds")
+        .select($"key", window($"time", "10 seconds"))
+      val right = rightInput.toDF()
+        .select($"value".as("key"), timestamp_seconds($"value").as("time"))
+        .select($"key", window($"time", "10 seconds"))
+      val joined = left.join(right, Seq("key", "window"))
+        .select($"key", $"window.end".cast("long"))
+      testStream(joined)(
+        AddData(leftInput, 1), CheckNewAnswer(),
+        AddData(rightInput, 1), CheckNewAnswer(Row(1, 10L)),
+        AddData(leftInput, 25), CheckNewAnswer(),
+        StopStream, StartStream(),
+        // The right input has no late filter; its old window must still find 
left state.
+        AddData(rightInput, 1), CheckNewAnswer(Row(1, 10L)),
+        AddData(leftInput, 5), CheckNewAnswer())
+    }
+  }
+
+  private def joinExec(query: StreamExecution): StreamingSymmetricHashJoinExec 
=
+    query.lastExecution.executedPlan.collectFirst {
+      case j: StreamingSymmetricHashJoinExec => j
+    }.get
+
+  /** Where the V4 eviction scan of the left key predicate starts in the last 
batch. */
+  private def leftPreviousScanBound(query: StreamExecution): Option[Long] =
+    joinExec(query).stateWatermarkPredicates.left.collect {
+      case p: JoinStateKeyWatermarkPredicate => p.prevStateWatermark
+    }.get
+
+  for {
+    version <- Seq(2, 3, 4)
+    offset <- Seq(10, -10)
+    // The analyzed plan keeps an interval expression unfolded; admission must 
still bound it.
+    (shiftedRightTime, spelling) <- Seq(
+      (s"rt + INTERVAL $offset SECONDS", ""),
+      (s"rt + INTERVAL 1 SECOND * $offset", " as an interval expression"),
+      (s"timestampadd(SECOND, $offset, rt)", " with timestampadd"))
+  } {
+    test(s"equality on a shifted opposite event time evicts state, V$version 
offset=$offset" +
+        spelling) {
+      withSQLConf(
+        SQLConf.STREAMING_JOIN_STATE_FORMAT_VERSION.key -> version.toString,
+        SQLConf.STATE_STORE_PROVIDER_CLASS.key -> 
classOf[RocksDBStateStoreProvider].getName,
+        SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> "false") {
+        val leftInput = MemoryStream[(Int, Int)]
+        val rightInput = MemoryStream[(Int, Int)]
+        val left = leftInput.toDF().toDF("lk", "lt")
+          .select($"lk", timestamp_seconds($"lt").as("lt"))
+          .withWatermark("lt", "10 seconds")
+        val right = rightInput.toDF().toDF("rk", "rt")
+          .select($"rk", timestamp_seconds($"rt").as("rt"))
+          .withWatermark("rt", "10 seconds")
+        // A left row matches the right row whose time is `offset` seconds 
earlier.
+        val joined = left.join(right,
+          expr(s"lk = rk AND lt = $shiftedRightTime"), "left_outer")
+          .select($"lk", $"lt".cast("int"), $"rk", $"rt".cast("int"))
+        testStream(joined)(
+          MultiAddData(leftInput, (1, 100 + offset), (2, 90 + offset), (3, 145 
+ offset))(
+            rightInput, (9, 50)),
+          CheckNewAnswer(),
+          // The first batch has no previous eviction to start the V4 scan 
after.
+          Execute { query => assert(leftPreviousScanBound(query).isEmpty) },
+          AddData(rightInput, (1, 100)),
+          CheckNewAnswer(Row(1, 100 + offset, 1, 100)),
+          MultiAddData(leftInput, (9, 300))(rightInput, (9, 150)),
+          // At watermark 90, the left key cutoff is (90 + offset) s less the 
1 ms the solver
+          // subtracts for >=, so (2, 90 + offset) stays in state for one more 
batch.
+          CheckNewAnswer(),
+          // (4, 95) passes late filtering at 90 s. For offset 10 it is below 
the previous
+          // cutoff, 99.999 s, so the V4 scan must start after 90 s, not after 
that cutoff.
+          MultiAddData(leftInput, (4, 95))(rightInput, (9, 151)),
+          // At watermark 140, the left key cutoff is (140 + offset) s less 1 
ms.
+          CheckNewAnswer(Row(2, 90 + offset, null, null), Row(4, 95, null, 
null)),
+          Execute { query =>
+            val shiftedLateCutoff = 90000L + offset * 1000L - 1
+            assert(leftPreviousScanBound(query) === 
Some(math.min(shiftedLateCutoff, 90000L)))
+            // Retained left rows are above 140 + offset, retained right rows 
above 140 - offset.
+            
assert(joinExec(query).produceOutputWatermark(140000L).contains(129999L))
+          },
+          // Right time 145 is above watermark 140, so (3, 145 + offset) must 
still be in state.
+          AddData(rightInput, (3, 145)),
+          CheckNewAnswer(Row(3, 145 + offset, 3, 145)))
+      }
+    }
+  }
+
+  test("shifted key eviction scans from the start in legacy mode") {
+    withSQLConf(
+      SQLConf.STREAMING_JOIN_STATE_FORMAT_VERSION.key -> "4",
+      SQLConf.STATE_STORE_PROVIDER_CLASS.key -> 
classOf[RocksDBStateStoreProvider].getName,
+      SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> "false",
+      SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key -> "false") {
+      val leftInput = MemoryStream[(Int, Int)]
+      val rightInput = MemoryStream[(Int, Int)]
+      val left = leftInput.toDF().toDF("lk", "lt")
+        .select($"lk", timestamp_seconds($"lt").as("lt"))
+        .withWatermark("lt", "10 seconds")
+      val right = rightInput.toDF().toDF("rk", "rt")
+        .select($"rk", timestamp_seconds($"rt").as("rt"))
+        .withWatermark("rt", "10 seconds")
+      val joined = left.join(right, expr("lk = rk AND lt = rt + INTERVAL 10 
SECONDS"), "left_outer")
+        .select($"lk", $"lt".cast("int"), $"rk", $"rt".cast("int"))
+      testStream(joined)(
+        MultiAddData(leftInput, (1, 95), (8, 300))(rightInput, (9, 100)),
+        CheckNewAnswer(),
+        AddData(rightInput, (9, 120)),
+        // Legacy mode filters late rows and evicts at the same watermark, so 
it gives no earlier
+        // cutoff to start the V4 scan after.
+        CheckNewAnswer(Row(1, 95, null, null)),
+        Execute { query => assert(leftPreviousScanBound(query).isEmpty) })
+    }
+  }
+
+  for (version <- Seq(2, 3, 4)) {
+    test(s"key eviction on one side and value eviction on the other keep a 
match, 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, Long)]
+        val left = leftInput.toDF().toDF("leftId", "seconds")
+          .select($"leftId", timestamp_seconds($"seconds").as("leftTime"))
+          .withWatermark("leftTime", "1 hour")
+        val right = rightInput.toDF().toDF("rightId", "keySeconds", "seconds")
+          .select($"rightId", 
timestamp_seconds($"keySeconds").as("rightKeyTime"),
+            timestamp_seconds($"seconds").as("rightTime"))
+          .withWatermark("rightTime", "1 hour")
+        // The leftTime watermark bounds rightKeyTime, so the right side 
evicts by key, while the
+        // left side evicts on leftTime. The V4 left joiner derives a time 
window for its lookups
+        // into the right state, which must use the exact key timestamp 
instead.
+        val joined = left.join(right, expr(
+          "leftId = rightId AND leftTime = rightKeyTime AND " +
+            "rightTime >= leftTime + INTERVAL 10 SECONDS AND " +
+            "rightTime <= leftTime + INTERVAL 20 SECONDS"))
+          .select($"leftId", $"leftTime".cast("long"), 
$"rightTime".cast("long"))
+        testStream(joined)(
+          AddData(rightInput, (1, 100L, 115L)),
+          CheckNewAnswer(),
+          Execute { query =>
+            val join = query.lastExecution.executedPlan.collectFirst {
+              case j: StreamingSymmetricHashJoinExec => j
+            }.get
+            assert(join.stateWatermarkPredicates.left.exists(
+              _.isInstanceOf[JoinStateValueWatermarkPredicate]))
+            assert(join.stateWatermarkPredicates.right.exists(
+              _.isInstanceOf[JoinStateKeyWatermarkPredicate]))
+          },
+          AddData(leftInput, (1, 100L)),
+          CheckNewAnswer(Row(1, 100L, 115L)))
+      }
+    }
+  }
+
+  for (version <- Seq(2, 3, 4)) {
+    test(s"equality on a truncated opposite event time keeps matchable state, 
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("lk", "ms")
+          .select($"lk", timestamp_millis($"ms").as("lt"))
+          .withWatermark("lt", "10 seconds")
+        val right = rightInput.toDF().toDF("rk", "ms")
+          .select($"rk", timestamp_millis($"ms").as("rt"))
+          .withWatermark("rt", "10 seconds")
+        val joined = left.join(right,
+          expr("lk = rk AND lt = CAST(CAST(rt AS BIGINT) AS TIMESTAMP)"))
+          .select($"lk", $"rk")
+        testStream(joined)(
+          MultiAddData(leftInput, (1, 25000L))(rightInput, (9, 25000L)),
+          CheckNewAnswer(),
+          MultiAddData(leftInput, (8, 35500L))(rightInput, (9, 35500L)),
+          CheckNewAnswer(),
+          AddData(rightInput, (9, 35600L)),
+          CheckNewAnswer(),
+          // rt = 25.7 seconds is above the watermark 25.5 seconds but 
truncates to lt = 25.
+          AddData(rightInput, (1, 25700L)),
+          CheckNewAnswer(Row(1, 1)))
+      }
+    }
+  }
+
+  // (shift, watermark row, evicting row, right time, left time by zone, other 
left rows)
+  // Each left time is the right time shifted in that zone. In Los Angeles a 
day across the
+  // spring-forward change is 23 hours and across the fall-back change 25 
hours.
+  private val dayShifts = Seq(
+    // One day after 2024-03-09T20:00Z.
+    ("+ INTERVAL 1 DAY", 1710012600000L, 1710012660000L, 1710014400000L,
+      Map("UTC" -> 1710100800000L, "America/Los_Angeles" -> 1710097200000L), 
Nil),
+    // One day and 36 hours before 2024-11-03T20:00Z. The other left row keeps 
the left
+    // watermark above the right one.
+    ("- INTERVAL 1 DAY", 1730662200000L, 1730662260000L, 1730664000000L,
+      Map("UTC" -> 1730577600000L, "America/Los_Angeles" -> 1730574000000L),
+      Seq(1730678400000L)),
+    ("- INTERVAL 36 HOURS", 1730662200000L, 1730662260000L, 1730664000000L,
+      Map("UTC" -> 1730534400000L, "America/Los_Angeles" -> 1730530800000L),
+      Seq(1730678400000L)))
+
+  for {
+    version <- Seq(2, 3, 4)
+    zone <- Seq("America/Los_Angeles", "UTC")
+    (shift, watermarkRow, evictingRow, rightTime, leftTimes, otherLeftRows) <- 
dayShifts
+  } {
+    test(s"equality on an opposite event time $shift across DST, V$version 
$zone") {
+      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",
+        SQLConf.SESSION_LOCAL_TIMEZONE.key -> zone) {
+        val leftInput = MemoryStream[(Int, Long)]
+        val rightInput = MemoryStream[(Int, Long)]
+        val left = leftInput.toDF().toDF("lk", "ms")
+          .select($"lk", timestamp_millis($"ms").as("lt"))
+          .withWatermark("lt", "0 seconds")
+        val right = rightInput.toDF().toDF("rk", "ms")
+          .select($"rk", timestamp_millis($"ms").as("rt"))
+          .withWatermark("rt", "0 seconds")
+        val joined = left.join(right, expr(s"lk = rk AND lt = rt $shift"))
+          .select($"lk", $"rk")
+        val leftRows = (1, leftTimes(zone)) +: otherLeftRows.map(time => (8, 
time))
+        testStream(joined)(
+          StreamProgressLockedActions(Seq(
+            AddData(leftInput, leftRows: _*), AddData(rightInput, (9, 
watermarkRow)))),
+          CheckNewAnswer(),
+          // Evicts at the right watermark, which is below rightTime.
+          AddData(rightInput, (9, evictingRow)),
+          CheckNewAnswer(),
+          AddData(rightInput, (1, rightTime)),
+          CheckNewAnswer(Row(1, 1)))
+      }
+    }
+  }
+
+  // A V4 input whose key is not its own event time is stored at the key 
timestamp only when the
+  // opposite key bounds that key. A restart may change the session time zone, 
which the offset
+  // log does not keep, so that choice must not depend on it: otherwise rows 
stored before the
+  // restart are looked up at another timestamp and no longer match.
+  for {
+    (shift, keyOffset) <- Seq(("+ INTERVAL 1 DAY", 86400000L), ("- INTERVAL 1 
DAY", -86400000L))
+    (firstZone, secondZone) <- Seq(("America/Los_Angeles", "UTC"), ("UTC", 
"America/Los_Angeles"))
+  } {
+    test(s"V4 keeps matching k = rt $shift after a restart from $firstZone to 
$secondZone") {
+      val leftInput = MemoryStream[(Int, Long)]
+      val rightInput = MemoryStream[(Int, Long)]
+      def joined(zone: String): DataFrame = {
+        var df: DataFrame = null
+        withSQLConf(SQLConf.SESSION_LOCAL_TIMEZONE.key -> zone) {
+          val left = leftInput.toDF().toDF("lk", "ms")
+            .select($"lk", timestamp_millis($"ms").as("k"))
+          val right = rightInput.toDF().toDF("rk", "ms")
+            .select($"rk", timestamp_millis($"ms").as("rt"))
+            .withWatermark("rt", "0 seconds")
+          df = left.join(right, expr(s"lk = rk AND k = rt 
$shift")).select($"lk", $"rk")
+        }
+        df
+      }
+      // 2024-01-15T00:00Z. January has no daylight saving change, so a day is 
24 hours in both
+      // zones.
+      val rightTime = 1705276800000L
+      def run(zone: String, checkpoint: String)(actions: StreamAction*): Unit =
+        withSQLConf(
+          SQLConf.STREAMING_JOIN_STATE_FORMAT_VERSION.key -> "4",
+          SQLConf.STATE_STORE_PROVIDER_CLASS.key -> 
classOf[RocksDBStateStoreProvider].getName,
+          SQLConf.SESSION_LOCAL_TIMEZONE.key -> zone) {
+          testStream(joined(zone))(StartStream(checkpointLocation = 
checkpoint) +: actions: _*)
+        }
+      withTempDir { dir =>
+        val checkpoint = dir.getCanonicalPath
+        run(firstZone, checkpoint)(
+          AddData(leftInput, (1, rightTime + keyOffset)), CheckNewAnswer(), 
StopStream)
+        run(secondZone, checkpoint)(AddData(rightInput, (1, rightTime)), 
CheckNewAnswer(Row(1, 1)))
+      }
+    }
+  }
+
+  for (version <- Seq(2, 4)) {
+    test(s"lookup key ordinals are not derived in every task, V$version") {
+      // A shifted key makes the lookup ordinal run the cutoff solver, which 
logs each cutoff it
+      // derives. Planning derives the same cutoffs whatever the number of 
partitions.
+      def solverLogLines(numPartitions: Int): Int = {
+        val logAppender = new LogAppender("stream-stream join state 
constraints")
+        withLogAppender(logAppender,
+            loggerNames = 
Seq(StreamingJoinHelper.getClass.getName.stripSuffix("$")),
+            level = Some(Level.INFO)) {
+          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",
+              SQLConf.SHUFFLE_PARTITIONS.key -> numPartitions.toString) {
+            val leftInput = MemoryStream[(Int, Int)]
+            val rightInput = MemoryStream[(Int, Int)]
+            val left = leftInput.toDF().toDF("lk", "t")
+              .select($"lk", timestamp_seconds($"t").as("lt"))
+              .withWatermark("lt", "0 seconds")
+            val right = rightInput.toDF().toDF("rk", "t")
+              .select($"rk", timestamp_seconds($"t").as("rt"))
+              .withWatermark("rt", "0 seconds")
+            val joined = left.join(right, expr("lk = rk AND lt = rt + INTERVAL 
10 SECONDS"))
+              .select($"lk", $"lt".cast("long"), $"rt".cast("long"))
+            testStream(joined)(
+              MultiAddData(leftInput, (1, 20))(rightInput, (1, 10)),
+              CheckNewAnswer(Row(1, 20L, 10L)),
+              MultiAddData(leftInput, (2, 40))(rightInput, (2, 30)),
+              CheckNewAnswer(Row(2, 40L, 30L)))
+          }
+        }
+        
logAppender.loggingEvents.count(_.getMessage.getFormattedMessage.contains(
+          "Final expression to evaluate constraint"))
+      }
+      assert(solverLogLines(numPartitions = 1) === 
solverLogLines(numPartitions = 5))

Review Comment:
   **Nit (P3):** If the solver's INFO line is reworded, logged at another level 
or emitted under another logger, both counts are 0 and this assertion passes 
for any implementation, including one that derives the V4 lookup ordinals in 
every task. Asserting that the single-partition run logs at least one line 
keeps the comparison meaningful.
   
   ```suggestion
         val singlePartitionLines = solverLogLines(numPartitions = 1)
         assert(singlePartitionLines > 0)
         assert(singlePartitionLines === solverLogLines(numPartitions = 5))
   ```
   
   **Verification:**
   - **Regression:** The lookup-ordinal test fails when the solver's INFO line 
is reworded or not emitted, and passes with the current solver for state 
formats 2 and 4.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -147,7 +155,9 @@ case class StreamingSymmetricHashJoinExec(
     stateFormatVersion: Int,
     left: SparkPlan,
     right: SparkPlan,
-    outputMode: Option[OutputMode])
+    outputMode: Option[OutputMode],
+    outputWatermarkSides: Option[Set[JoinSide]] = None,
+    eventTimeCopies: EventTimeCopies = EventTimeCopies.empty)

Review Comment:
   **Nit (P3):** `TreeNode.argString` prints this field through `case other => 
other :: Nil`. The simple string of every stream-stream join therefore ends 
with `EventTimeCopies(Set())` when multiple stateful operators are allowed, and 
in legacy mode with pairs such as `(ExprId(12,<uuid>),ExprId(10,<uuid>))`, 
whose UUIDs change from one JVM to the next. The neighboring 
`JoinStateWatermarkPredicates` override `toString` for this reason. Leaving the 
field out when it is empty and printing pairs as `#12 -> #10` would keep plans 
readable.
   
   **Verification:**
   - **Behavior:** The plan string of a planned stream-stream join has no 
copy-pair argument when multiple stateful operators are allowed, and in legacy 
mode shows each accepted pair by the expression ID numbers of the key and the 
event time.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala:
##########
@@ -630,6 +671,231 @@ 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 =>
+          Seq(f.child)
+        case t: TransformWithStateExec if t.timeMode == TimeMode.EventTime() 
=> Seq(t.child)
+        case t: TransformWithStateInPySparkExec if t.timeMode == 
TimeMode.EventTime() =>
+          Seq(t.child)
+        case _ => Nil
+      }
+
+      plan.flatMap { consumer =>
+        watermarkedInputs(consumer).flatMap { input =>
+          Try(WatermarkSupport.findEventTimeColumn(input.output,
+            allowMultipleEventTimeColumns = 
false)).toOption.flatten.toSeq.flatMap { column =>
+            findJoinSides(input, column).map { case (joinOperatorId, side, 
joinEventTime) =>
+              JoinWatermarkConsumer(consumer, joinOperatorId, side, 
joinEventTime)
+            }
+          }
+        }
+      }
+    }
+
+    /**
+     * Tell each stream-stream join which inputs' event times reach the 
stateful operator that
+     * consumes its output watermark, so that the join holds back that 
watermark only for those
+     * inputs' state. A join without a traced consumer holds back for both 
inputs.
+     */
+    private def withJoinOutputWatermarkSides(plan: SparkPlan): SparkPlan = {
+      val sides = 
joinWatermarkConsumers(plan).groupMap(_.joinOperatorId)(_.side)
+      if (sides.isEmpty) {
+        plan
+      } else {
+        plan transform {
+          case j: StreamingSymmetricHashJoinExec
+              if j.stateInfo.exists(info => sides.contains(info.operatorId)) =>
+            j.copy(outputWatermarkSides = 
Some(sides(j.stateInfo.get.operatorId).toSet))
+        }
+      }
+    }
+
+    /**
+     * Reject an append-mode aggregation whose event time comes from a 
stream-stream join input
+     * that the join cannot bound: the join holds back its output watermark 
for that input, so
+     * the aggregation would never emit a result. Only an aggregation that the 
tracer of
+     * [[joinWatermarkConsumers]] reaches fails; with the finalization check 
disabled, it is only
+     * logged.
+     */
+    private def checkJoinOutputWatermarkConsumers(plan: SparkPlan): Unit = {
+      val joins = plan.collect {
+        case j: StreamingSymmetricHashJoinExec if j.stateInfo.isDefined =>
+          j.stateInfo.get.operatorId -> j
+      }.toMap
+      // A bounded input's state watermark advances with the input watermark; 
an input the join
+      // cannot bound contributes 0 at every input watermark.
+      def holdsOutputWatermark(join: StreamingSymmetricHashJoinExec, side: 
JoinSide): Boolean = {
+        Seq(1000000L, 2000000L).forall { inputWatermark =>
+          val (left, right) = 
StreamingSymmetricHashJoinHelper.getStateWatermark(
+            join.left.output, join.right.output, join.leftKeys, join.rightKeys,
+            join.condition.full, Some(inputWatermark), 
!allowMultipleStatefulOperators)
+          (if (side == LeftSide) left else right).contains(0L)
+        }
+      }
+      def isAppendAggregation(consumer: SparkPlan): Boolean = consumer match {
+        case s: StateStoreSaveExec => 
s.outputMode.contains(OutputMode.Append())
+        case s: SessionWindowStateStoreSaveExec => 
s.outputMode.contains(OutputMode.Append())
+        case s: StatefulStreamlineAggregateExec => 
s.outputMode.contains(OutputMode.Append())
+        case _ => false
+      }
+      joinWatermarkConsumers(plan).distinct.foreach {
+        case JoinWatermarkConsumer(consumer, joinOperatorId, side, eventTime)
+            if isAppendAggregation(consumer) &&
+              joins.get(joinOperatorId).exists(holdsOutputWatermark(_, side)) 
=>
+          val join = joins(joinOperatorId)
+          val (other, otherOutput) =
+            if (side == LeftSide) ("right", join.right.output) else ("left", 
join.left.output)
+          val constraint = s"a time constraint that limits how late a matching 
$other row can " +
+            "arrive"
+          val requirement =
+            if 
(otherOutput.exists(_.metadata.contains(EventTimeWatermark.delayKey))) {
+              constraint
+            } else {
+              s"a watermark on the $other input and $constraint"
+            }
+          val error = new AnalysisException(
+            errorClass = "STREAMING_JOIN_UNBOUNDED_DOWNSTREAM_EVENT_TIME",
+            messageParameters = Map(
+              "eventTime" -> eventTime.name,
+              "side" -> side.toString,
+              "requirement" -> requirement,

Review Comment:
   **Nit (P3):** `requirement` is built here as either "a time constraint that 
limits how late a matching <other> row can arrive" or that clause preceded by a 
request for a watermark on the other input. 
`common/utils/src/main/resources/error/README.md` says that the values passed 
to a message should not themselves be messages. The other conditions this stack 
adds keep their wording in `error-conditions.json`. Two sub-conditions, one per 
case, with the other input's side as a parameter, would render the same text. 
Once the condition ships, that fix changes its parameters.
   
   **Verification:**
   - **Behavior:** An append-mode aggregation after a left outer join whose 
right input has no watermark fails at start with the sub-condition that asks 
for a watermark and a time constraint, and one whose right input has a 
watermark fails with the sub-condition that asks for a time constraint; each 
check covers the error's parameters and message.



##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinLegacyEventTimeKeySuite.scala:
##########
@@ -0,0 +1,332 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.streaming
+
+import org.apache.spark.sql.{AnalysisException, DataFrame, Row}
+import org.apache.spark.sql.catalyst.analysis.StreamingJoinHelper
+import org.apache.spark.sql.catalyst.plans.Inner
+import org.apache.spark.sql.catalyst.plans.logical.{Join, JoinHint, Union}
+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
+
+/**
+ * With spark.sql.streaming.statefulOperator.allowMultiple=false, an input 
filters late rows by
+ * its first watermarked column. An equality key on a later watermarked column 
bounds the other
+ * input's state only when the input builds it from that first column, as a 
copy or as a
+ * tumbling or sliding time window.
+ */
+class StreamingJoinLegacyEventTimeKeySuite extends StreamTest {
+  import testImplicits._
+
+  private val legacyMode = SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key -> 
"false"
+
+  /** Adds the key column `<side>w` to an input whose event time is `<side>t`. 
*/
+  private type KeyBuilder = (DataFrame, String) => DataFrame
+
+  private val tumbling: KeyBuilder =
+    (df, side) => df.withColumn(s"${side}w", window(col(s"${side}t"), "10 
seconds"))
+  private val sliding: KeyBuilder =
+    (df, side) => df.withColumn(s"${side}w", window(col(s"${side}t"), "10 
seconds", "5 seconds"))
+  private val copy: KeyBuilder = (df, side) => df.withColumn(s"${side}w", 
col(s"${side}t"))
+  private val copyThenWindow: KeyBuilder = (df, side) =>
+    df.withColumn(s"${side}c", col(s"${side}t"))
+      .withColumn(s"${side}w", window(col(s"${side}c"), "10 seconds"))
+  private val renamedWindow: KeyBuilder = (df, side) =>
+    df.withColumn(s"${side}x", window(col(s"${side}t"), "10 seconds"))
+      .filter(col(s"${side}k") >= 0)
+      .withColumnRenamed(s"${side}x", s"${side}w")
+  // A window over the event time less 20 seconds, in a column that keeps the 
event time's
+  // watermark metadata. Its end can be at or below the watermark while the 
event time is above.
+  private val shiftedWindow: KeyBuilder = (df, side) => {
+    val time = s"${side}t"
+    df.select(col("*"),
+        (col(time) - expr("INTERVAL 20 SECONDS")).as(s"${side}s", 
df.schema(time).metadata))
+      .withColumn(s"${side}w", window(col(s"${side}s"), "10 seconds"))
+  }
+  private val sessionWindow: KeyBuilder =
+    (df, side) => df.withColumn(s"${side}w", session_window(col(s"${side}t"), 
"10 seconds"))
+
+  private def eventTimeInput(memory: MemoryStream[(Int, Int)], side: String): 
DataFrame =
+    memory.toDF().toDF(s"${side}k", "time")
+      .select(col(s"${side}k"), timestamp_seconds($"time").as(s"${side}t"))
+      .withWatermark(s"${side}t", "1 second")
+
+  private def keyed(memory: MemoryStream[(Int, Int)], side: String, key: 
KeyBuilder): DataFrame =
+    key(eventTimeInput(memory, side), side)
+      .select(col(s"${side}k"), col(s"${side}t"), col(s"${side}w"))
+
+  /** The (key, event time) pairs that the shared rule accepts, by column 
name. */
+  private def eventTimeCopies(df: DataFrame): Set[(String, String)] = {
+    val plan = df.queryExecution.analyzed
+    val names = plan.flatMap(_.output).map(a => a.exprId -> a.name).toMap
+    StreamingJoinHelper.findEventTimeCopies(plan).pairs.map { case (key, 
eventTime) =>
+      (names(key), names(eventTime))
+    }
+  }
+
+  private def joinWithRight(left: DataFrame, key: KeyBuilder = tumbling): 
DataFrame =
+    left.join(keyed(MemoryStream[(Int, Int)], "r", key), expr("lk = rk AND lw 
= rw"))
+
+  Seq(
+    "tumbling window" -> tumbling,
+    "sliding window" -> sliding,
+    "copy" -> copy,
+    "window over a copy" -> copyThenWindow,
+    "renamed window after a filter" -> renamedWindow).foreach { case (name, 
key) =>
+    test(s"$name of the event time after it is accepted") {
+      val copies = eventTimeCopies(joinWithRight(keyed(MemoryStream[(Int, 
Int)], "l", key), key))
+      assert(copies.contains(("lw", "lt")))
+      assert(copies.contains(("rw", "rt")))
+    }
+  }
+
+  test("window over a shifted time is not accepted") {
+    val left = shiftedWindow(eventTimeInput(MemoryStream[(Int, Int)], "l"), 
"l")
+    val copies = eventTimeCopies(joinWithRight(left))
+    assert(!copies.contains(("lw", "lt")))
+    assert(!copies.contains(("ls", "lt")))
+    // The window is over ls itself, which late filtering does not use while 
lt comes first.
+    assert(copies.contains(("lw", "ls")))
+  }
+
+  test("session window is not accepted") {
+    val copies = eventTimeCopies(joinWithRight(keyed(MemoryStream[(Int, Int)], 
"l", sessionWindow)))
+    assert(!copies.exists(_._1 == "lw"))
+  }
+
+  test("window over another input's event time is not accepted") {
+    val a = MemoryStream[(Int, Int)]
+    val b = MemoryStream[(Int, Int)]
+    val left = eventTimeInput(a, "a").join(eventTimeInput(b, "b"), expr("ak = 
bk AND at = bt"))
+      .withColumn("lk", $"ak")
+      .withColumn("lw", window($"bt", "10 seconds"))
+    val copies = eventTimeCopies(joinWithRight(left))
+    // The left input filters late rows by at, but the window is over bt.
+    assert(!copies.contains(("lw", "at")))
+    assert(copies.contains(("lw", "bt")))
+  }
+
+  test("union is accepted only when every input builds the key from the same 
position") {
+    def union(first: KeyBuilder, second: KeyBuilder): DataFrame =
+      keyed(MemoryStream[(Int, Int)], "l", first)
+        .union(keyed(MemoryStream[(Int, Int)], "l", second))
+    assert(eventTimeCopies(joinWithRight(union(tumbling, 
sliding))).contains(("lw", "lt")))
+    assert(!eventTimeCopies(joinWithRight(union(tumbling, 
shiftedWindow))).contains(("lw", "lt")))
+    assert(!eventTimeCopies(joinWithRight(union(shiftedWindow, 
tumbling))).contains(("lw", "lt")))
+  }
+
+  test("a pair rejected by one join input is rejected for every join") {
+    // The second join's left input is a union whose first input is the first 
join's input, so
+    // both inputs output the same expression IDs, but only the first builds 
the window from lt.
+    val windowed = keyed(MemoryStream[(Int, Int)], "l", 
tumbling).queryExecution.analyzed
+    val shifted = keyed(MemoryStream[(Int, Int)], "l", 
shiftedWindow).queryExecution.analyzed
+    val right = keyed(MemoryStream[(Int, Int)], "r", 
tumbling).queryExecution.analyzed
+    val first = Join(windowed, right, Inner, None, JoinHint.NONE)
+    val second = Join(Union(Seq(windowed, shifted)), right, Inner, None, 
JoinHint.NONE)
+    val Seq(_, lt, lw) = windowed.output
+    val pair = (lw.exprId, lt.exprId)
+    assert(StreamingJoinHelper.findEventTimeCopies(first).pairs.contains(pair))
+    
assert(!StreamingJoinHelper.findEventTimeCopies(second).pairs.contains(pair))
+    assert(!StreamingJoinHelper.findEventTimeCopies(Union(Seq(first, 
second))).pairs
+      .contains(pair))
+  }
+
+  // Batches of left and right rows of (key, seconds), with 10-second windows. 
The watermark is
+  // 30 seconds in the third batch, so it finalizes the rows at 5 and 6 
seconds, whose windows end
+  // by 15 seconds, and keeps those at 31 and 40 seconds.
+  private def legacyJoin(
+      joinType: String,
+      key: KeyBuilder,
+      windowsPerRow: Int,
+      version: Int,
+      restart: Boolean): Unit = {
+    withSQLConf(legacyMode,
+        SQLConf.STREAMING_JOIN_STATE_FORMAT_VERSION.key -> version.toString,
+        SQLConf.STATE_STORE_PROVIDER_CLASS.key -> 
classOf[RocksDBStateStoreProvider].getName,
+        SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> "false") {
+      val leftInput = MemoryStream[(Int, Int)]
+      val rightInput = MemoryStream[(Int, Int)]
+      val joined = keyed(leftInput, "l", key)
+        .join(keyed(rightInput, "r", key), expr("lk = rk AND lw = rw"), 
joinType)
+      val (result, matched, unmatchedLeft) = if (joinType == "left_semi") {
+        (joined.select($"lk", $"lt".cast("int")), Row(1, 5), Nil)
+      } else {
+        val unmatched = if (joinType == "left_outer" || joinType == 
"full_outer") {
+          Seq(Row(2, 6, null, null))
+        } else {
+          Nil
+        }
+        (joined.select($"lk", $"lt".cast("int"), $"rk", $"rt".cast("int")), 
Row(1, 5, 1, 5),
+          unmatched)
+      }
+      def times(rows: Seq[Row]): Seq[Row] = 
rows.flatMap(Seq.fill(windowsPerRow)(_))
+      withTempDir { checkpoint =>
+        val start = StartStream(checkpointLocation = 
checkpoint.getCanonicalPath)
+        val restartActions = if (restart) Seq(StopStream, start) else Nil
+        testStream(result)((Seq(
+          start,
+          MultiAddData(leftInput, (1, 5), (2, 6))(rightInput, (1, 5)),
+          CheckNewAnswer(times(Seq(matched)): _*),
+          MultiAddData(leftInput, (3, 31))(rightInput, (9, 31)),
+          CheckNewAnswer()) ++ restartActions ++ Seq(
+          AddData(rightInput, (9, 40)),
+          CheckNewAnswer(times(unmatchedLeft): _*),
+          // Only the rows at 31 and 40 seconds stay, as in Spark 4.3. Without 
the bound, all
+          // six rows would stay in state.
+          Execute { query =>
+            assert(query.lastProgress.stateOperators.head.numRowsTotal === 3 * 
windowsPerRow)
+          })): _*)
+      }
+    }
+  }
+
+  for {
+    (keyName, key, windowsPerRow) <- Seq(
+      ("tumbling window", tumbling, 1), ("sliding window", sliding, 2), 
("copy", copy, 1))
+    joinType <- Seq("inner", "left_outer", "right_outer", "full_outer", 
"left_semi")
+    version <- Seq(2, 3)
+  } {
+    test(s"legacy-mode $joinType join on a $keyName after the event time 
evicts by it, " +
+        s"V$version") {
+      legacyJoin(joinType, key, windowsPerRow, version, restart = false)
+    }
+  }
+
+  for {
+    joinType <- Seq("left_outer", "full_outer")
+    version <- Seq(2, 3)
+  } {
+    test(s"legacy-mode $joinType join on a window after the event time evicts 
after a " +
+        s"restart, V$version") {
+      legacyJoin(joinType, tumbling, 1, version, restart = true)
+    }
+  }
+
+  // The V4 state manager accepts one event-time column per input, as in Spark 
4.3, so these
+  // inputs keep failing there whichever key bounds them.
+  test("legacy-mode V4 join on an input with a window after the event time 
still fails") {
+    withSQLConf(legacyMode,
+        SQLConf.STREAMING_JOIN_STATE_FORMAT_VERSION.key -> "4",
+        SQLConf.STATE_STORE_PROVIDER_CLASS.key -> 
classOf[RocksDBStateStoreProvider].getName) {
+      val leftInput = MemoryStream[(Int, Int)]
+      val rightInput = MemoryStream[(Int, Int)]
+      val joined = keyed(leftInput, "l", tumbling)
+        .join(keyed(rightInput, "r", tumbling), expr("lk = rk AND lw = rw"))
+      testStream(joined)(
+        MultiAddData(leftInput, (1, 5))(rightInput, (1, 5)),
+        ExpectFailure[AnalysisException](assertFailure = error =>
+          assert(error.getMessage.contains("MULTIPLE_EVENT_TIME_COLUMNS"))))
+    }
+  }
+
+  for (version <- Seq(2, 3)) {
+    test(s"legacy-mode inner join on a window over a shifted time keeps rows 
that can still " +
+        s"match, V$version") {
+      withSQLConf(legacyMode,
+          SQLConf.STREAMING_JOIN_STATE_FORMAT_VERSION.key -> version.toString,
+          SQLConf.STATE_STORE_PROVIDER_CLASS.key -> 
classOf[RocksDBStateStoreProvider].getName,
+          SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> "false") {
+        val leftInput = MemoryStream[(Int, Int)]
+        val rightInput = MemoryStream[(Int, Int)]
+        val joined = keyed(leftInput, "l", shiftedWindow)
+          .join(keyed(rightInput, "r", shiftedWindow), expr("lk = rk AND lw = 
rw"))
+          .select($"lk", $"lt".cast("int"), $"rk", $"rt".cast("int"))
+        testStream(joined)(
+          MultiAddData(leftInput, (1, 55))(rightInput, (9, 50)),
+          CheckNewAnswer(),
+          // The watermark is 49 seconds. The window of (1, 55) is [30, 40), 
so evicting by the
+          // window end would remove it here.
+          AddData(rightInput, (9, 51)),
+          CheckNewAnswer(),
+          // (1, 56) is above the watermark of 50 seconds and has the same 
window.
+          AddData(rightInput, (1, 56)),
+          CheckNewAnswer(Row(1, 55, 1, 56)))
+      }
+    }
+  }
+
+  private def assertLegacyWindowHint(left: DataFrame, right: DataFrame): Unit 
= {
+    withSQLConf(legacyMode) {
+      val error = intercept[AnalysisException] {
+        testStream(left.join(right, expr("lk = rk AND lw = rw"), 
"left_outer"))(
+          StartStream(), CheckNewAnswer())
+      }
+      assert(error.getMessage.contains("the right input filters late rows by 
its first " +
+        "watermarked column, rt, so its window key rw is a time constraint 
only if that input " +
+        "computes it as a tumbling or sliding window over rt itself"))
+    }
+  }
+
+  test("legacy-mode left outer join on a window over a shifted time fails 
analysis") {
+    assertLegacyWindowHint(keyed(MemoryStream[(Int, Int)], "l", tumbling),
+      keyed(MemoryStream[(Int, Int)], "r", shiftedWindow))
+  }
+
+  test("legacy-mode left outer join on a session window fails analysis") {
+    assertLegacyWindowHint(keyed(MemoryStream[(Int, Int)], "l", tumbling),
+      keyed(MemoryStream[(Int, Int)], "r", sessionWindow))
+  }
+
+  test("legacy-mode left outer join on a union of different windows fails 
analysis") {
+    val right = keyed(MemoryStream[(Int, Int)], "r", tumbling)
+      .union(keyed(MemoryStream[(Int, Int)], "r", shiftedWindow))
+    assertLegacyWindowHint(keyed(MemoryStream[(Int, Int)], "l", tumbling), 
right)
+  }
+
+  test("default-mode left outer join on a window after the event time still 
fails analysis") {
+    val error = intercept[AnalysisException] {
+      val joined = keyed(MemoryStream[(Int, Int)], "l", tumbling)
+        .join(keyed(MemoryStream[(Int, Int)], "r", tumbling), expr("lk = rk 
AND lw = rw"),
+          "left_outer")
+      testStream(joined)(StartStream(), CheckNewAnswer())
+    }
+    assert(error.getMessage.contains("allow unmatched state to be finalized"))
+    
assert(!error.getMessage.contains(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key))
+  }
+
+  test("legacy-mode join fails at start when the planned input filters late 
rows by " +

Review Comment:
   **Nit (P3):** This is the only test that raises 
`STREAMING_JOIN_EVENT_TIME_KEY_NOT_PLANNED`, and it runs a right outer join 
with `spark.sql.streaming.join.checkFinalization.enabled` at its default. 
Throwing in the branch that should only log, inverting the conf test, or giving 
the `LeftOuter | LeftSemi` arm the right input's predicate would still pass 
every suite. No test runs a left outer, left semi or full outer join, or the 
disabled conf, through the check.
   
   See **Shared repair plan 1** in the review body.



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