HeartSaVioR commented on code in PR #60280:
URL: https://github.com/apache/spark/pull/60280#discussion_r4536394725


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -224,98 +228,218 @@ object StreamingSymmetricHashJoinHelper extends Logging {
     WatermarkSupport.findEventTimeColumn(rightAttributes,
       allowMultipleEventTimeColumns = useFirstEventTimeColumn)
 
-    val joinKeyOrdinalForWatermark: Option[Int] = 
findJoinKeyOrdinalForWatermark(
-      leftKeys, rightKeys)
-
     def getOneSideStateWatermarkPredicate(
         oneSideInputAttributes: Seq[Attribute],
         oneSideJoinKeys: Seq[Expression],
-        otherSideInputAttributes: Seq[Attribute]): 
Option[JoinStateWatermarkPredicate] = {
+        otherSideInputAttributes: Seq[Attribute],
+        otherSideJoinKeys: Seq[Expression]): 
Option[JoinStateWatermarkPredicate] = {
+      // State is bounded by future input from the opposite side, not by its 
own watermark.
+      val joinKeyOrdinalForWatermark = 
StreamingJoinHelper.getStateKeyWatermarkOrdinal(
+        otherSideJoinKeys, otherSideInputAttributes)
       val isWatermarkDefinedOnInput = 
oneSideInputAttributes.exists(_.metadata.contains(delayKey))
       val isWatermarkDefinedOnJoinKey = joinKeyOrdinalForWatermark.isDefined
 
       if (isWatermarkDefinedOnJoinKey) { // case 1 and 3 in the 
StreamingSymmetricHashJoinExec docs
+        val ordinal = joinKeyOrdinalForWatermark.get
         val keyExprWithWatermark = BoundReference(
-          joinKeyOrdinalForWatermark.get,
-          oneSideJoinKeys(joinKeyOrdinalForWatermark.get).dataType,
-          oneSideJoinKeys(joinKeyOrdinalForWatermark.get).nullable)
-        val expr = watermarkExpression(Some(keyExprWithWatermark), 
eventTimeWatermarkForEviction)
-        expr.map { e =>
-          // V4 can skip keys at or below the previous watermark only if 
late-input filtering
-          // rejects new rows in that range on this same key. A watermark on 
the other input's
-          // equality key can drive eviction even when this input has no 
watermark, or has one
-          // on a different column. New rows can then pass late-input 
filtering with keys
-          // already eligible for eviction. V4 must scan from the beginning to 
find them;
-          // otherwise, outer joins can fail to emit null rows for these 
unmatched inputs.
-          val prevStateKeyWatermark =
-            if (oneSideInputAttributes.find(_.metadata.contains(delayKey))
-              
.exists(oneSideJoinKeys(joinKeyOrdinalForWatermark.get).semanticEquals)) {
-              eventTimeWatermarkForLateEvents
-            } else {
-              None
-            }
-          // watermarkExpression only provides the expression when 
eventTimeWatermarkForEviction
-          // is defined.
-          JoinStateKeyWatermarkPredicate(
-            e,
-            eventTimeWatermarkForEviction.get,
-            prevStateKeyWatermark)
+          ordinal, oneSideJoinKeys(ordinal).dataType, 
oneSideJoinKeys(ordinal).nullable)
+        // The opposite watermark bounds this key, shifted by an exact 
constant in the opposite
+        // key. See StreamingJoinHelper.getStateKeyWatermark for the shifts it 
accepts.
+        def keyWatermark(watermark: Option[Long]): Option[Long] =
+          StreamingJoinHelper.getStateKeyWatermark(
+            otherSideJoinKeys, otherSideInputAttributes, ordinal, watermark)
+        keyWatermark(eventTimeWatermarkForEviction).flatMap { stateWatermark =>
+          watermarkExpression(Some(keyExprWithWatermark), 
Some(stateWatermark)).map { e =>
+            // V4 can skip keys at or below the previous watermark only if 
late-input filtering
+            // rejects new rows in that range on this same key. A watermark on 
the other input's
+            // equality key can drive eviction even when this input has no 
watermark, or has one
+            // on a different column. New rows can then pass late-input 
filtering with keys
+            // already eligible for eviction. V4 must scan from the beginning 
to find them;
+            // otherwise, outer joins can fail to emit null rows for these 
unmatched inputs.
+            val prevStateKeyWatermark =
+              if (oneSideInputAttributes.find(_.metadata.contains(delayKey))
+                .exists(oneSideJoinKeys(ordinal).semanticEquals)) {
+                // Late filtering drops new keys at or below the late-input 
watermark, and the
+                // previous batch evicted keys up to its cutoff, which is the 
cutoff at that
+                // watermark. A shifted cutoff can lie on either side of the 
watermark, so the
+                // scan starts after the lower of the two.
+                eventTimeWatermarkForLateEvents.flatMap { lateWatermark =>
+                  keyWatermark(Some(lateWatermark)).map(math.min(_, 
lateWatermark))
+                }
+              } else {
+                None
+              }
+            JoinStateKeyWatermarkPredicate(e, stateWatermark, 
prevStateKeyWatermark)
+          }
         }
       } else if (isWatermarkDefinedOnInput) { // case 2 in the 
StreamingSymmetricHashJoinExec docs
-        val stateValueWatermark = StreamingJoinHelper.getStateValueWatermark(
-          attributesToFindStateWatermarkFor = 
AttributeSet(oneSideInputAttributes),
-          attributesWithEventWatermark = 
AttributeSet(otherSideInputAttributes),
-          condition,
-          eventTimeWatermarkForEviction)
-        // A row can pass late-input filtering but already be eligible for 
eviction in this batch.
-        // When the previous join-derived state cutoff is ahead of the 
late-input watermark, a new
-        // row can fall at or below that cutoff. V4 must scan from the 
beginning to find such rows.
-        val prevStateValueWatermark = eventTimeWatermarkForLateEvents.flatMap 
{ lateWatermark =>
-          StreamingJoinHelper.getStateValueWatermark(
-            attributesToFindStateWatermarkFor = 
AttributeSet(oneSideInputAttributes),
-            attributesWithEventWatermark = 
AttributeSet(otherSideInputAttributes),
-            condition,
-            eventTimeWatermarkForLateEvents).filter(_ <= lateWatermark)
-        }
-        val inputAttributeWithWatermark = 
oneSideInputAttributes.find(_.metadata.contains(delayKey))
-        val expr = watermarkExpression(inputAttributeWithWatermark, 
stateValueWatermark)
-        expr.map { e =>
-          // watermarkExpression only provides the expression when 
eventTimeWatermarkForEviction
-          // is defined
-          JoinStateValueWatermarkPredicate(e, stateValueWatermark.get, 
prevStateValueWatermark)
+        getStateValueWatermarkForInput(oneSideInputAttributes, 
otherSideInputAttributes,
+          condition, eventTimeWatermarkForEviction).flatMap { case (attribute, 
watermark) =>
+          // Late filtering only constrains the input's event-time column. A 
different indexed
+          // column can admit values below the previous cutoff and must be 
scanned from the start.
+          val prevStateValueWatermark = eventTimeWatermarkForLateEvents.filter 
{ _ =>
+            oneSideInputAttributes.find(_.metadata.contains(delayKey))
+              .exists(_.semanticEquals(attribute))
+          }.flatMap { lateWatermark =>
+            // Also scan from the start if the derived cutoff exceeds the 
late-input watermark.
+            
StreamingJoinHelper.getStateValueWatermark(AttributeSet(Seq(attribute)),
+              AttributeSet(otherSideInputAttributes), condition, 
Some(lateWatermark))
+              .filter(_ <= lateWatermark)
+          }
+          watermarkExpression(Some(attribute), Some(watermark)).map { e =>
+            JoinStateValueWatermarkPredicate(e, watermark, 
prevStateValueWatermark)
+          }
         }
       } else {
         None
       }
     }
 
     val leftStateWatermarkPredicate =
-      getOneSideStateWatermarkPredicate(leftAttributes, leftKeys, 
rightAttributes)
+      getOneSideStateWatermarkPredicate(leftAttributes, leftKeys, 
rightAttributes, rightKeys)
     val rightStateWatermarkPredicate =
-      getOneSideStateWatermarkPredicate(rightAttributes, rightKeys, 
leftAttributes)
+      getOneSideStateWatermarkPredicate(rightAttributes, rightKeys, 
leftAttributes, leftKeys)
     JoinStateWatermarkPredicates(leftStateWatermarkPredicate, 
rightStateWatermarkPredicate)
   }
 
-  private[join] def findJoinKeyOrdinalForWatermark(
+  /** Keep each cutoff attached to the column constrained by the join 
condition. */
+  private def getStateValueWatermarkForInput(
+      inputAttributes: Seq[Attribute],
+      otherInputAttributes: Seq[Attribute],
+      condition: Option[Expression],
+      eventWatermark: Option[Long]): Option[(Attribute, Long)] = {
+    val eventTime = inputAttributes.find(_.metadata.contains(delayKey))
+    // First try the watermarked column. If it has no inferable bound, try the 
other timestamp
+    // columns in input schema order and use the first with a bound. This 
makes the indexed column
+    // deterministic for a fixed input schema and join condition.
+    val candidates = eventTime.toSeq ++ inputAttributes.filter { attribute =>
+      attribute.dataType == TimestampType && 
!eventTime.exists(_.semanticEquals(attribute))
+    }
+    candidates.iterator.flatMap { attribute =>
+      StreamingJoinHelper.getStateValueWatermark(AttributeSet(Seq(attribute)),
+        AttributeSet(otherInputAttributes), condition, 
eventWatermark).map(attribute -> _)
+    }.take(1).toSeq.headOption
+  }
+
+  /**
+   * Get the equality-key ordinal at which a V4 state manager stores and looks 
up a side's rows.
+   * A side evicted by key uses the key that the opposite input's watermark 
bounds. Any other side
+   * stores each row at its own event time, unless it is evicted on another 
column. When that
+   * event time is an equality key, its ordinal gives the same stored 
timestamps and lets a lookup
+   * read one timestamp instead of scanning every timestamp of the key.
+   */
+  def getStateKeyOrdinalForLookup(
+      oneSideAttributes: Seq[Attribute],
+      oneSideKeys: Seq[Expression],
+      otherSideAttributes: Seq[Attribute],
+      otherSideKeys: Seq[Expression],
+      predicate: Option[JoinStateWatermarkPredicate]): Option[Int] = {
+    def storesRowsAtKey(ordinal: Int): Boolean = predicate match {
+      case Some(p: JoinStateValueWatermarkPredicate) =>
+        p.expr.references.forall(_.semanticEquals(oneSideKeys(ordinal)))
+      case _ => true
+    }
+    StreamingJoinHelper.getStateKeyWatermarkOrdinal(otherSideKeys, 
otherSideAttributes).orElse(
+      StreamingJoinHelper.getEventTimeKeyOrdinal(oneSideKeys, 
oneSideAttributes)
+        .filter(storesRowsAtKey))
+  }
+
+  /**
+   * Conservatively prove that older state can use the current watermark 
semantics. Without
+   * watermarks there is no affected state. Otherwise each side must have 
exactly one event-time
+   * column, and either its own event time must be the sole watermarked 
equality key at the same
+   * ordinal, or the join must be a two-sided time-interval join on the event 
times (see
+   * [[isOwnEventTimeIntervalJoin]]). This excludes other range bounds and 
retained event times
+   * with no eviction bound. It also excludes a key computed from the event 
time by a constant,
+   * which older versions evicted at the unshifted watermark. A NULL selected 
key does not matter:
+   * old V4 state indexed it at timestamp 0 under its own key, and evicting 
that row, which can
+   * never match, emits its correct outer row.
+   */
+  private[sql] def isWatermarkCheckpointCompatible(
+      leftAttributes: Seq[Attribute],
+      rightAttributes: Seq[Attribute],
       leftKeys: Seq[Expression],
-      rightKeys: Seq[Expression]): Option[Int] = {
-    // Join keys of both sides generate rows of the same fields, that is, same 
sequence of data
-    // types. If one side (say left side) has a column (say timestamp) that 
has a watermark on it,
-    // then it will never consider joining keys that are < state key watermark 
(i.e. event time
-    // watermark). On the other side (i.e. right side), even if there is no 
watermark defined,
-    // there has to be an equivalent column (i.e., timestamp). And any right 
side data that has the
-    // timestamp < watermark will not match will not match with left side 
data, as the left side get
-    // filtered with the explicitly defined watermark. So, the watermark in 
timestamp column in
-    // left side keys effectively causes the timestamp on the right side to 
have a watermark.
-    // We will use the ordinal of the left timestamp in the left keys to find 
the corresponding
-    // right timestamp in the right keys.
-    leftKeys.zipWithIndex.collectFirst {
-      case (ne: NamedExpression, index) if ne.metadata.contains(delayKey) => 
index
-    } orElse {
-      rightKeys.zipWithIndex.collectFirst {
-        case (ne: NamedExpression, index) if ne.metadata.contains(delayKey) => 
index
+      rightKeys: Seq[Expression],
+      condition: Option[Expression]): Boolean = {
+    val leftEventTime = leftAttributes.filter(_.metadata.contains(delayKey))
+    val rightEventTime = rightAttributes.filter(_.metadata.contains(delayKey))
+
+    def watermarkKeyOrdinals(keys: Seq[Expression]): Seq[Int] = {
+      keys.zipWithIndex.collect {
+        case (key: NamedExpression, index) if key.metadata.contains(delayKey) 
=> index
       }
     }
+
+    val leftOrdinals = watermarkKeyOrdinals(leftKeys)
+    val rightOrdinals = watermarkKeyOrdinals(rightKeys)
+    if (leftEventTime.isEmpty && rightEventTime.isEmpty) {
+      leftOrdinals.isEmpty && rightOrdinals.isEmpty
+    } else if (leftEventTime.size == 1 && rightEventTime.size == 1) {
+      val leftOrdinal = StreamingJoinHelper.getEventTimeKeyOrdinal(leftKeys, 
leftAttributes)
+      val rightOrdinal = StreamingJoinHelper.getEventTimeKeyOrdinal(rightKeys, 
rightAttributes)
+      val alignedOwnEventTimeKeys = leftOrdinal.isDefined && leftOrdinal == 
rightOrdinal &&
+        leftOrdinals == leftOrdinal.toSeq && rightOrdinals == 
rightOrdinal.toSeq
+      alignedOwnEventTimeKeys || isOwnEventTimeIntervalJoin(leftAttributes, 
rightAttributes,
+        leftKeys, rightKeys, condition, leftEventTime.head, 
rightEventTime.head)
+    } else {
+      false
+    }
+  }
+
+  /**
+   * Whether every ordering conjunct compares the two inputs' event times, 
each shifted only by
+   * exact constant intervals, and both event times get a range bound. Older 
versions solved
+   * every column of an input but then found bounds only in the same 
conjuncts, so they derived
+   * the same value predicates, scan starts, V4 index columns and output 
watermark. Old V4 stored
+   * a null event time at timestamp 0 under the row's own key; both versions 
scan that entry the
+   * same way. No equality key may use an event time: older versions evicted 
such keys at the
+   * unshifted watermark.
+   */
+  private def isOwnEventTimeIntervalJoin(
+      leftAttributes: Seq[Attribute],
+      rightAttributes: Seq[Attribute],
+      leftKeys: Seq[Expression],
+      rightKeys: Seq[Expression],
+      condition: Option[Expression],
+      leftEventTime: Attribute,
+      rightEventTime: Attribute): Boolean = {
+    def conjuncts(e: Expression): Seq[Expression] = e match {
+      case And(left, right) => conjuncts(left) ++ conjuncts(right)
+      case other => Seq(other)
+    }
+    def eventTimeOf(e: Expression): Option[Attribute] =
+      Seq(leftEventTime, 
rightEventTime).find(StreamingJoinHelper.isExactIntervalShift(e, _))

Review Comment:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM: Claude Opus 5.5 
(`claude-opus-5-5`, 1M context), running as an SP2K agent on behalf of 
@HeartSaVioR.
   
   Agreed, fixed in SPARK-61344 (#60279, 
[f9762a3d955](https://github.com/apache/spark/pull/60279/commits/f9762a3d9553a75e07fe884d6a60ef3253a2b8d1)),
 and used here 
([9c618562e01](https://github.com/apache/spark/pull/60280/commits/9c618562e0186b65f8fd2cae49f1c34bd7fb802c)).
 Both versions count a day as 24 hours in every time zone, so for these 
range-only joins the old and new derivations give the same cutoffs, scan starts 
and V4 index columns. The restart check now accepts any constant interval 
without months, in every time zone, for the interval-join rule only, and still 
requires a range bound on both event times. Month intervals, which have no 
fixed length, are still rejected, and equality-key exactness is unchanged.
   
   Tests: `INTERVAL 1 DAY` resumes again in UTC, and also in 
America/Los_Angeles; `INTERVAL 24 HOURS` in America/Los_Angeles resumes for a 
left outer join; `INTERVAL 1 MONTH` is rejected before state is opened. Shifted 
event-time keys, one-directional bounds and bounds on another column are still 
rejected, and aligned event-time keys still resume.
   
   <!-- sp2k-review2 reply 4530212691 -->
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -35,22 +33,178 @@ import org.apache.spark.unsafe.types.CalendarInterval
 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, 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]): Option[Int] = {
+    getEventTimeKeyOrdinal(keys, inputAttributes).orElse {
+      keys.indices.find(getStateKeyWatermark(keys, inputAttributes, _, 
Some(0L)).isDefined)
+    }
+  }
+
+  /** Find the equality key that is this input's event-time column itself. */
+  def getEventTimeKeyOrdinal(
+      keys: Seq[Expression],
+      inputAttributes: Seq[Attribute]): 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 =>
+      keys.indexWhere(_.semanticEquals(eventTime)) match {
+        case ordinal if ordinal >= 0 => Some(ordinal)
+        case _ => None
+      }
+    }
+  }
+
+  /**
+   * Get the cutoff for the opposite input's equality key at `ordinal`, given 
this input's
+   * watermark. `keys` and `inputAttributes` belong to this input, whose 
future rows have an event
+   * time above the watermark. When the key is that event time, the equal key 
of any state row
+   * they can still match is above the watermark too. When the key is the 
event time shifted by
+   * exact intervals, solving `stateKey >= rightTime + INTERVAL 10 SECONDS` 
shifts the cutoff by
+   * that interval, less 1 ms as for range conditions. When the shift has 
whole days, months or
+   * years but never moves a time backward, the cutoff is the watermark 
itself. Returns None for
+   * any other key, including a shift with whole days, months or years that 
can move a time
+   * backward.
+   */
+  def getStateKeyWatermark(
+      keys: Seq[Expression],
+      inputAttributes: Seq[Attribute],
+      ordinal: Int,
+      eventWatermark: Option[Long]): Option[Long] = {
+    if (getEventTimeKeyOrdinal(keys, inputAttributes).contains(ordinal)) {
+      eventWatermark
+    } else {
+      shiftOfKey(keys(ordinal), inputAttributes).flatMap {
+        case KeyShift(eventTime, true, _) =>
+          val stateKey = AttributeReference("stateKey", TimestampType)()
+          getStateValueWatermark(AttributeSet(Seq(stateKey)), 
AttributeSet(Seq(eventTime)),

Review Comment:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM: Claude Opus 5.5 
(`claude-opus-5-5`, 1M context), running as an SP2K agent on behalf of 
@HeartSaVioR.
   
   Fixed in 
[9c618562e01](https://github.com/apache/spark/pull/60280/commits/9c618562e0186b65f8fd2cae49f1c34bd7fb802c).
 Before the key path calls the solver, it now replaces each foldable interval 
in the key with a literal of its value, the same value `intervalShift` 
evaluates. So the admission check on the analyzed plan derives the cutoff that 
execution derives after constant folding. Left outer, full outer and left semi 
joins on `lt = rt + INTERVAL 1 HOUR * 2` now pass analysis. 
`make_dt_interval(0, 2, 0, 0)` and `INTERVAL 1 SECOND * 2` give the same key 
and event-time bounds as `INTERVAL 2 HOURS` and `INTERVAL 2 SECONDS`, and the 
shifted-key join test also runs with `INTERVAL 1 SECOND * 10` in V2, V3 and V4. 
Keys written with interval expressions are still rejected when they shift 
backward by whole days or months, are built from an unwatermarked column, or 
are truncated.
   
   <!-- sp2k-review2 reply 4530212712 -->
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -706,32 +707,65 @@ object UnsupportedOperationChecker extends Logging {
   }
 
   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
-        }
+    val keys = ExtractEquiJoinKeys.unapply(join)
+    val leftKeys = keys.map(_._2).getOrElse(Nil)
+    val rightKeys = keys.map(_._3).getOrElse(Nil)
+
+    def canEvictState(
+        stateInput: LogicalPlan,
+        otherInput: LogicalPlan,
+        otherKeys: Seq[Expression]): Boolean = {
+      val eventTime = 
otherInput.output.find(_.metadata.contains(EventTimeWatermark.delayKey))
+      StreamingJoinHelper.getStateKeyWatermarkOrdinal(otherKeys, 
otherInput.output).isDefined ||
+        StreamingJoinHelper.getStateValueWatermark(stateInput.outputSet,
+          AttributeSet(eventTime.toSeq), join.condition, 
Some(1000000)).isDefined
+    }
+
+    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
+      }
+      val downstreamNote = downstreamRequirement.map { case (eventTimeInput, 
boundingInput) =>
+        s" A stateful operator after the join that uses the $eventTimeInput 
input's event time " +
+          s"also needs a watermark on the $boundingInput input and a reverse 
time constraint; " +
+          "otherwise the join holds back its output watermark and that 
operator stops " +
+          "emitting results."
+      }.getOrElse("")
+      val checkConf = SQLConf.STREAMING_JOIN_CHECK_FINALIZATION_ENABLED.key
+      val message =
         s"Stream-stream ${join.joinType} join between two streaming 
DataFrame/Datasets " +
-          "is not supported without a watermark in the join keys, or a 
watermark on " +
-          "the nullable side and an appropriate range condition")(join)
+          s"is not supported: it requires $requirement " +
+          "that allow unmatched state to be finalized. " +
+          "The time constraint may be equality on event time or a time range 
condition. " +
+          "When upgrading an existing query, correct its watermarks and time 
constraints, " +
+          "then use a new checkpoint and replay the input, reconciling prior 
sink output." +
+          downstreamNote +
+          s" To run the query anyway, set $checkConf to false; the query then 
keeps that " +
+          "state without bound, and an outer join never outputs those 
unmatched rows."
+      if (SQLConf.get.streamingJoinCheckFinalizationEnabled) {

Review Comment:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM: Claude Opus 5.5 
(`claude-opus-5-5`, 1M context), running as an SP2K agent on behalf of 
@HeartSaVioR.
   
   Agreed, fixed in 
[9c618562e01](https://github.com/apache/spark/pull/60280/commits/9c618562e0186b65f8fd2cae49f1c34bd7fb802c).
 With `spark.sql.streaming.join.checkFinalization.enabled` set to `false`, the 
rule of earlier versions is now the floor, at every layer of this stack: a join 
still fails unless it has a watermarked equality key or a range bound that the 
solver finds for a finalized input. A left outer join with no watermark on 
either input fails, as on the base branch, and its error no longer suggests the 
conf. A left outer or left semi join on `lt = rt` with a watermark only on `lt` 
still logs the warning and runs, and its error still names the conf. The later 
PRs in this stack skip their own new solver checks for this floor 
([6ffda93fc12](https://github.com/apache/spark/pull/60283/commits/6ffda93fc129cb081ffc13de754e9222e664d92b),
 
[c1e67e66de4](https://github.com/apache/spark/pull/60284/commits/c1e67e66de4ca23467bdf8f162df9ce424e7fde4),
 [451d1c92a57](https://github.com/apa
 che/spark/pull/60286/commits/451d1c92a57091ab1255f62fbf9610797139ad41)), so 
the joins they reject but earlier versions admitted also warn and run. With the 
conf at its default, every admission decision is unchanged. The conf doc and 
the migration guide say that joins earlier versions rejected still fail.
   
   <!-- sp2k-review2 reply 4530212725 -->
   



##########
docs/streaming/ss-migration-guide.md:
##########
@@ -25,6 +25,60 @@ Please refer [Migration Guide: SQL, Datasets and 
DataFrame](../sql-migration-gui
 
 ## Upgrading from Structured Streaming 4.3 to 4.4
 
+- Since Spark 4.4, left outer and left semi stream-stream joins require a 
watermark on the
+  right input and a time condition that limits how late a matching right row 
can arrive.

Review Comment:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM: Claude Opus 5.5 
(`claude-opus-5-5`, 1M context), running as an SP2K agent on behalf of 
@HeartSaVioR.
   
   Thanks, fixed 
([9c618562e01](https://github.com/apache/spark/pull/60280/commits/9c618562e0186b65f8fd2cae49f1c34bd7fb802c)).
 The migration guide entry and the join guide, right below the support table, 
now say that an equality key counts as the time constraint only when it is the 
other input's event time, or that event time shifted by constant intervals, 
except a shift backward by whole days, months or years. They name `leftTime = 
rightTime - INTERVAL 1 DAY` and `leftTime = CAST(CAST(rightTime AS BIGINT) AS 
TIMESTAMP)` as keys that do not count, and say that a time range condition 
between the two event times can bound such a join instead when both inputs have 
watermarks.
   
   <!-- sp2k-review2 reply 4530212743 -->
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -706,32 +707,44 @@ object UnsupportedOperationChecker extends Logging {
   }
 
   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
-        }
+    val keys = ExtractEquiJoinKeys.unapply(join)
+    val leftKeys = keys.map(_._2).getOrElse(Nil)
+    val rightKeys = keys.map(_._3).getOrElse(Nil)
+
+    def canEvictState(
+        stateInput: LogicalPlan,
+        otherInput: LogicalPlan,
+        otherKeys: Seq[Expression]): Boolean = {
+      val eventTime = 
otherInput.output.find(_.metadata.contains(EventTimeWatermark.delayKey))
+      StreamingJoinHelper.getStateKeyWatermarkOrdinal(otherKeys, 
otherInput.output).isDefined ||
+        StreamingJoinHelper.getStateValueWatermark(stateInput.outputSet,

Review Comment:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM: Claude Opus 5.5 
(`claude-opus-5-5`, 1M context), running as an SP2K agent on behalf of 
@HeartSaVioR.
   
   Done 
([9c618562e01](https://github.com/apache/spark/pull/60280/commits/9c618562e0186b65f8fd2cae49f1c34bd7fb802c)).
 The analysis check and the stored-side watermark branch of the eviction 
predicates each have a TODO naming SPARK-61347 and one naming SPARK-61348, 
describing the range bound that this PR admits but does not finalize yet. 
SPARK-61347 (#60282) removes its two TODOs when it evicts without the stored 
side's own watermark, and SPARK-61348 (#60283) removes the other two when the 
solver gives a cutoff only for a TIMESTAMP column or a time window at least as 
long as the other input's.
   
   <!-- sp2k-review2 reply 4530213150 -->
   



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