spark-test commented on code in PR #60666:
URL: https://github.com/apache/spark/pull/60666#discussion_r4615368755


##########
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:
   **Blocking (P1):** This call asks the range-condition solver whether the key 
is shifted forward, and `.exists(_ >= -1)` on the next line turns "no answer" 
into "not bounded". The solver's collectTerms 
(StreamingJoinHelper.scala:279-342) only parses Add, Subtract, 
TimestampAddInterval, DatetimeSub, UnaryMinus, CheckOverflow, casts, attributes 
and literals, so it has no answer for keys such as:
   
   - `lt = TIMESTAMPADD(SECOND, 10, rt)`, or `timestamp_add('SECOND', lit(10), 
col('rt'))` in the DataFrame API
   - `lt = rt + INTERVAL 1 MONTH` (TimestampAddYMInterval)
   - `lt = rw.end`, where `rw` is the right input's watermarked window
   - `lt = rt + make_dt_interval(0, 0, 0, 10)`, which analysis does not fold
   
   With watermarks on `lt` and `rt` and no range condition, a left outer join 
on `lk = rk` plus one of these keys passes the existing check, because `lt` is 
a watermarked join key, and then fails this check when the query starts. 
Restarts from existing checkpoints fail the same way. On the base branch these 
joins return correct results. For the 10-second shift, right state is evicted 
at `rt + 10 s <= W`, and a later right row passes late-row filtering only with 
`rt > W`, so its key is above every evicted `lt`. The conf doc says a key 
shifted forward by a constant is accepted. The only workaround is setting 
`spark.sql.streaming.join.checkWatermarkDirection.enabled` to false, which also 
turns the check off for the joins that do lose matches.
   
   See **Shared repair plan 1** in the review body.



##########
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:
   **Nit (P3):** For a left semi join this reason is wrong. A left row that 
matches is output once, and is then either not stored or removed from state 
(StreamingSymmetricHashJoinExec.scala:855-862, 900-902), so no later right row 
can affect a row that was already output. A left semi join loses unmatched left 
rows that eviction removed without output 
(StreamingSymmetricHashJoinExec.scala:608) before a matching right row arrived. 
The same reason appears in the scaladoc 
(UnsupportedOperationChecker.scala:744-746) and the conf doc 
(SQLConf.scala:4409). The message could say that late rows can match rows 
already output with NULLs for an outer join, or, for a left semi join, left 
rows that were evicted without output.
   
   **Verification:**
   - **Behavior:** A rejected left semi stream-stream join reports that late 
right rows can match left rows evicted without output, and a rejected left 
outer join still reports that they can match left rows already output.



##########
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:
   **Non-blocking (P2):** This range arm credits any bound the solver derives 
for the checked input, but eviction never uses that bound when a watermarked 
equality key exists. getStateWatermarkPredicates then evicts both inputs by the 
key at the eviction ordinal (StreamingSymmetricHashJoinHelper.scala:237-263), 
and it applies a range-derived bound only when there is no such key 
(StreamingSymmetricHashJoinHelper.scala:264). So a range conjunct exempts keyed 
joins that the key check would reject. For example, take a left outer join of 
orders (watermark on `orderTime`) with shipments (watermark on `shipTime`) on 
`o.id = s.orderId AND o.orderTime = s.orderTime AND s.shipTime >= o.orderTime 
AND s.shipTime <= o.orderTime + INTERVAL 7 DAYS`. It passes, because the upper 
bound gives orders a state value watermark. Eviction still removes orders at 
`orderTime <= W`, so an unmatched order is output with NULLs. A shipment for 
that order that arrives in a later batch, above the watermark, then fi
 nds nothing to match. Likewise, `lk = rk AND lt = rt - INTERVAL 10 SECONDS AND 
lt >= rt - INTERVAL 20 SECONDS` passes, although the same key without the last 
conjunct is rejected. Ignoring ranges whenever a key exists would go too far: a 
range that bounds the key column at least as tightly as key eviction, as in `lt 
= rk2 AND lt >= rt` with `rt` watermarked, is safe, and the base branch runs it 
correctly.
   
   **Recommended change:** Make the range arm of the watermark-direction check 
credit a range only where eviction applies a bound that the range implies. In 
checkInput in UnsupportedOperationChecker, when the shared key ordinal exists, 
credit a range condition only if it bounds the checked input's own key column 
at that ordinal tightly enough: every later row of the other input that passes 
late-row filtering must be able to match only keys above the eviction 
watermark. Compute that bound at microsecond precision, taking such rows to be 
strictly above the watermark, so that lt >= rt with rt watermarked still counts 
and lt >= rt - INTERVAL 1 MICROSECOND does not. Give no range credit when the 
key at the ordinal is not a column of the checked input. When no key ordinal 
exists, keep the current range test, which matches the state value watermark 
that eviction applies. In StreamingJoinHelper, add a way to get the solver's 
bound in microseconds without changing the millisecond value that e
 viction reads. Add checker tests that combine a watermarked key with range 
conditions.
   
   **Why this works:** When a watermarked equality key exists, eviction removes 
the state rows of both inputs whose key at the ordinal is at or below the 
eviction watermark, and it ignores range conditions. A removed row is final 
only if no later row of the other input can match a key in that range. A later 
row passes late-row filtering only if its watermark column is above the 
watermark. So a range that ties the state key column to that column, tightly 
enough that any key the row can match is above the watermark, proves the 
removed row final. A range on another column, or a looser one, says nothing 
about the rows eviction removes.
   
   **Compatibility:** Joins without a watermarked equality key, including range 
joins with both inputs watermarked and the one-sided full outer case, keep 
their current outcome, and eviction for every accepted query is unchanged.
   
   **Risks:** Keyed joins that pass today only because of a range on another 
column, or a looser range, fail at analysis. These joins can lose matches 
today, the migration guide entry already covers rejected joins, and setting 
spark.sql.streaming.join.checkWatermarkDirection.enabled to false restores the 
earlier check.
   
   **Constraints:** Keep the millisecond result of getStateValueWatermark 
unchanged, because eviction's state value watermark reads it. Keep the range 
test for joins without a key ordinal as it is.
   
   **Exclusions:**
   - Joins without a watermarked equality key whose range bounds a column other 
than the checked input's watermark column: eviction then applies the derived 
bound to the watermark column, a mismatch the base branch shares and that only 
an eviction change can remove.
   
   **Verification:**
   - **Regression:** For left outer, left semi, right outer and full outer 
joins, a keyed join whose other-input key is not bounded is rejected when its 
condition adds a range on a column other than the key, or a range that bounds 
the key column more loosely than key eviction.
   - **Behavior:** A keyed join is accepted when its range bounds the key 
column at or above the eviction watermark, such as lt >= rt with rt 
watermarked, and rejected when the same range is moved back by 1 microsecond.
   - **Compatibility:** Range joins without a watermarked equality key, 
including the one-sided full outer case, keep their current outcome with the 
watermark-direction check on and with it 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:
   **Non-blocking (P2):** The `>= -1` threshold cannot tell a backward shift 
shorter than 1 ms from no shift. The solver turns the microsecond sum into 
milliseconds with `(value / 1000.0).toLong` (StreamingJoinHelper.scala:249), 
which truncates toward zero, and the `>=` arm subtracts 1 
(StreamingJoinHelper.scala:149). So a shift of -1 to -999 microseconds gives 0 
- 1 = -1 and passes, while -1000 microseconds gives -2 and is rejected. 
Eviction and late-row filtering compare microseconds (`col <= W * 1000`, 
statefulOperators.scala:680-698), so these joins keep losing matches. For 
example, take `lt = rt - INTERVAL '0.0005' SECOND`. By the code, a left row at 
`lt = W*1000 - 200` microseconds is evicted and output with NULLs. A right row 
at `rt = lt + 500` microseconds that arrives in a later batch is above the 
late-row watermark, but it finds no left row to match.
   
   See **Shared repair plan 1** in the review body.



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

Review Comment:
   **Nit (P3):** This solve repeats, with the same arguments, the 
`hasValidWatermarkRange` call at UnsupportedOperationChecker.scala:714-718 
(both orderings at 719-725 for a full outer join). It runs even when 
`boundedByKey` already holds. Lines 750-753 also repeat the ExtractEquiJoinKeys 
match that `isWatermarkInJoinKeys` made at line 710. The cost is small, once 
per query start on the driver, but each repeated solve rebuilds and evaluates 
the term trees and logs the solver's INFO lines a second time. Passing the keys 
and range results that `checkForStreamStreamJoinWatermark` already computed, 
and evaluating the range arm only when the key does not bound the input, gives 
the same outcome without the repeated work.
   
   **Verification:**
   - **Inspection:** The two stream-stream join checks share one equi-join key 
extraction and at most one range solve per input and set of arguments, and the 
direction check skips the range solve for an input whose key already bounds it.



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