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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -224,98 +228,221 @@ 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)
       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, 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)
+          }
         }
-        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.
+        val otherSideEventTime = 
otherSideInputAttributes.find(_.metadata.contains(delayKey))
+        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(otherSideEventTime.toSeq), 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))
+    // Only the first marked column is checked for late input in compatibility 
mode.
+    val otherEventTime = 
otherInputAttributes.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(otherEventTime.toSeq), condition, eventWatermark,
+        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. 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, both parts are fixed in SPARK-61344 (#60279).
   
   - **Whole-day intervals** 
([f9762a3d955](https://github.com/apache/spark/pull/60279/commits/f9762a3d9553a75e07fe884d6a60ef3253a2b8d1)).
 The restart check 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. SPARK-61345 (#60280) uses the same check instead of the 
exact-shift test 
([9c618562e01](https://github.com/apache/spark/pull/60280/commits/9c618562e0186b65f8fd2cae49f1c34bd7fb802c)).
 Both versions count a day as 24 hours in every zone, so an older checkpoint of 
`leftKey = rightKey AND rightTime >= leftTime AND rightTime <= leftTime + 
INTERVAL 1 DAY` resumes in UTC and in America/Los_Angeles. Month intervals have 
no fixed length and are still rejected.
   - **Key-only joins** 
([f9762a3d955](https://github.com/apache/spark/pull/60279/commits/f9762a3d9553a75e07fe884d6a60ef3253a2b8d1)).
 A join with only equality conditions on columns other than event times, and no 
other condition, is now accepted when no stateful operator follows it. Neither 
version evicts its state, and V4 reads its rows by key prefix in both, so only 
its output watermark changed. A key-only join followed by a stateful operator 
is still rejected. The older version passed its input watermark downstream 
although the join keeps every row, so the downstream operator may already have 
finalized and evicted results that later join output still changes, and reusing 
that state would keep them.
   - **Also accepted now** 
([f9762a3d955](https://github.com/apache/spark/pull/60279/commits/f9762a3d9553a75e07fe884d6a60ef3253a2b8d1)),
 after the review of SPARK-61350 (#60286): casts of the event times, such as 
`CAST(rightTime AS BIGINT) >= CAST(leftTime AS BIGINT)`, which both versions 
read as the event times. Also accepted: an input that gets no bound in either 
version, such as the right input of `rightTime <= leftTime + INTERVAL 5 
SECONDS`, when the output-watermark tracer shows that no stateful operator 
after the join reads its event time. The key-only rule above is a case of this.
   - **Still rejected.** Keys computed from an event time, such as `CAST(lt AS 
DATE) = CAST(rt AS DATE)`: later PRs in this stack derive cutoffs from some of 
those keys, so this check cannot show that their state means the same. Inputs 
without their own watermark, and expiry-bounded, shifted-key, numeric-expiry 
and constant-conjunct shapes also stay rejected before any state is opened.
   
   Tests: the compatibility suite resumes `INTERVAL 1 DAY` in UTC and 
America/Los_Angeles, `INTERVAL 24 HOURS` in a left outer join, and a key-only 
inner join in V2 and V4, which still matches a left row buffered before the 
restart. It rejects `INTERVAL 1 MONTH`, and a key-only join followed by 
deduplication in V1 to V4, with state and commits unchanged.
   
   <!-- sp2k-review2 reply 4531361623 -->
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -706,32 +707,66 @@ 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),
+          exactForUnwatermarkedColumns = true).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 " +

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-61345 (#60280, 
[9c618562e01](https://github.com/apache/spark/pull/60280/commits/9c618562e0186b65f8fd2cae49f1c34bd7fb802c)).
 The admission error now says that the join holds back its output watermark for 
that input. An append-mode aggregation over that event time then fails when the 
query starts. Other stateful operators that use it keep its state and do not 
emit results that wait for the watermark. The migration guide's equality-join 
entry says the same, and adds that update-mode aggregations and deduplication 
still emit rows.
   
   <!-- sp2k-review2 reply 4531361643 -->
   



##########
docs/streaming/apis-on-dataframes-and-datasets.md:
##########
@@ -1297,6 +1297,15 @@ joined <- join(
 Outer joins have the same guarantees as [inner 
joins](#semantic-guarantees-of-stream-stream-inner-joins-with-watermarking)
 regarding watermark delays and whether data will be dropped or not.
 
+Unmatched output and state removal use the same cutoff, derived from the 
opposite input's
+watermark and the time constraint. In the example above, the `clickTime` 
watermark finalizes
+impressions; no watermark on `impressionTime` is needed for this. Without that 
watermark, the
+time constraint must have an exact length: whole days in a session time zone 
with daylight saving

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 
[0ad26f2a1fa](https://github.com/apache/spark/pull/60282/commits/0ad26f2a1fadc24b49703e6d3d849eaf80f650e1),
 with the rule now independent of the time zone (see the reply on the V4 
layout). For a side that only such a bound would finalize, the analysis error 
now adds that the time constraint bounds that input only on a column without 
its own watermark, through an interval of a day or more or a truncating cast 
such as `CAST(ts AS BIGINT)`, and that the query should bound the input's 
watermarked event time instead or use a bound shorter than a day. The message 
still ends with the `spark.sql.streaming.join.checkFinalization.enabled` 
option, and a join that lacks the opposite watermark keeps the old message. The 
join guide and the migration guide now say that an interval of a day or more, 
such as `INTERVAL 1 DAY` or `INTERVAL 48 HOURS`, or a truncating cast, does not 
finalize an input without its own watermark in any session time zone, and say 
what to do instead.
   
   <!-- sp2k-review2 reply 4531361653 -->
   



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

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 
[f9762a3d955](https://github.com/apache/spark/pull/60279/commits/f9762a3d9553a75e07fe884d6a60ef3253a2b8d1).
 The row loop now generates the key once and checks the selected key with 
`isNullAt` on the generated key row. A value predicate still checks its column 
on the input row. The NULL-key and V4 null-window join tests return the same 
rows.
   
   <!-- sp2k-review2 reply 4531361665 -->
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -403,19 +408,21 @@ case class StreamingSymmetricHashJoinExec(
     // Create left and right side hash joiners and store in the joiner manager.
     // Both sides should use the same store generator if we are re-using the 
same store instance.
     val joinStateManagerStoreGenerator = new JoinStateManagerStoreGenerator()
-    val joinKeyOrdinalForWatermark =
-      
StreamingSymmetricHashJoinHelper.findJoinKeyOrdinalForWatermark(leftKeys, 
rightKeys)
     val joinerManager = OneSideHashJoinerManager(
       new OneSideHashJoiner(
         LeftSide, left.output, leftKeys, leftInputIter,
         condition.leftSideOnly, postJoinFilter, stateWatermarkPredicates.left, 
partitionId,
         checkpointIds.left.keyToNumValues, 
checkpointIds.left.keyWithIndexToValue,
-        skippedNullValueCount, joinStateManagerStoreGenerator, 
joinKeyOrdinalForWatermark),
+        skippedNullValueCount, joinStateManagerStoreGenerator,
+        getStateKeyOrdinalForLookup(

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).
 The exec now computes the two lookup ordinals once, on the driver when the 
plan executes, and only for state format V4. Tasks reuse them, and the other 
formats do not compute them at all. A new test counts the cutoff solver's log 
lines for a join on `lt = rt + INTERVAL 10 SECONDS`, and finds the same count 
with 1 and 5 partitions, in V2 and V4.
   
   <!-- sp2k-review2 reply 4531361674 -->
   



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