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


##########
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) {
+      val leftOrdinal = StreamingJoinHelper.getEventTimeKeyOrdinal(leftKeys, 
leftAttributes)
+      val rightOrdinal = StreamingJoinHelper.getEventTimeKeyOrdinal(rightKeys, 
rightAttributes)
+      val alignedOwnEventTimeKeys = leftOrdinal.isDefined && leftOrdinal == 
rightOrdinal &&
+        leftOrdinals == leftOrdinal.toSeq && rightOrdinals == 
rightOrdinal.toSeq
+      // One input's own event-time key paired with a forward shift of the 
other input's.
+      def forwardShiftedKey(
+          ownOrdinal: Option[Int],
+          ownWatermarkOrdinals: Seq[Int],
+          shiftedKeys: Seq[Expression],
+          shiftedAttributes: Seq[Attribute],
+          shiftedWatermarkOrdinals: Seq[Int],
+          shiftedSide: JoinSide): Boolean = ownOrdinal.exists { ordinal =>
+        ownWatermarkOrdinals == Seq(ordinal) && 
shiftedWatermarkOrdinals.isEmpty &&
+          StreamingJoinHelper.isForwardShiftOfEventTime(shiftedKeys(ordinal), 
shiftedAttributes) &&
+          leftKeys.indices.filter(_ != ordinal).forall { i =>
+            !(leftKeys(i).references ++ rightKeys(i).references)
+              .exists(_.metadata.contains(delayKey))
+          } && !consumedSides(shiftedSide)
+      }
+      alignedOwnEventTimeKeys ||
+        forwardShiftedKey(leftOrdinal, leftOrdinals, rightKeys, 
rightAttributes, rightOrdinals,
+          RightSide) ||
+        forwardShiftedKey(rightOrdinal, rightOrdinals, leftKeys, 
leftAttributes, leftOrdinals,
+          LeftSide) ||
+        isOwnEventTimeIntervalJoin(leftAttributes, rightAttributes, leftKeys, 
rightKeys,
+          condition, leftEventTime.head, rightEventTime.head, consumedSides)
+    } else {
+      false

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 as you suggested, in #60279, where the restart check lives; it 
reaches this PR
   through the next merge. The check now accepts an older checkpoint of a join 
where only one input
   has a watermark and no equality key uses an event time, in state formats 1 
to 3, when no stateful
   operator after the join reads the join's output watermark. Older versions 
evicted neither input
   of such a join, and formats 1 to 3 test every stored row each batch, so the 
first batch after the
   restart evicts the old rows the way this version does. Format 4 stays 
rejected, with a TODO that
   names this PR: older versions stored the rows of the input without a 
watermark without a time
   index entry, which this PR's eviction needs. The migration guide's restart 
paragraph says which
   of these checkpoints are reused.
   
   Tests: the compatibility suite's one-sided checkpoints (a range and an 
expiry bound on the left
   input, which has no watermark) now resume in formats 1 to 3 and match a row 
stored before the
   restart; in format 4, and when a later operator reads the watermarked input, 
they are still
   rejected.
   
   <!-- sp2k-review11 reply 4598419956 -->
   



##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinSuite.scala:
##########
@@ -2425,6 +2802,275 @@ abstract class StreamingLeftSemiJoinBase extends 
StreamingJoinSuite {
     }
   }
 
+  // A left semi join processes the right input before the left input. A right 
row at or below
+  // its eviction cutoff passes late filtering when it is above the 
late-events watermark, and
+  // the left rows of the same batch must still find it. Each case runs a 
batch whose
+  // late-events watermark is 100 seconds and whose eviction watermark is 
`watermark` seconds.
+  // (name, condition, left time, right time, watermark, state rows after the 
second batch and
+  // after the third)
+  for ((name, condition, leftTime, rightTime, watermark, rowsBefore, 
rowsAfter) <- Seq(
+      ("equal event times", "leftTime = rightTime", 102, 102, 105, 2L, 0L),
+      // The left key leftTime + 10 seconds of (7, 100) stays above the 
100-second cutoff.
+      ("a key shifted by less than the watermark step",
+        "leftTime + INTERVAL 10 SECONDS = rightTime", 120, 130, 150, 3L, 1L),
+      // The right key cutoff is the watermark plus 10 seconds less 1 ms, so 
the right row
+      // (1, 112) is at or below it although the watermark advances by only 5 
seconds. The left
+      // keys of (7, 100) and (7, 105) stay above the 105-second left cutoff.
+      ("a key shifted by more than the watermark step",
+        "leftTime + INTERVAL 10 SECONDS = rightTime", 102, 112, 105, 2L, 2L),
+      // A value cutoff of the watermark less 10 seconds and 1 ms: (1, 130) is 
below 139.999 s.
+      ("a time interval",
+        "leftTime BETWEEN rightTime - INTERVAL 10 SECONDS AND rightTime + 
INTERVAL 10 SECONDS",
+        125, 130, 150, 4L, 2L))) {
+    test(s"left semi join keeps a same-batch match between the watermarks: 
$name") {
+      withSQLConf(SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> 
"false") {
+        val leftInput = MemoryStream[(Int, Int)]
+        val rightInput = MemoryStream[(Int, Int)]
+        val left = leftInput.toDF()
+          .select($"_1".as("leftKey"), timestamp_seconds($"_2").as("leftTime"))
+          .withWatermark("leftTime", "0 seconds")
+        val right = rightInput.toDF()
+          .select($"_1".as("rightKey"), 
timestamp_seconds($"_2").as("rightTime"))
+          .withWatermark("rightTime", "0 seconds")
+        val joined = left.join(right, expr(s"leftKey = rightKey AND 
$condition"), "left_semi")
+          .select($"leftKey", $"leftTime".cast("int"))
+
+        testStream(joined)(
+          MultiAddData(leftInput, (7, 100))(rightInput, (8, 100)),
+          CheckNewAnswer(),
+          MultiAddData(leftInput, (7, watermark))(rightInput, (8, watermark)),
+          CheckNewAnswer(),
+          assertNumStateRows(total = rowsBefore, updated = 4),
+          MultiAddData(leftInput, (1, leftTime))(rightInput, (1, rightTime)),
+          CheckNewAnswer((1, leftTime)),
+          // The right row is stored for the left row to probe and removed at 
the end of the
+          // batch, together with the other rows at or below the cutoffs.
+          assertNumStateRows(total = rowsAfter, updated = 1))
+      }
+    }
+  }
+
+  // The right cutoff comes from a bound on rightExpiry. The right row (1, 
110, 160) matches the
+  // left row (1, 120) of the same batch and is evicted at its end, whether 
the cutoff is applied
+  // to rightExpiry or to rightTime. Storing only the right rows above the 
cutoff at the
+  // late-events watermark would drop this match when the cutoff is applied to 
rightTime.
+  test("left semi join keeps a same-batch match bounded by another right 
column") {
+    withSQLConf(SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> 
"false") {
+      val leftInput = MemoryStream[(Int, Int, Int)]
+      val rightInput = MemoryStream[(Int, Int, Int)]
+      val left = leftInput.toDF()
+        .select($"_1".as("leftKey"), timestamp_seconds($"_2").as("leftTime"))
+        .withWatermark("leftTime", "0 seconds")
+      val right = rightInput.toDF()
+        .select($"_1".as("rightKey"), timestamp_seconds($"_2").as("rightTime"),
+          timestamp_seconds($"_3").as("rightExpiry"))
+        .withWatermark("rightTime", "0 seconds")
+      val joined = left.join(right, expr("leftKey = rightKey AND " +
+        "rightExpiry >= leftTime + INTERVAL 30 SECONDS AND " +
+        "leftTime >= rightTime - INTERVAL 1 HOUR"), "left_semi")
+        .select($"leftKey", $"leftTime".cast("int"))
+
+      testStream(joined)(
+        MultiAddData(leftInput, (7, 100, 0))(rightInput, (8, 100, 100)),
+        CheckNewAnswer(),
+        MultiAddData(leftInput, (7, 150, 0))(rightInput, (8, 150, 150)),
+        CheckNewAnswer(),
+        assertNumStateRows(total = 3, updated = 4),
+        // The late-events watermark is 100 seconds, and the right cutoff at 
it is 130 seconds
+        // less 1 ms: above the right row's rightTime of 110 seconds, below 
its rightExpiry.
+        MultiAddData(leftInput, (1, 120, 0))(rightInput, (1, 110, 160)),
+        CheckNewAnswer((1, 120)),
+        assertNumStateRows(total = 2, updated = 1))
+    }
+  }
+
+  test("left semi join keeps a same-batch match bounded by another right 
column when both " +
+      "watermarks are equal") {
+    withSQLConf(SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> "false",
+        SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key -> "false") {
+      val leftInput = MemoryStream[(Int, Int, Int)]
+      val rightInput = MemoryStream[(Int, Int, Int)]
+      val left = leftInput.toDF()
+        .select($"_1".as("leftKey"), timestamp_seconds($"_2").as("leftTime"))
+        .withWatermark("leftTime", "0 seconds")
+      val right = rightInput.toDF()
+        .select($"_1".as("rightKey"), timestamp_seconds($"_2").as("rightTime"),
+          timestamp_seconds($"_3").as("rightExpiry"))
+        .withWatermark("rightTime", "0 seconds")
+      val joined = left.join(right, expr("leftKey = rightKey AND " +
+        "rightExpiry >= leftTime + INTERVAL 30 SECONDS AND " +
+        "leftTime >= rightTime - INTERVAL 1 HOUR"), "left_semi")
+        .select($"leftKey", $"leftTime".cast("int"))
+
+      testStream(joined)(
+        MultiAddData(leftInput, (7, 100, 0))(rightInput, (8, 100, 100)),
+        CheckNewAnswer(),
+        // Both watermarks are 100 seconds, and the right cutoff is 130 
seconds less 1 ms. The
+        // right row passes late filtering but is at or below the cutoff on 
rightTime, and the

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 
[90dfad8d848](https://github.com/apache/spark/pull/60279/commits/90dfad8d84808a6c4e00b41b0c6ffa24c713db31).
 You are right that the legacy-mode test with a second right column cannot 
reach the same-batch decision: with equal watermarks, a right row that its 
batch evicts cannot match a left row that passes late filtering unless the 
cutoff is not exact. The test is renamed and its comment says that the right 
cutoff applies to `rightExpiry`, so the right row stays in state and matches 
the later left row, and that the default-mode test and the tests of the exact 
cutoffs cover the same-batch decision. A new test with the truncating-cast 
condition of the default-mode test, in legacy mode and skipped in state format 
4, makes the join store the right row that its batch evicts when the cutoff is 
not exact: with the left semi clause removed from the store decision, the left 
row at 100.6 seconds does not match. It is the same test as in #60279.
   
   <!-- sp2k-review11 reply 4598420050 -->
   



##########
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) {
+      val leftOrdinal = StreamingJoinHelper.getEventTimeKeyOrdinal(leftKeys, 
leftAttributes)
+      val rightOrdinal = StreamingJoinHelper.getEventTimeKeyOrdinal(rightKeys, 
rightAttributes)
+      val alignedOwnEventTimeKeys = leftOrdinal.isDefined && leftOrdinal == 
rightOrdinal &&
+        leftOrdinals == leftOrdinal.toSeq && rightOrdinals == 
rightOrdinal.toSeq
+      // One input's own event-time key paired with a forward shift of the 
other input's.
+      def forwardShiftedKey(
+          ownOrdinal: Option[Int],
+          ownWatermarkOrdinals: Seq[Int],
+          shiftedKeys: Seq[Expression],
+          shiftedAttributes: Seq[Attribute],
+          shiftedWatermarkOrdinals: Seq[Int],
+          shiftedSide: JoinSide): Boolean = ownOrdinal.exists { ordinal =>
+        ownWatermarkOrdinals == Seq(ordinal) && 
shiftedWatermarkOrdinals.isEmpty &&
+          StreamingJoinHelper.isForwardShiftOfEventTime(shiftedKeys(ordinal), 
shiftedAttributes) &&
+          leftKeys.indices.filter(_ != ordinal).forall { i =>
+            !(leftKeys(i).references ++ rightKeys(i).references)
+              .exists(_.metadata.contains(delayKey))
+          } && !consumedSides(shiftedSide)
+      }
+      alignedOwnEventTimeKeys ||
+        forwardShiftedKey(leftOrdinal, leftOrdinals, rightKeys, 
rightAttributes, rightOrdinals,
+          RightSide) ||
+        forwardShiftedKey(rightOrdinal, rightOrdinals, leftKeys, 
leftAttributes, leftOrdinals,
+          LeftSide) ||
+        isOwnEventTimeIntervalJoin(leftAttributes, rightAttributes, leftKeys, 
rightKeys,
+          condition, leftEventTime.head, rightEventTime.head, consumedSides)
+    } else {
+      false
+    }
+  }
+
+  /**
+   * Whether every ordering conjunct compares the two inputs' TIMESTAMP event 
times, each only cast
+   * or offset by constants (see [[StreamingJoinHelper.isConstantOffsetOf]]), 
or gives no bound to
+   * either input in either version, and each event time either gets a range 
bound or gets none and
+   * is not in `consumedSides`. Each half of a BETWEEN counts as one conjunct, 
as the solver reads
+   * it. Older versions and this one solve such conjuncts the same way for 
columns with their own
+   * watermark, and older versions solved every column of an input but then 
found bounds only in the
+   * same conjuncts, so they derived the same value predicates, scan starts 
and V4 index columns,
+   * and neither evicts an input that gets no bound. Old V4 stored a null 
event time at timestamp 0
+   * under the row's own key; both versions scan that entry the same way. No 
equality key may use an

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 
[90dfad8d848](https://github.com/apache/spark/pull/60279/commits/90dfad8d84808a6c4e00b41b0c6ffa24c713db31).
 The scaladoc of the interval-join rule now says what the first batch after 
restoring an older generation does: it scans V4 state from the start, evicts a 
row that an older version stored at timestamp 0 with a NULL event time, and a 
preserved side emits it padded with nulls, which older versions never did, and 
that this scan must stay.
   
   <!-- sp2k-review11 reply 4598420046 -->
   



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