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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -224,98 +238,394 @@ 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] = {
-      val isWatermarkDefinedOnInput = 
oneSideInputAttributes.exists(_.metadata.contains(delayKey))
+        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, eventTimeLags)
       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)
-        }
-      } 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)
+          ordinal, oneSideJoinKeys(ordinal).dataType, 
oneSideJoinKeys(ordinal).nullable)
+        // The opposite watermark bounds this key when the opposite key is 
that input's event
+        // time, possibly shifted by constant intervals: by the shift for an 
exact interval, and
+        // unshifted for whole days, months or years that never move a time 
backward. See
+        // StreamingJoinHelper.getStateKeyWatermark for which shifts qualify.
+        def keyWatermark(watermark: Option[Long]): Option[Long] =
+          StreamingJoinHelper.getStateKeyWatermark(
+            otherSideJoinKeys, otherSideInputAttributes, ordinal, watermark, 
eventTimeLags)
+        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)
+          }
         }
-        val inputAttributeWithWatermark = 
oneSideInputAttributes.find(_.metadata.contains(delayKey))
-        val expr = watermarkExpression(inputAttributeWithWatermark, 
stateValueWatermark)
-        expr.map { e =>
-          // watermarkExpression only provides the expression when 
eventTimeWatermarkForEviction
-          // is defined
-          JoinStateValueWatermarkPredicate(e, stateValueWatermark.get, 
prevStateValueWatermark)
+      } else { // case 2 in the StreamingSymmetricHashJoinExec docs
+        // Future matches are limited by the opposite watermark. This input 
needs no watermark;
+        // its event-time column may also have been pruned from the physical 
join.
+        // TODO(SPARK-61348): the analysis check admits a range bound on a 
column that is not
+        //   TIMESTAMP, which this branch never evicts.
+        getStateValueWatermarkForInput(oneSideInputAttributes, 
otherSideInputAttributes, condition,
+          eventTimeWatermarkForEviction, eventTimeLags).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.getStateValueWatermarkForLags(AttributeSet(Seq(attribute)),
+              otherSideInputAttributes, condition, Some(lateWatermark), 
eventTimeLags)
+              .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],
+      eventTimeLags: Option[EventTimeLags]): Option[(Attribute, Long)] = {
+    // TODO(SPARK-61348): the analysis check admits a range bound on a column 
that is not
+    //   TIMESTAMP, which no candidate below takes. A left, right or full 
outer join whose
+    //   preserved side is bounded only through such a column cast to 
TIMESTAMP then keeps its
+    //   unmatched rows in state and never emits them. SPARK-61348 rejects 
that shape at analysis.
+    // TODO(SPARK-61508): an inner or left semi join side that is bounded only 
through such a
+    //   cast column has no eviction predicate either, so it keeps its rows 
for the life of the
+    //   query until eviction through the cast is supported. Projecting the 
column to TIMESTAMP
+    //   before the join bounds that state.
+    // TODO(SPARK-61349): a conjunct that uses only constants still caps the 
cutoff, so it can
+    //   stop eviction.
+    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.getStateValueWatermarkForLags(AttributeSet(Seq(attribute)),
+        otherInputAttributes, condition, eventWatermark, eventTimeLags,
+        exactForUnwatermarkedColumns = true).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. An input that neither version 
evicts keeps the same
+   * rows, but its state watermark in the join's output watermark changed, so 
such an input is
+   * accepted only when no stateful operator after the join reads it: 
`consumedSides` names the
+   * inputs whose state watermark reaches a later operator through the join's 
output watermark,
+   * both when that operator cannot be traced, and none when no stateful 
operator follows, with a
+   * single global watermark, or for the right input of a left semi join. A 
key-only join, with
+   * no other condition and no equality key that uses an event time, is 
evicted by neither
+   * version, and V4 reads its rows by key prefix. Otherwise each side must 
have exactly one
+   * event-time column, and either its own event time must be the sole 
watermarked equality key
+   * at the same ordinal, or the join must be a time-interval join on the 
event times (see
+   * [[isOwnEventTimeIntervalJoin]]). This excludes other range bounds. A key 
computed from the
+   * event time by a constant is accepted only when it shifts the event time 
forward, the other
+   * input's key at that ordinal is its own event time, no other equality key 
uses an event time,
+   * and no stateful operator after the join reads the shifted input's event 
time. Older versions
+   * evicted both sides at the unshifted watermark at that ordinal. For a 
forward shift, that is
+   * the cutoff this version uses for the shifted side, and at or below the 
one it uses for the
+   * other side, which can no longer match rows at or below it, and both 
versions store V4 rows
+   * at that ordinal. Only the shifted input's bound in the output watermark 
changes. Older
+   * versions evicted a backward shift before its last match. A NULL selected 
key does not change
+   * the semantics: such a row can never match.
+   * Old V4 state indexed it at timestamp 0 under its own key, and the first 
batch after the
+   * restart scans V4 state from the start, so it evicts the row and a 
preserved side emits it
+   * unless an older version already joined it. V1 to V3 test every stored row 
each batch and
+   * also evict such a 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],
+      consumedSides: Set[JoinSide]): Boolean = {
+    val leftEventTime = leftAttributes.filter(_.metadata.contains(delayKey))
+    val rightEventTime = rightAttributes.filter(_.metadata.contains(delayKey))
+    val keyOnly = condition.isEmpty && !(leftKeys ++ rightKeys).exists { key =>
+      key.references.exists(_.metadata.contains(delayKey)) || (key match {
+        case named: NamedExpression => named.metadata.contains(delayKey)
+        case _ => false
+      })
+    }
+
+    def watermarkKeyOrdinals(keys: Seq[Expression]): Seq[Int] = {
+      keys.zipWithIndex.collect {
+        case (key: NamedExpression, index) if key.metadata.contains(delayKey) 
=> index
       }
     }
+
+    val leftOrdinals = watermarkKeyOrdinals(leftKeys)
+    val rightOrdinals = watermarkKeyOrdinals(rightKeys)
+    if (leftEventTime.isEmpty && rightEventTime.isEmpty) {
+      leftOrdinals.isEmpty && rightOrdinals.isEmpty
+    } else if (keyOnly && consumedSides.isEmpty) {
+      true
+    } else if (leftEventTime.size == 1 && rightEventTime.size == 1) {

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 in 
[ab59957f358](https://github.com/apache/spark/pull/60280/commits/ab59957f3582d270164fd563b24f31603ff5e54c)
 on #60280, where the legacy-mode lags live. With
   `spark.sql.streaming.statefulOperator.allowMultiple=false`, the restart 
check now gets the lags
   that eviction reads. It accepts an older checkpoint when each input's only 
watermarked equality
   key is at the same position and its lag gives the watermark itself as the 
cutoff on both sides,
   which is the cutoff Spark 4.3 used. That covers a join on a window over the 
first watermarked
   column, and a join on that column while the input keeps the window. A key 
whose lag lowers the
   cutoff or has no bound is still rejected. The lags are now the same in every 
batch (see the
   union finding), so the first batch after a restart reads the same lags as 
later ones.
   
   I did not extend the time-interval rule to inputs with several watermarked 
columns. That rule
   solves the condition without the lags, so it could accept a range on a later 
column that
   legacy-mode eviction now bounds lower. Those checkpoints stay rejected with 
the explicit error.
   The migration guide now names the legacy-mode checkpoints that are reused.
   
   Tests: older format 2 and 3 checkpoints of a legacy-mode join on the window, 
and on the event
   time while the query keeps the window, resume and match a row stored before 
the restart. One on a
   key shifted back 20 seconds is still rejected.
   
   <!-- sp2k-review11 reply 4598419940 -->
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -17,36 +17,722 @@
 
 package org.apache.spark.sql.catalyst.analysis
 
+import java.util.Locale
+
+import scala.util.Try
 import scala.util.control.NonFatal
 
 import org.apache.spark.internal.Logging
 import org.apache.spark.internal.LogKeys._
+import org.apache.spark.sql.catalyst.InternalRow
 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.{InnerLike, LeftOuter, RightOuter}
+import org.apache.spark.sql.catalyst.plans.logical.{Expand, Join, LogicalPlan, 
Project, UnaryNode, 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
 
+/**
+ * How far below a column that can filter its stream-stream join input's late 
rows one of the
+ * input's watermarked columns can be, for an equality key or a range 
condition on it: at most
+ * `micros` where the plan relates the two columns; by an amount that the plan 
does not bound when
+ * `unbounded`; and by an amount that it does not show when `unrelated`, 
because it does not relate
+ * the two. A window column is compared by its end, as eviction and late 
filtering compare it.
+ */
+case class EventTimeLag(micros: Long, unrelated: Boolean, unbounded: Boolean) {
+  def max(other: EventTimeLag): EventTimeLag = EventTimeLag(math.max(micros, 
other.micros),
+    unrelated || other.unrelated, unbounded || other.unbounded)
+
+  /**
+   * The cutoff for the other input's equality key when this input's watermark 
is `watermark`.
+   * A key that the plan does not relate keeps the Spark 4.3 cutoff.
+   */
+  def keyWatermark(watermark: Long): Option[Long] =
+    if (unbounded) None else Some(watermark - EventTimeLag.ceilMillis(micros))
+
+  /**
+   * The watermark to substitute for the column in a range condition. Spark 
4.3 substituted the
+   * watermark for every watermarked column; this does so only where the plan 
bounds the lag.
+   */
+  def rangeWatermark(watermark: Long): Option[Long] =
+    if (unbounded || unrelated) None else Some(watermark - 
EventTimeLag.ceilMillis(micros))
+}
+
+object EventTimeLag {
+  val zero: EventTimeLag = EventTimeLag(0L, unrelated = false, unbounded = 
false)
+  val unrelated: EventTimeLag = EventTimeLag(0L, unrelated = true, unbounded = 
false)
+  val unbounded: EventTimeLag = EventTimeLag(0L, unrelated = false, unbounded 
= true)
+
+  private def ceilMillis(micros: Long): Long =
+    micros / MICROS_PER_MILLIS + (if (micros % MICROS_PER_MILLIS == 0) 0 else 
1)
+}
+
+/**
+ * The [[EventTimeLag]] of the watermarked columns of stream-stream join 
inputs, by expression ID;
+ * see [[StreamingJoinHelper.findEventTimeLags]]. A column missing from `lags` 
has lag zero, so
+ * `EventTimeLags(Map.empty)` gives every watermarked column lag zero. That is 
right when multiple
+ * stateful operators are allowed: execution then fails at start for a planned 
input with two
+ * distinct watermarked columns, so the only one left filters late rows itself.
+ */
+case class EventTimeLags(lags: Map[ExprId, EventTimeLag]) {
+  /**
+   * The lag of `column` in a join input with output `inputAttributes`, if it 
carries a watermark.
+   * The input's first watermarked column filters its late rows itself.
+   */
+  def lagOf(column: NamedExpression, inputAttributes: Seq[Attribute]): 
Option[EventTimeLag] =
+    if (!column.metadata.contains(delayKey)) {
+      None
+    } else if (inputAttributes.find(_.metadata.contains(delayKey))
+        .exists(_.exprId == column.exprId)) {
+      Some(EventTimeLag.zero)
+    } else {
+      Some(lags.getOrElse(column.exprId, EventTimeLag.zero))
+    }
+}
+
+object EventTimeLags {
+  val none: EventTimeLags = EventTimeLags(Map.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. Without `lags`, only the input's 
first watermarked
+   * column counts as its event time; with them, every watermarked column that 
they bound does.
+   */
+  def getStateKeyWatermarkOrdinal(
+      keys: Seq[Expression],
+      inputAttributes: Seq[Attribute],
+      lags: Option[EventTimeLags] = None): Option[Int] = {
+    getEventTimeKeyOrdinal(keys, inputAttributes, lags).orElse {
+      keys.indices.find(getStateKeyWatermark(keys, inputAttributes, _, 
Some(0L), lags).isDefined)
+    }
+  }
+
+  /**
+   * Find the equality key that is this input's first watermarked column, or 
else, with `lags`,
+   * the watermarked key with the smallest lag that bounds it; see 
[[findEventTimeLags]].
+   */
+  def getEventTimeKeyOrdinal(
+      keys: Seq[Expression],
+      inputAttributes: Seq[Attribute],
+      lags: Option[EventTimeLags] = None): 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 =>
+      Some(keys.indexWhere(_.semanticEquals(eventTime))).filter(_ >= 0).orElse 
{
+        lags.flatMap { l =>
+          keys.indices.flatMap { i =>
+            keyLag(keys(i), inputAttributes, l).filterNot(_.unbounded).map(i 
-> _.micros)
+          }.sortBy(_._2).headOption.map(_._1)
+        }
+      }
+    }
+  }
+
+  /** The lag of a key that is a watermarked column of the input. */
+  private def keyLag(
+      key: Expression,
+      inputAttributes: Seq[Attribute],
+      lags: EventTimeLags): Option[EventTimeLag] = key match {
+    case n: NamedExpression => lags.lagOf(n, inputAttributes)
+    case _ => None
+  }
+
+  /**
+   * The lag of every watermarked column of each stream-stream join input in 
`plan`, combined
+   * over the inputs by [[EventTimeLag.max]]. This is for
+   * spark.sql.streaming.statefulOperator.allowMultiple=false, where an input 
can keep several
+   * watermarked columns, such as its event time and a copy of it or a time 
window over it, and
+   * filters late rows by the first of them. When `planned`, `plan` is the 
optimized plan that runs,
+   * so each input filters late rows by its first watermarked column, and a 
column's lag is taken
+   * against that one. Otherwise the optimizer can prune any watermarked 
column before a column, so
+   * its lag is the largest against all of them. Spark 4.3 bounded state by 
every watermarked
+   * column at the watermark. A lag lowers that cutoff; see [[EventTimeLag]].
+   */
+  def findEventTimeLags(plan: LogicalPlan, planned: Boolean): EventTimeLags = {
+    val lags = 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
+      watermarked.indices.map { i =>
+        val lateFiltered = if (planned) watermarked.take(1) else 
watermarked.take(i)
+        watermarked(i) -> lateFiltered.filter(_ != watermarked(i)).map { 
eventTime =>
+          lagBelow(input, watermarked(i), eventTime, Some(0L), Some(0L))
+        }.foldLeft(EventTimeLag.zero)(_ max _)
+      }
+    }
+    EventTimeLags(lags.groupMapReduce(_._1)(_._2)(_ max _))
+  }
+
+  /** How a column relates to the column of a node's child that [[lagBelow]] 
follows for it. */
+  private case class Step(column: ExprId, offset: Option[Long])
+
+  /**
+   * How far `key` of `plan` can be below its column `eventTime`, which late 
filtering compares
+   * with the watermark. Both are compared by their bounds: a time, or a 
window's end. `keyLow` is
+   * the smallest that the join input's key is above `key`, and 
`eventTimeHigh` the largest that the
+   * join input's late-filtered column is above `eventTime`; None means 
without bound. The walk
+   * follows both columns down by expression ID: through a projection or an 
expansion that passes
+   * them on, builds a time or session window from a single column, or, for 
the key, shifts a
+   * timestamp by constant intervals; through any other node with one input 
that outputs both, as
+   * such a node keeps an expression ID only for an unchanged value; into the 
input of a join that
+   * outputs both, or into both inputs of one that outputs each from a 
different input and equates
+   * them through its condition (see [[lagThroughJoinCondition]]); and into 
every input of a union,
+   * at the same positions. A union input that does not watermark a column 
that the union, which
+   * takes its first input's metadata, watermarks builds it some other way, so 
the lag is
+   * unbounded. Where both reach the same column, the lag is the difference of 
the two offsets.
+   * Everything else leaves the columns unrelated.
+   */
+  private def lagBelow(
+      plan: LogicalPlan,
+      key: ExprId,
+      eventTime: ExprId,
+      keyLow: Option[Long],
+      eventTimeHigh: Option[Long]): EventTimeLag = {
+    def outputsBoth(p: LogicalPlan): Boolean =
+      p.output.exists(_.exprId == key) && p.output.exists(_.exprId == 
eventTime)
+    def follow(child: LogicalPlan, keyStep: Option[Step], eventTimeStep: 
Option[Step]) =
+      (keyStep, eventTimeStep) match {
+        case (Some(k), Some(t)) => lagBelow(child, k.column, t.column,
+          addOffsets(keyLow, k.offset), addOffsets(eventTimeHigh, t.offset))
+        case _ => EventTimeLag.unrelated
+      }
+    if (key == eventTime) {
+      (keyLow, eventTimeHigh) match {
+        case (Some(low), Some(high)) => Try(Math.subtractExact(high, 
low)).toOption match {
+          case Some(lag) => EventTimeLag(math.max(0L, lag), unrelated = false, 
unbounded = false)
+          case None => EventTimeLag.unbounded
+        }
+        case _ => EventTimeLag.unbounded
+      }
+    } else {
+      plan match {
+        case p: Project =>
+          def entry(id: ExprId): Option[NamedExpression] = 
p.projectList.find(_.exprId == id)
+          follow(p.child, entry(key).flatMap(keyStep), 
entry(eventTime).flatMap(eventTimeStep))
+        case e: Expand =>
+          // The rewrite of a sliding window puts one window per projection 
beside the child's
+          // columns, which every projection passes on.
+          def step(id: ExprId, window: (Seq[Expression], Attribute) => 
Option[Long]) = {
+            val entries = e.output.indexWhere(_.exprId == id) match {
+              case -1 => Nil
+              case index => e.projections.map(_(index))
+            }
+            entries.map {
+              case a: Attribute => Some(a.exprId)
+              case _ => None
+            }.distinct match {
+              case Seq(Some(passedOn)) => Some(Step(passedOn, Some(0L)))
+              case _ if e.output.exists(a => a.exprId == id &&
+                  a.metadata.contains(TimeWindow.marker)) =>
+                entries.map(timeWindowSource).distinct match {
+                  case Seq(Some(source)) => Some(Step(source.exprId, 
window(entries, source)))
+                  case _ => None
+                }
+              case _ => None
+            }
+          }
+          // A window ends after its time column, and at most its length after 
it.
+          follow(e.child, step(key, (_, _) => Some(0L)), step(eventTime, 
(entries, source) =>
+            entries.map(timeWindowLength(_, source)).reduceOption((a, b) =>
+              for (x <- a; y <- b) yield math.max(x, y)).flatten))
+        case u: Union =>
+          val keyIndex = u.output.indexWhere(_.exprId == key)
+          val eventTimeIndex = u.output.indexWhere(_.exprId == eventTime)
+          def unwatermarked(child: LogicalPlan, index: Int): Boolean =
+            u.output(index).metadata.contains(delayKey) &&
+              !child.output(index).metadata.contains(delayKey)
+          if (keyIndex < 0 || eventTimeIndex < 0) {
+            EventTimeLag.unrelated
+          } else {
+            u.children.map { child =>
+              if (unwatermarked(child, keyIndex) || unwatermarked(child, 
eventTimeIndex)) {
+                EventTimeLag.unbounded
+              } else {
+                lagBelow(child, child.output(keyIndex).exprId,
+                  child.output(eventTimeIndex).exprId, keyLow, eventTimeHigh)
+              }
+            }.reduce(_ max _)
+          }
+        case j: Join =>
+          j.children.find(outputsBoth).map(lagBelow(_, key, eventTime, keyLow, 
eventTimeHigh))
+            .getOrElse(lagThroughJoinCondition(j, key, eventTime, keyLow, 
eventTimeHigh))
+        case u: UnaryNode if outputsBoth(u.child) =>
+          lagBelow(u.child, key, eventTime, keyLow, eventTimeHigh)
+        case _ => EventTimeLag.unrelated
+      }
+    }
+  }
+
+  /**
+   * The lag of `key` below `eventTime` of [[lagBelow]] where `join` outputs 
them from different
+   * inputs, through an equality `x = y` in its condition between a 
watermarked column x of the
+   * key's input and a watermarked column y of the event time's input: the key 
is at most its lag
+   * below x, which equals y, which is at most its lag below the event time, 
so the lags add up.
+   * That holds on every row that the join outputs with a non-NULL key: all 
rows of an inner join
+   * satisfy its condition, and so do those of a left or right outer join that 
pads the key's
+   * input, whose other rows carry a NULL key that no condition matches. The 
smallest bounded lag
+   * over such equalities wins. Other conjuncts, such as a range or a shifted 
equality, and other
+   * join types leave the columns unrelated.
+   */
+  private def lagThroughJoinCondition(
+      join: Join,
+      key: ExprId,
+      eventTime: ExprId,
+      keyLow: Option[Long],
+      eventTimeHigh: Option[Long]): EventTimeLag = {
+    def watermarked(p: LogicalPlan): Set[ExprId] =
+      p.output.filter(_.metadata.contains(delayKey)).map(_.exprId).toSet
+    def outputs(p: LogicalPlan, id: ExprId): Boolean = 
p.output.exists(_.exprId == id)
+    val inputs = if (outputs(join.left, key) && outputs(join.right, 
eventTime)) {
+      Some((join.left, join.right))
+    } else if (outputs(join.right, key) && outputs(join.left, eventTime)) {
+      Some((join.right, join.left))
+    } else {
+      None
+    }
+    val lags = inputs.filter { case (keyInput, _) =>
+      join.joinType match {
+        case _: InnerLike => true
+        case LeftOuter => keyInput eq join.right
+        case RightOuter => keyInput eq join.left
+        case _ => false
+      }
+    }.toSeq.flatMap { case (keyInput, eventTimeInput) =>
+      val keyColumns = watermarked(keyInput)
+      val eventTimeColumns = watermarked(eventTimeInput)
+      join.condition.toSeq.flatMap(splitConjunctivePredicates).flatMap {
+        case EqualTo(a: Attribute, b: Attribute) => Seq(a.exprId -> b.exprId, 
b.exprId -> a.exprId)
+        case _ => Nil
+      }.filter { case (x, y) => keyColumns.contains(x) && 
eventTimeColumns.contains(y) }
+        .map { case (x, y) =>
+          val below = lagBelow(keyInput, key, x, keyLow, Some(0L))
+          val above = lagBelow(eventTimeInput, y, eventTime, Some(0L), 
eventTimeHigh)
+          if (below.unrelated || above.unrelated) {
+            EventTimeLag.unrelated
+          } else {
+            Try(Math.addExact(below.micros, above.micros)).toOption
+              .filter(_ => !below.unbounded && !above.unbounded)
+              .map(EventTimeLag(_, unrelated = false, unbounded = false))
+              .getOrElse(EventTimeLag.unbounded)
+          }
+        }
+    }
+    lags.filter(lag => !lag.unrelated && 
!lag.unbounded).sortBy(_.micros).headOption
+      .getOrElse(EventTimeLag.unrelated)

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 in 
[ab59957f358](https://github.com/apache/spark/pull/60280/commits/ab59957f3582d270164fd563b24f31603ff5e54c)
 on #60280. An earlier-join equality whose lag has no bound now gives the key no
   bound, instead of leaving it unrelated. Your example is now a test: with `as 
= at - INTERVAL 1 DAY`
   and `AB = A.join(B, ak = bk AND as = bt)`, the chained inner join on `bt = 
ct` keeps C's row, so an
   AB row whose `bt` is a day below the watermark still matches, and the right 
outer form fails
   analysis. Chained joins tied by `at = bt` keep their cutoffs.
   
   <!-- sp2k-review11 reply 4598419974 -->
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala:
##########
@@ -167,6 +171,29 @@ class IncrementalExecution(
   private val allowMultipleStatefulOperators: Boolean =
     
sparkSession.sessionState.conf.getConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE)
 
+  // The lags of the planned join inputs, against the columns that they filter 
late rows by. They
+  // read the optimized plan, whose expression IDs the planned joins use. The 
analysis check reads
+  // the analyzed plan with the same rule, against every column that pruning 
can leave first, so
+  // it bounds a column here whenever it bounds one there. The projections 
that build the later
+  // watermarked columns stay in every batch's optimized plan: they sit above 
the input's
+  // watermark node, which the optimizer keeps even for a batch without data.
+  private lazy val eventTimeLags: Option[EventTimeLags] =
+    if (allowMultipleStatefulOperators) {
+      None
+    } else {
+      Some(StreamingJoinHelper.findEventTimeLags(optimizedPlan, planned = 
true))

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 in 
[ab59957f358](https://github.com/apache/spark/pull/60280/commits/ab59957f3582d270164fd563b24f31603ff5e54c)
 on #60280. The union columns that an input builds without a watermark now come 
from
   the batch's analyzed plan, which keeps every union input, so `yw` has no 
bound in every batch,
   including batches in which `Y2` has no data; a no-data batch reads the same 
kind of analyzed plan.
   Keys with a bounded lag, such as
   a window over the first watermarked column, keep their cutoffs. Tests cover 
the equality-key and
   the range form of this shape.
   
   <!-- sp2k-review11 reply 4598419987 -->
   



##########
common/utils/src/main/resources/error/error-conditions.json:
##########
@@ -8165,6 +8165,41 @@
     ],
     "sqlState" : "55019"
   },
+  "STREAMING_JOIN_CHECKPOINT_INCOMPATIBLE" : {
+    "message" : [
+      "Cannot reuse the checkpoint for the stream-stream join with condition 
<joinCondition>. Watermarked columns: left [<leftWatermarkColumns>], right 
[<rightWatermarkColumns>].",
+      "This Spark version changes how watermarks determine which rows can 
still match. Spark cannot verify that rows saved by the previous version can be 
reused safely for this join. Start the query with a new checkpoint and replay 
the required input, accounting for previously written results to avoid 
duplicates and correct any missing or incorrect output."
+    ],
+    "sqlState" : "0A000"
+  },
+  "STREAMING_JOIN_UNBOUNDED_DOWNSTREAM_EVENT_TIME" : {
+    "message" : [
+      "The append-mode aggregation after a stream-stream join uses the event 
time <eventTime> of the join's <side> input, but the join has no bound on that 
event time for the state of that input, so it holds back its output watermark 
and the aggregation would never emit results."
+    ],
+    "subClass" : {
+      "TIME_CONSTRAINT" : {
+        "message" : [
+          "Add a time constraint that limits how late a matching <otherSide> 
row can arrive, aggregate the event time of an input whose state the join can 
bound. A bound on the event time comes from an equality key that shifts the 
other input's event time by an exact interval (under one day, or timestampadd 
in hours, minutes or seconds), or from a range condition used in place of a 
shifted equality. To run the query anyway, set <config> to false."

Review Comment:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM: Claude Sonnet 5.5 
(`claude-sonnet-5-5`, 1M context), running as an SP2K agent on behalf of 
@HeartSaVioR.
   
   Fixed in 
[ab59957f358](https://github.com/apache/spark/pull/60280/commits/ab59957f3582d270164fd563b24f31603ff5e54c)
 on #60280. The `TIME_CONSTRAINT` and `WATERMARK_AND_TIME_CONSTRAINT` messages 
now join their two remedies with "or", so they read as alternatives, as the 
`_OR_UPDATE_MODE` variants do.
   
   <!-- sp2k-review11 reply 4598420035 -->
   



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