spark-test commented on code in PR #60666:
URL: https://github.com/apache/spark/pull/60666#discussion_r4619875062
##########
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)
+ }
+ }
+
+ /**
+ * When the join evicts an unmatched row of an input, an outer join outputs
it with NULLs and a
+ * left semi join drops it. Both are final only if later rows of the other
input cannot match
+ * the row. 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)
+ }
+ lazy 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, a later row of
the " +
+ s"$otherSide input can match a $stateSide row that the join
already evicted. To " +
Review Comment:
**Nit (P3):** For a full outer join without a watermarked equality key, such
as `lk = rk AND lt >= rt` with watermarks on `lt` and `rt`, this sentence says
a later left row can match a right row "that the join already evicted". As I
read `getStateWatermarkPredicates`, that join never evicts the right input:
with no key ordinal, the right side's predicate comes from
`getStateValueWatermark`, which finds no bound, so no predicate is installed
(StreamingSymmetricHashJoinHelper.scala:264-287). With the check off, the join
would keep the right state forever and never output unmatched right rows; it
would not lose a match. The conf doc at SQLConf.scala:4409 gives the same
reason. Choosing the sentence by whether a key ordinal exists would keep the
current wording for keyed joins, where key eviction removes both inputs, and
could say for keyless ones that the join never evicts that input's state, so
its unmatched rows are never output. Only full outer joins reach the keyless
case, becaus
e the existing check already rejects keyless left outer, left semi and right
outer joins whose range leaves the output-once input unbounded.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60666#discussion_r4615368789).
**Verification:**
- **Behavior:** A full outer stream-stream join without a watermarked
equality key whose range condition bounds only the left input, with a watermark
only on the right input, is rejected with a message that asks for a watermark
on the left input to bound the right input's state and says that the join never
evicts the right input's state, without claiming that it already evicted a
right row.
- **Regression:** A left outer join on the event-time key with a watermark
only on the left input is still rejected with the message that a later right
row can match a left row the join already evicted.
##########
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)
+ }
+ }
+
+ /**
+ * When the join evicts an unmatched row of an input, an outer join outputs
it with NULLs and a
+ * left semi join drops it. Both are final only if later rows of the other
input cannot match
+ * the row. 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)
+ }
+ lazy val boundedByRange = StreamingJoinHelper.getStateValueWatermark(
Review Comment:
**Nit (P3):** This arm accepts an input whenever `getStateValueWatermark`
derives a bound, also for a join with a watermarked equality key, whose
eviction uses the key and ignores the range
(StreamingSymmetricHashJoinHelper.scala:237-262). For example, `lk = rk AND lt
= rt - INTERVAL 10 SECONDS AND lt >= rt - INTERVAL 20 SECONDS` passes, while
the same key without the last conjunct is rejected. Your reply in the earlier
thread on this line defers a precise arm to SPARK-62002 and SPARK-61989, which
is fine for this PR, but only that thread records the decision, and the
scaladoc at UnsupportedOperationChecker.scala:743-748 presents the range as an
equal alternative to the key. A TODO here naming both tickets and the keyed
joins this arm still accepts would keep a later change from building on the arm
as if it were complete.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60666#discussion_r4615368774).
**Verification:**
- **Inspection:** The comment at the range arm of the watermark-direction
check in UnsupportedOperationChecker.scala names SPARK-62002 and SPARK-61989
and says that the arm still accepts a join with a watermarked equality key when
a range condition bounds the checked input, although eviction then uses the key
and ignores the range, and the change touches no executable code.
##########
docs/streaming/ss-migration-guide.md:
##########
@@ -25,6 +25,16 @@ Please refer [Migration Guide: SQL, Datasets and
DataFrame](../sql-migration-gui
## Upgrading from Structured Streaming 4.3 to 4.4
+- Since Spark 4.4, a stream-stream left outer, left semi, right outer or full
outer join fails
+ analysis unless the watermark of the other input bounds the state of each
input whose rows the
+ join outputs once, as the join support table of the programming guide
requires. For example,
+ a left outer join on `leftTime = rightTime` with a watermark only on
`leftTime` is rejected:
+ a later right row could match a left row that was already output with NULLs.
So is a key
Review Comment:
**Nit (P3):** The sentence that starts with "So is a key" has two subjects
joined by "and", so it needs "So are", and what the check rejects is the joins
on those keys rather than the keys. For example: "So are joins on a key shifted
backward, such as `leftTime = rightTime - INTERVAL 10 SECONDS`, and on a key in
any other form than the event-time column shifted forward by constants, such as
a UDF of that column."
**Verification:**
- **Inspection:** The sentence about backward-shifted keys and keys in other
forms in the 4.4 entry of docs/streaming/ss-migration-guide.md uses a plural
verb for its compound subject and names the joins on those keys as what is
rejected.
##########
docs/streaming/ss-migration-guide.md:
##########
@@ -25,6 +25,16 @@ Please refer [Migration Guide: SQL, Datasets and
DataFrame](../sql-migration-gui
## Upgrading from Structured Streaming 4.3 to 4.4
+- Since Spark 4.4, a stream-stream left outer, left semi, right outer or full
outer join fails
+ analysis unless the watermark of the other input bounds the state of each
input whose rows the
+ join outputs once, as the join support table of the programming guide
requires. For example,
+ a left outer join on `leftTime = rightTime` with a watermark only on
`leftTime` is rejected:
+ a later right row could match a left row that was already output with NULLs.
So is a key
+ shifted backward, such as `leftTime = rightTime - INTERVAL 10 SECONDS`, and
a key in a form
+ other than the event-time column shifted forward by constants, such as a UDF
of that column.
+ A full outer join needs watermarks on both inputs. To restore the earlier
check, set
Review Comment:
**Nit (P3):** The check runs at every query start, and
`spark.sql.streaming.join.checkWatermarkDirection.enabled` is not in
`OffsetSeqMetadata.relevantSQLConfs`, so an existing query with such a join,
for example one started on 4.3 with a left outer join on `leftTime = rightTime`
and a watermark only on `leftTime`, fails to restart from its checkpoint after
the upgrade. The `EXCEPT` and `toTable` entries at ss-migration-guide.md:38-49
state their restart outcome; this entry could add something like "As a result,
existing queries with such joins fail to restart. To keep the earlier check for
them, set the conf to `false` each time they restart, because the checkpoint
does not record it."
**Verification:**
- **Inspection:** The 4.4 entry for the watermark-direction check in
docs/streaming/ss-migration-guide.md states that existing checkpointed queries
with a rejected join fail to restart after the upgrade and that the opt-out
conf has to be set for each restart, as the other 4.4 entries in that section
state their restart outcome.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -51,6 +51,65 @@ 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 pass late-row
filtering only with the
+ * watermarked column, or the end of a watermarked window, above the
watermark. Their keys are
+ * above it too if the key is that column, or that column shifted forward by
constants. With a
+ * backward shift, or a key in another form, they can still match state keys
at or below the
+ * watermark, which eviction removes.
+ */
+ def isKeyBoundedByWatermark(key: Expression, inputAttributes: AttributeSet):
Boolean = {
+ def isWatermarked(a: AttributeReference): Boolean =
+ a.metadata.contains(delayKey) && inputAttributes.contains(a)
+ def isNotBackward(shift: Expression): Boolean = shift.foldable &&
(shift.eval() match {
+ case i: CalendarInterval => i.months >= 0 && i.days >= 0 &&
i.microseconds >= 0
+ case n: java.lang.Number => n.longValue >= 0
+ case _ => false
+ })
+ key match {
+ case a: AttributeReference => isWatermarked(a)
+ // NOTE: We assume this is window struct, as same as
WatermarkSupport.watermarkExpression
+ case GetStructField(a: AttributeReference, 1, _) => isWatermarked(a)
+ case Cast(child, TimestampType, _, _) if child.dataType == TimestampType
=>
+ isKeyBoundedByWatermark(child, inputAttributes)
+ case DatetimeSub(_, _, replacement) =>
isKeyBoundedByWatermark(replacement, inputAttributes)
+ case TimestampAddInterval(start, interval, _) =>
+ isNotBackward(interval) && isKeyBoundedByWatermark(start,
inputAttributes)
+ case TimestampAddYMInterval(start, interval, _) =>
Review Comment:
**Nit (P3):** `lt = rt - INTERVAL 1 MONTH` resolves to `DatetimeSub` over
`TimestampAddYMInterval` with a negated literal
(BinaryArithmeticWithDatetimeResolver.scala:118-120), so only the guard in this
arm rejects it, and the suite's only row for this arm, 'month interval
forward', accepts. Likewise, every `CalendarInterval` in the new rows has zero
months and days, so dropping `i.months >= 0` or `i.days >= 0` at
StreamingJoinHelper.scala:92 also keeps the suite green, and no row has a
non-constant shift. Rejecting rows for a backward month interval in the
analyzer's resolved form, a calendar interval of minus one day and of minus one
month, and a `TIMESTAMPADD` whose quantity is a right-input column would pin
each guard.
**Verification:**
- **Regression:** With watermarks on both inputs, a left outer join whose
right key is the right event-time column moved back by one month in the
analyzer's resolved subtraction form, by a calendar interval of minus one day,
or by a calendar interval of minus one month is rejected naming the right
input, and each of these cases fails when the corresponding guard of the key
classifier is removed.
- **Behavior:** A left outer join whose right key is the right event-time
column moved by a TIMESTAMPADD whose quantity is a column of the right input is
rejected with the analysis error that names the right input, not an internal
evaluation error.
##########
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)
+ }
+ }
+
+ /**
+ * When the join evicts an unmatched row of an input, an outer join outputs
it with NULLs and a
+ * left semi join drops it. Both are final only if later rows of the other
input cannot match
+ * the row. 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)
+ }
+ lazy 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, a later row of
the " +
+ s"$otherSide input can match a $stateSide row that the join
already evicted. To " +
+ s"skip this check, set $confKey to false.")(join)
+ }
+ }
+
+ join.joinType match {
+ case LeftOuter | LeftSemi => checkInput("left", join.left, "right",
join.right, rightKeys)
+ case RightOuter => checkInput("right", join.right, "left", join.left,
leftKeys)
Review Comment:
**Nit (P3):** The message names the input from the labels passed on this
line, but the rows that reach it ('RightOuter join with stream-stream relations
and join on attribute with right watermark', 'RightOuter join on event time
with right watermark only') assert only "without a watermark on the" and "that
bounds the state of the". Swapping the labels here, or at the first full outer
call at UnsupportedOperationChecker.scala:783, would make the message point
users at the wrong input, and every test would still pass. Asserting the named
input in each rejection row, as the left outer rows and the one-sided full
outer row already do, would catch it.
**Verification:**
- **Regression:** Each rejection row of the watermark-direction check fails
when the side labels passed for a right outer join, or for the first input
checked of a full outer join, are swapped in UnsupportedOperationChecker.scala,
because the row asserts which input the message names.
##########
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:
Thanks for reproducing both cases and confirming that master loses the same
rows. Keeping the range arm as it is in this PR and tracking a precise version
in SPARK-62002 and SPARK-61989 is fine. Because only this thread records that
decision, this review raises a separate small follow-up about recording the
deferral in the code.
<!-- SPARK_DEV_REVIEW_REPLY
{"feedback_id":"inline:4615368774","thread_id":"inline:4615368774","verdict_sha256":"8ac68bbc6cc596112f1495d0c1aaef3594249234d81df8428a5bb1692bceaa5a"}
-->
--
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]