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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -51,6 +51,50 @@ object StreamingJoinHelper extends PredicateHelper with 
Logging {
     }
   }
 
+  /**
+   * Find the ordinal of the equality key whose watermark evicts the state of 
both inputs.
+   *
+   * 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.
+   */
+  def findJoinKeyOrdinalForWatermark(
+      leftKeys: Seq[Expression],
+      rightKeys: Seq[Expression]): Option[Int] = {
+    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
+      }
+    }
+  }
+
+  /**
+   * Whether an equality key of one input bounds, by that input's watermark, 
the equal key of the
+   * other input's state rows. Later rows of this input have keys above the 
watermark if the key
+   * is the watermarked column, or that column shifted forward by a constant. 
With a backward
+   * shift, they can still match state keys at or below the watermark, which 
eviction removes.
+   */
+  def isKeyBoundedByWatermark(key: Expression, inputAttributes: AttributeSet): 
Boolean = {
+    key match {
+      case a: AttributeReference => a.metadata.contains(delayKey) && 
inputAttributes.contains(a)
+      case _ if key.dataType == TimestampType =>
+        // Solving `stateKey >= key` at watermark 0 gives the shift less 1 ms.
+        val stateKey = AttributeReference("stateKey", TimestampType)()
+        getStateValueWatermark(AttributeSet(stateKey), inputAttributes,

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, agreed. Using the range solver to read the key's direction was the 
wrong tool. I
   replaced it with a classifier that reads the key itself, as in your shared 
plan. A key is
   bounded if it is the other input's watermarked column or the end of its 
watermarked window,
   optionally moved by an interval, TIMESTAMPADD/timestamp_add or a year-month 
interval whose
   foldable shift is not negative. The analyzer's no-op cast and `DatetimeSub` 
are looked through.
   I added checker rows for TIMESTAMPADD, a month interval and a window end; 
they failed before
   this change. The migration note now also says that a key in another form, 
such as a UDF of the
   event-time column, is rejected, and how to turn the check off.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -51,6 +51,50 @@ object StreamingJoinHelper extends PredicateHelper with 
Logging {
     }
   }
 
+  /**
+   * Find the ordinal of the equality key whose watermark evicts the state of 
both inputs.
+   *
+   * 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.
+   */
+  def findJoinKeyOrdinalForWatermark(
+      leftKeys: Seq[Expression],
+      rightKeys: Seq[Expression]): Option[Int] = {
+    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
+      }
+    }
+  }
+
+  /**
+   * Whether an equality key of one input bounds, by that input's watermark, 
the equal key of the
+   * other input's state rows. Later rows of this input have keys above the 
watermark if the key
+   * is the watermarked column, or that column shifted forward by a constant. 
With a backward
+   * shift, they can still match state keys at or below the watermark, which 
eviction removes.
+   */
+  def isKeyBoundedByWatermark(key: Expression, inputAttributes: AttributeSet): 
Boolean = {
+    key match {
+      case a: AttributeReference => a.metadata.contains(delayKey) && 
inputAttributes.contains(a)
+      case _ if key.dataType == TimestampType =>
+        // Solving `stateKey >= key` at watermark 0 gives the shift less 1 ms.
+        val stateKey = AttributeReference("stateKey", TimestampType)()
+        getStateValueWatermark(AttributeSet(stateKey), inputAttributes,
+          Some(GreaterThanOrEqual(stateKey, key)), Some(0L)).exists(_ >= -1)

Review Comment:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM: Claude Opus 5.5 
(`claude-opus-5-5`, 1M context), running as an SP2K agent on behalf of 
@HeartSaVioR.
   
   Thanks, confirmed: `rt - INTERVAL 1 MICROSECOND` passed the check. The new 
classifier compares
   the shift exactly, in months, days and microseconds, so any backward shift 
is rejected. There is
   a checker row for the 1 microsecond case now.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -733,5 +734,55 @@ object UnsupportedOperationChecker extends Logging {
           "is not supported without a watermark in the join keys, or a 
watermark on " +
           "the nullable side and an appropriate range condition")(join)
     }
+
+    if 
(SQLConf.get.getConf(SQLConf.STREAMING_JOIN_CHECK_WATERMARK_DIRECTION_ENABLED)) 
{
+      checkStreamStreamJoinWatermarkDirection(join)
+    }
+  }
+
+  /**
+   * The rows of an input that the join outputs once, unmatched rows of an 
outer join or the
+   * matched rows of a left semi join, are final only if later rows of the 
other input cannot
+   * match them. So the other input's watermark must bound this input's state, 
through the
+   * equality key that eviction uses or through a range condition.
+   */
+  private def checkStreamStreamJoinWatermarkDirection(join: Join): Unit = {
+    val (leftKeys, rightKeys) = join match {
+      case ExtractEquiJoinKeys(_, leftKeys, rightKeys, _, _, _, _, _) => 
(leftKeys, rightKeys)
+      case _ => (Nil, Nil)
+    }
+    val keyOrdinal = 
StreamingJoinHelper.findJoinKeyOrdinalForWatermark(leftKeys, rightKeys)
+
+    def checkInput(
+        stateSide: String,
+        state: LogicalPlan,
+        otherSide: String,
+        other: LogicalPlan,
+        otherKeys: Seq[Expression]): Unit = {
+      val boundedByKey = keyOrdinal.exists { ordinal =>
+        StreamingJoinHelper.isKeyBoundedByWatermark(otherKeys(ordinal), 
other.outputSet)
+      }
+      val boundedByRange = StreamingJoinHelper.getStateValueWatermark(

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.
   
   You're right that the range arm lets these through, and I reproduced both 
examples end to end:
   the backward key with an extra range emits `(1, 35, null)` and loses `(1, 
35, 45)`, and the
   orders/shipments join emits `(1, 20, null)` and loses `(1, 20, 50)`. Master 
accepts both queries
   and loses the same rows, because this PR does not change eviction. They are 
the existing
   SPARK-62002 (backward-shifted key) and SPARK-61989 (key the other watermark 
does not bound)
   defects. A correct range arm needs a microsecond-precise bound on the key 
column, and simply
   ignoring ranges when a key exists would reject joins such as `lt = rk2 AND 
lt >= rt` that work
   today. So I'd like to keep this PR as it is; those two tickets track it.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -733,5 +734,55 @@ object UnsupportedOperationChecker extends Logging {
           "is not supported without a watermark in the join keys, or a 
watermark on " +
           "the nullable side and an appropriate range condition")(join)
     }
+
+    if 
(SQLConf.get.getConf(SQLConf.STREAMING_JOIN_CHECK_WATERMARK_DIRECTION_ENABLED)) 
{
+      checkStreamStreamJoinWatermarkDirection(join)
+    }
+  }
+
+  /**
+   * The rows of an input that the join outputs once, unmatched rows of an 
outer join or the
+   * matched rows of a left semi join, are final only if later rows of the 
other input cannot
+   * match them. So the other input's watermark must bound this input's state, 
through the
+   * equality key that eviction uses or through a range condition.
+   */
+  private def checkStreamStreamJoinWatermarkDirection(join: Join): Unit = {
+    val (leftKeys, rightKeys) = join match {
+      case ExtractEquiJoinKeys(_, leftKeys, rightKeys, _, _, _, _, _) => 
(leftKeys, rightKeys)
+      case _ => (Nil, Nil)
+    }
+    val keyOrdinal = 
StreamingJoinHelper.findJoinKeyOrdinalForWatermark(leftKeys, rightKeys)
+
+    def checkInput(
+        stateSide: String,
+        state: LogicalPlan,
+        otherSide: String,
+        other: LogicalPlan,
+        otherKeys: Seq[Expression]): Unit = {
+      val boundedByKey = keyOrdinal.exists { ordinal =>
+        StreamingJoinHelper.isKeyBoundedByWatermark(otherKeys(ordinal), 
other.outputSet)
+      }
+      val boundedByRange = StreamingJoinHelper.getStateValueWatermark(
+        state.outputSet, other.outputSet, join.condition, 
Some(1000000)).isDefined
+      if (!boundedByKey && !boundedByRange) {
+        val confKey = 
SQLConf.STREAMING_JOIN_CHECK_WATERMARK_DIRECTION_ENABLED.key
+        throwError(
+          s"Stream-stream ${join.joinType} join between two streaming 
DataFrame/Datasets " +
+            s"is not supported without a watermark on the $otherSide input 
that bounds the " +
+            s"state of the $stateSide input, through an equality on the 
$otherSide input's " +
+            "event-time column or a range condition. Otherwise, late rows of 
the " +
+            s"$otherSide input can match $stateSide rows that were already 
output. To " +

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. The message now says that a later row of the other input can 
match a row the
   join already evicted. That covers both cases: an outer join already output 
it with NULLs, and a
   left semi join dropped it. The scaladoc and the conf doc say the same.



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