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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -717,21 +727,94 @@ 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.
+    // The check takes the generated key and the input row, so the key is 
computed only once.
+    private[this] val isEvictionColumnNull: (UnsafeRow, UnsafeRow) => Boolean =
+      stateWatermarkPredicate match {
+        case Some(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
+          (key, _) => key.isNullAt(ordinal)
+        case Some(JoinStateValueWatermarkPredicate(expr, _, _)) =>
+          val isNull = Predicate.create(IsNull(expr), inputAttributes)

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 
[c984d5cd38b](https://github.com/apache/spark/pull/60279/commits/c984d5cd38be5c8c24dd2120235af9ceb2db4dfc).
 The null check now tests the compared column (or the window end), not the 
whole `column <= cutoff` predicate. The generated code no longer contains the 
cutoff, so it does not change from batch to batch. The existing NULL range-end 
and NULL window tests pass in formats 2, 3 and 4.
   
   <!-- sp2k-review3 reply 4537966885 -->
   



##########
docs/streaming/ss-migration-guide.md:
##########
@@ -25,6 +25,39 @@ Please refer [Migration Guide: SQL, Datasets and 
DataFrame](../sql-migration-gui
 
 ## Upgrading from Structured Streaming 4.3 to 4.4
 
+- Spark 4.4 holds back the output watermark of a stream-stream join when 
retained state can
+  still emit old event times. Downstream stateful operators may retain more 
state, take longer
+  to finalize results, or stop making progress while the join has no 
event-time eviction bound.
+  The join holds back only for an input whose event time reaches the next 
stateful operator: in
+  a join on `clickTime <= impressionTime + INTERVAL 1 HOUR`, a window 
aggregation over
+  `impressionTime` makes progress, and one over `clickTime` does not. Spark 
follows the event
+  time through projections, filters, unions, and time and session windows, to 
aggregations,
+  deduplication, stream-stream joins, and `flatMapGroupsWithState` or 
`transformWithState` with
+  event-time timeouts. When Spark cannot tell which input's event time the 
operator uses, for
+  example when the operator's event time is computed from the join output by a 
function, it
+  holds back for both inputs.
+
+- When restarting a stream-stream join from an older Spark version, Spark may 
reject the
+  existing checkpoint with `STREAMING_JOIN_CHECKPOINT_INCOMPATIBLE`. Spark 
reuses the checkpoint
+  of a join without watermarks, of a join with an equality condition between 
the two inputs'
+  event times, such as `leftTime = rightTime`, and of a join whose time 
condition compares the
+  two inputs' event times, optionally cast, with constant intervals or 
numbers, such as

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 
[c984d5cd38b](https://github.com/apache/spark/pull/60279/commits/c984d5cd38be5c8c24dd2120235af9ceb2db4dfc).
 The guide now says the condition "compares the two inputs' event times with 
each other, each optionally cast and offset by constant intervals or numbers". 
A comparison of one event time with a constant no longer fits the wording.
   
   <!-- sp2k-review3 reply 4537966892 -->
   



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelperSuite.scala:
##########
@@ -48,6 +50,30 @@ class StreamingJoinHelperSuite extends AnalysisTest {
     }
   }
 
+  test("state watermark extraction ignores columns outside both attribute 
sets") {
+    val leftTime = AttributeReference("leftTime", TimestampType)()
+    val leftOffset = AttributeReference("leftOffset", LongType)()
+    val metadata = new MetadataBuilder().putLong(EventTimeWatermark.delayKey, 
1000).build()
+    val rightTime = AttributeReference("rightTime", TimestampType, metadata = 
metadata)()
+    val rightDelay = AttributeReference("rightDelay", DayTimeIntervalType())()
+    val conditions = Seq(
+      leftTime > TimestampAddInterval(rightTime, rightDelay),
+      leftTime.cast(LongType) + leftOffset > rightTime.cast(LongType))
+    val logAppender = new LogAppender("state watermark extraction")
+    withLogAppender(logAppender, level = Some(Level.WARN)) {
+      conditions.foreach { condition =>
+        withClue(condition.sql) {
+          // Eviction passes only the constrained column and the opposite 
event time.

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 
[c984d5cd38b](https://github.com/apache/spark/pull/60279/commits/c984d5cd38be5c8c24dd2120235af9ceb2db4dfc).
 The test comment now names the callers per condition. The first condition 
reaches the references check through the V4 range scan and the left semi exact 
cutoff. Eviction already returns `None` for it. The second condition also 
reaches the check through eviction, because `leftOffset` is in neither 
attribute set.
   
   <!-- sp2k-review3 reply 4537966899 -->
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -296,6 +292,229 @@ object StreamingSymmetricHashJoinHelper extends Logging {
     JoinStateWatermarkPredicates(leftStateWatermarkPredicate, 
rightStateWatermarkPredicate)
   }
 
+  /** Keep each cutoff attached to the column constrained by the join 
condition. */
+  private def getStateValueWatermarkForInput(
+      inputAttributes: Seq[Attribute],
+      otherInputAttributes: Seq[Attribute],
+      condition: Option[Expression],
+      eventWatermark: Option[Long]): Option[(Attribute, Long)] = {
+    val eventTime = inputAttributes.find(_.metadata.contains(delayKey))
+    // First try the watermarked column. If it has no inferable bound, try the 
other timestamp
+    // columns in input schema order and use the first with a bound. This 
makes the indexed column
+    // deterministic for a fixed input schema and join condition.
+    val candidates = eventTime.toSeq ++ inputAttributes.filter { attribute =>
+      attribute.dataType == TimestampType && 
!eventTime.exists(_.semanticEquals(attribute))
+    }
+    candidates.iterator.flatMap { attribute =>
+      StreamingJoinHelper.getStateValueWatermark(AttributeSet(Seq(attribute)),
+        AttributeSet(otherInputAttributes), condition, 
eventWatermark).map(attribute -> _)
+    }.take(1).toSeq.headOption
+  }
+
+  /**
+   * 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 its event 
time:
+   * `consumedSides` names the inputs whose event time such an operator reads, 
both when the
+   * operator cannot be traced and none when no stateful operator follows. 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.
+   */
+  private[sql] def isWatermarkCheckpointCompatible(
+      leftAttributes: Seq[Attribute],
+      rightAttributes: Seq[Attribute],
+      leftKeys: Seq[Expression],
+      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
+      }
+    }
+
+    def ownEventTimeKeyOrdinal(keys: Seq[Expression], eventTime: Attribute): 
Option[Int] = {
+      keys.zipWithIndex.collectFirst {
+        case (key: NamedExpression, index)
+            if key.metadata.contains(delayKey) && 
key.semanticEquals(eventTime) => 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 = ownEventTimeKeyOrdinal(leftKeys, leftEventTime.head)
+      val rightOrdinal = ownEventTimeKeyOrdinal(rightKeys, rightEventTime.head)
+      val alignedOwnEventTimeKeys = leftOrdinal.isDefined && leftOrdinal == 
rightOrdinal &&
+        leftOrdinals == leftOrdinal.toSeq && rightOrdinals == 
rightOrdinal.toSeq
+      alignedOwnEventTimeKeys || 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]]), and each event
+   * time either gets a range bound or gets none and is not in 
`consumedSides`. 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 event time: older versions evicted such keys at the unshifted 
watermark. Time windows
+   * are excluded: older versions derived an ordering bound for them that this 
version removes.
+   */
+  private def isOwnEventTimeIntervalJoin(
+      leftAttributes: Seq[Attribute],
+      rightAttributes: Seq[Attribute],
+      leftKeys: Seq[Expression],
+      rightKeys: Seq[Expression],
+      condition: Option[Expression],
+      leftEventTime: Attribute,
+      rightEventTime: Attribute,
+      consumedSides: Set[JoinSide]): 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.isConstantOffsetOf(e, _))
+    def comparesInputs(a: Expression, b: Expression): Boolean =
+      (eventTimeOf(a), eventTimeOf(b)) match {
+        case (Some(x), Some(y)) => !x.semanticEquals(y)
+        case _ => false
+      }
+    // The solver reads bounds only from these conjunct shapes; other 
conjuncts give no bound in
+    // either version.
+    val conditionIsInterval = condition.toSeq.flatMap(conjuncts).forall {
+      case c @ (_: LessThan | _: LessThanOrEqual | _: GreaterThan | _: 
GreaterThanOrEqual) =>
+        val comparison = c.asInstanceOf[BinaryComparison]
+        comparesInputs(comparison.left, comparison.right)
+      case Between(input, lower, upper, _) =>
+        comparesInputs(input, lower) && comparesInputs(input, upper)
+      case _ => true
+    }
+    val keysUseEventTime = (leftKeys ++ rightKeys).exists(
+      _.references.exists(_.metadata.contains(delayKey)))
+    def boundsEventTime(
+        predicate: Option[JoinStateWatermarkPredicate], eventTime: Attribute): 
Boolean = {
+      predicate.exists {
+        case JoinStateValueWatermarkPredicate(e, _, _) => 
e.references.contains(eventTime)
+        case _ => false
+      }
+    }
+    val timestampEventTimes =
+      leftEventTime.dataType == TimestampType && rightEventTime.dataType == 
TimestampType
+    !keysUseEventTime && timestampEventTimes && conditionIsInterval && {
+      // The cutoffs are the watermark plus constants, so any watermark shows 
whether they exist.
+      val predicates = getStateWatermarkPredicates(leftAttributes, 
rightAttributes, leftKeys,
+        rightKeys, condition, Some(1000000L), None, useFirstEventTimeColumn = 
false)
+      def sameEviction(
+          predicate: Option[JoinStateWatermarkPredicate],
+          eventTime: Attribute,
+          side: JoinSide): Boolean = {
+        boundsEventTime(predicate, eventTime) || predicate.isEmpty && 
!consumedSides(side)
+      }
+      sameEviction(predicates.left, leftEventTime, LeftSide) &&
+        sameEviction(predicates.right, rightEventTime, RightSide)
+    }
+  }
+
+  /**
+   * For the right input of a left semi join, cutoffs at the late-events 
watermark that are exact
+   * today: no left row that passes late filtering can match a right row at or 
below them. Returns
+   * a predicate on the right join key and a predicate on the right input row, 
either of which
+   * can be absent.
+   *
+   * The key cutoff applies when the left input's late-filtered column is the 
left join key at an
+   * ordinal: the right key at that ordinal must then be above the late-events 
watermark. The
+   * value cutoff is on the right event time, solved only from conjuncts that 
compare it with the
+   * left input's late-filtered column, each shifted only by literal intervals 
without a day or
+   * month part, and with no cast. Any other conjunct can give a cutoff that 
is too high, so it
+   * gives none here: for example a bound on another right column, an interval 
with whole days,
+   * or a truncating cast.
+   * TODO(SPARK-61344, SPARK-61381): derive exact cutoffs for those conditions 
too.
+   */
+  def getLeftSemiExactRightCutoffs(
+      leftAttributes: Seq[Attribute],
+      rightAttributes: Seq[Attribute],
+      leftKeys: Seq[Expression],
+      rightKeys: Seq[Expression],
+      condition: Option[Expression],
+      eventTimeWatermarkForLateEvents: Option[Long],
+      useFirstEventTimeColumn: Boolean): (Option[Expression], 
Option[Expression]) = {
+    // The column the left input's late filter compares with the late-events 
watermark.
+    val leftLateFiltered = WatermarkSupport.findEventTimeColumn(leftAttributes,
+      allowMultipleEventTimeColumns = useFirstEventTimeColumn)
+    val rightEventTime = WatermarkSupport.findEventTimeColumn(rightAttributes,
+      allowMultipleEventTimeColumns = useFirstEventTimeColumn)
+
+    val keyCutoff = leftLateFiltered.flatMap { column =>
+      leftKeys.indexWhere(_.semanticEquals(column)) match {
+        case ordinal if ordinal >= 0 =>
+          val rightKey = BoundReference(
+            ordinal, rightKeys(ordinal).dataType, rightKeys(ordinal).nullable)
+          watermarkExpression(Some(rightKey), eventTimeWatermarkForLateEvents)
+        case _ => None
+      }
+    }
+
+    // Whether the expression is the column shifted only by literal intervals 
that the solver
+    // counts exactly: no whole days, which Spark adds in the session time 
zone, and no months.
+    def isExactShiftOf(e: Expression, column: Attribute): Boolean = e match {
+      case a: Attribute => a.semanticEquals(column)
+      case Cast(child, TimestampType, _, _) if child.dataType == TimestampType 
=>

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 
[77e611b42e4](https://github.com/apache/spark/pull/60279/commits/77e611b42e4bbd2ce927b0f89238b2e978099d8a)
 (on #60307, and it reaches this PR through the merge). The new left semi test 
uses a condition with a truncating cast, a late-events watermark of 100.5 
seconds, a left row at 100.6 seconds and a right row at 160.2 seconds. The two 
rows match after the cast. The test fails when we let `isExactShiftOf` accept a 
cast to BIGINT, because the left row is not emitted. We skip the test in state 
format 4, where the range scan already misses this match for a separate reason.
   
   <!-- sp2k-review3 reply 4537966906 -->
   



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