spark-test commented on code in PR #60668:
URL: https://github.com/apache/spark/pull/60668#discussion_r4622917322
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -710,18 +753,35 @@ case class StreamingSymmetricHashJoinExec(
Predicate.create(Literal(false), Seq.empty).eval _ // false = do not
remove if no predicate
}
+ private[this] var updatedStateRowsCount = 0
+ private[this] var numRemovedFromOtherSideDuringJoinCount = 0
+ private[this] val allowMultipleStatefulOperators: Boolean =
+ conf.getConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE)
+
+ // The join condition bounds the column that the value predicate tests, so
a row with a NULL
+ // in it can never match, and `column <= cutoff` never holds for it. The
legacy mode tests the
+ // event time even when the condition bounds another column. The same
holds for an equality
+ // key that the opposite watermark selects; the key that
findJoinKeyOrdinalForWatermark selects
+ // keeps the previous behavior.
+ private[this] val isEvictionColumnNull: UnsafeRow => Boolean =
stateWatermarkPredicate match {
+ case Some(JoinStateValueWatermarkPredicate(LessThanOrEqual(column, _),
_, _))
+ if allowMultipleStatefulOperators =>
Review Comment:
**Blocking (P1):** This guard also fires for the whole-input fallback that
StreamingSymmetricHashJoinHelper.scala:277-281 now takes when the condition
bounds an input only through a non-TIMESTAMP column. There the value predicate
tests the event time, which the condition never references, so the premise in
the comment above, that the condition bounds the tested column, does not hold.
By the review's reading of the code, for an inner join on `l.k = r.k AND
r.rightTime <= CAST(l.leftDate AS TIMESTAMP)` with watermarks on leftTime and
rightTime, a left row (1, NULL, DATE '2030-01-01') passes late filtering, since
`leftTime <= watermark` is not true for NULL, but IsNull(leftTime) holds, so
the row is neither probed nor stored (line 910) and the matching right row
finds nothing. A left outer join emits it null-padded instead of joined, and on
state formats 1 to 3 such rows that an earlier version stored are evicted at
the next eviction (line 780). Master joins and keeps the row, so the
change silently loses those matches.
This extends existing discussions
[1](https://github.com/apache/spark/pull/60668#issuecomment-6993169113),
[2](https://github.com/apache/spark/pull/60668#discussion_r4616349079).
See **Shared repair plan 1** in the review body.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -262,40 +262,68 @@ object StreamingSymmetricHashJoinHelper extends Logging {
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)
+ val eventTime =
oneSideInputAttributes.find(_.metadata.contains(delayKey))
+ // The legacy mode with a single global watermark keeps applying a
cutoff on any column of
+ // this input to the event time. So does the default mode when the
condition bounds no
Review Comment:
**Nit (P3):** This presents the fallback as the default mode's rule, but for
a condition such as `leftKey = rightKey AND CAST(leftDate AS TIMESTAMP) >
rightTime - INTERVAL 1 HOUR` the left input is still evicted by leftTime with
the cutoff solved for leftDate, so a left row with an old leftTime and a recent
leftDate can leave state before a matching right row arrives: the early
eviction this change fixes for TIMESTAMP columns. You deferred that as
SPARK-62044 in your reply, but nothing in the code names it, so a TODO here
would show readers that the fix is partial.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60668#issuecomment-6993169113).
**Verification:**
- **Inspection:** The comment above the default-mode whole-input fallback in
getStateWatermarkPredicates carries a TODO naming SPARK-62044 and says that
such inputs keep the base branch's early eviction by their event time.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -262,40 +262,68 @@ object StreamingSymmetricHashJoinHelper extends Logging {
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)
+ val eventTime =
oneSideInputAttributes.find(_.metadata.contains(delayKey))
+ // The legacy mode with a single global watermark keeps applying a
cutoff on any column of
+ // this input to the event time. So does the default mode when the
condition bounds no
+ // TIMESTAMP column, such as through a DATE column cast to TIMESTAMP
only.
+ def solve(watermark: Option[Long]): Option[(Attribute, Long)] = {
+ def wholeInput = eventTime.flatMap { e =>
+ StreamingJoinHelper.getStateValueWatermark(
+ attributesToFindStateWatermarkFor =
AttributeSet(oneSideInputAttributes),
+ attributesWithEventWatermark =
AttributeSet(otherSideInputAttributes),
+ condition,
+ watermark).map(e -> _)
+ }
+ if (useFirstEventTimeColumn) {
+ wholeInput
+ } else {
+
StreamingJoinHelper.getStateValueWatermarkColumn(oneSideInputAttributes,
+ AttributeSet(otherSideInputAttributes), condition,
watermark).orElse(wholeInput)
Review Comment:
**Nit (P3):** By the review's reading of the tests, dropping this
`.orElse(wholeInput)` passes every test in the change. For a left outer join on
`leftKey = rightKey AND CAST(leftDate AS TIMESTAMP) >= rightTime - INTERVAL 1
HOUR` with watermarks on leftTime and rightTime, the left input would then get
no state predicate in the default mode, so its state would never be evicted and
its unmatched rows never emitted, while analysis still accepts the join.
StreamingJoinHelperSuite only checks that getStateValueWatermarkColumn returns
None for a TIMESTAMP_NTZ cast, and StreamingSymmetricHashJoinHelperSuite and
the join suites bound only TIMESTAMP columns.
See **Shared repair plan 1** in the review body.
##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinEqualityWatermarkSuite.scala:
##########
@@ -0,0 +1,151 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.streaming
+
+import org.apache.spark.sql.{DataFrame, Row}
+import org.apache.spark.sql.execution.streaming.runtime.MemoryStream
+import org.apache.spark.sql.execution.streaming.state.RocksDBStateStoreProvider
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.tags.SlowSQLTest
+
+@SlowSQLTest
+class StreamingJoinEqualityWatermarkSuite extends StreamTest {
+ import testImplicits._
+
+ private def withJoinConf(version: Int)(f: => Unit): Unit = {
+ withSQLConf(
+ SQLConf.STREAMING_JOIN_STATE_FORMAT_VERSION.key -> version.toString,
+ SQLConf.STATE_STORE_PROVIDER_CLASS.key ->
classOf[RocksDBStateStoreProvider].getName,
+ SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> "false")(f)
+ }
+
+ // The watermarks are on different equality keys: la on the left and rb on
the right. A
+ // negative time gives a NULL key.
+ private def crossedKeyJoin()
+ : (MemoryStream[(Int, Int)], MemoryStream[(Int, Int)], DataFrame) = {
+ val leftInput = MemoryStream[(Int, Int)]
+ val rightInput = MemoryStream[(Int, Int)]
+ val left = leftInput.toDF().toDF("a", "b")
+ .select(timestamp_seconds($"a").as("la"),
+ when($"b" >= 0, timestamp_seconds($"b")).as("lb"))
+ .withWatermark("la", "10 seconds")
+ val right = rightInput.toDF().toDF("a", "b")
+ .select(timestamp_seconds($"a").as("ra"),
timestamp_seconds($"b").as("rb"))
+ .withWatermark("rb", "10 seconds")
+ val joined = left.join(right, expr("la = ra AND lb = rb"), "full_outer")
+ .select($"la".cast("int"), $"lb".cast("int"), $"ra".cast("int"),
$"rb".cast("int"))
+ (leftInput, rightInput, joined)
+ }
+
+ for {
+ version <- Seq(2, 3, 4)
+ restart <- Seq(false, true)
+ } {
+ test(s"equality eviction follows the opposite watermark, V$version
restart=$restart") {
+ withJoinConf(version) {
+ val (leftInput, rightInput, joined) = crossedKeyJoin()
+ withTempDir { checkpoint =>
+ val restartActions = if (restart) {
+ Seq(StopStream, StartStream(checkpointLocation =
checkpoint.getCanonicalPath))
+ } else {
+ Nil
+ }
+ testStream(joined)((Seq(
+ StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+ MultiAddData(leftInput, (5, 50))(rightInput, (80, 50)),
+ CheckNewAnswer(),
+ MultiAddData(leftInput, (60, 100))(rightInput, (70, 50)),
+ CheckNewAnswer(),
+ AddData(leftInput, (70, 100)),
+ // At watermark 40, left (5, 50) can still match fresh right input
on rb = 50.
+ CheckNewAnswer()) ++ restartActions ++ Seq(
+ AddData(rightInput, (5, 50)),
+ CheckNewAnswer(Row(5, 50, 5, 50)),
+ // Fresh on la, but already expired on lb: V4 must visit it below
the old cutoff.
+ AddData(leftInput, (90, 10)),
+ CheckNewAnswer(Row(90, 10, null, null)),
+ MultiAddData(leftInput, (200, 200))(rightInput, (200, 200)),
+ CheckNewAnswer(Row(200, 200, 200, 200)),
+ MultiAddData(leftInput, (210, 210))(rightInput, (210, 210)),
+ CheckNewAnswer(Row(210, 210, 210, 210), Row(60, 100, null, null),
+ Row(70, 100, null, null), Row(null, null, 80, 50), Row(null,
null, 70, 50))
+ )): _*)
+ }
+ }
+ }
+ }
+
+ // The legacy mode evicts both inputs by la and ra, as earlier versions did.
+ for (version <- Seq(2, 4)) {
+ test(s"equality eviction in the legacy mode keeps the earlier behavior,
V$version") {
+ withJoinConf(version) {
+ withSQLConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key -> "false") {
+ val (leftInput, rightInput, joined) = crossedKeyJoin()
+ testStream(joined)(
+ MultiAddData(leftInput, (5, 50))(rightInput, (80, 50)),
+ CheckNewAnswer(),
+ MultiAddData(leftInput, (60, 100))(rightInput, (70, 50)),
+ CheckNewAnswer(),
+ AddData(leftInput, (70, 100)),
+ CheckNewAnswer(Row(5, 50, null, null)),
+ AddData(rightInput, (5, 50)),
+ CheckNewAnswer(Row(null, null, 5, 50)),
+ MultiAddData(leftInput, (200, 200))(rightInput, (200, 200)),
+ CheckNewAnswer(Row(200, 200, 200, 200)))
+ }
+ }
+ }
+ }
+
+ // An earlier version, like the legacy mode, stored a row whose lb is NULL
and evicted it by la.
+ for (version <- Seq(2, 3)) {
+ test(s"a stored row whose eviction key is NULL is evicted, V$version") {
+ withJoinConf(version) {
+ val (leftInput, rightInput, joined) = crossedKeyJoin()
+ withTempDir { checkpoint =>
+ withSQLConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key -> "false")
{
+ testStream(joined)(
+ StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+ MultiAddData(leftInput, (5, -1))(rightInput, (80, 50)),
+ CheckNewAnswer(),
+ MultiAddData(leftInput, (60, 100))(rightInput, (70, 50)),
+ CheckNewAnswer(),
+ StopStream)
+ }
+ testStream(joined)(
+ StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+ AddData(leftInput, (70, 100)),
+ CheckNewAnswer(Row(5, null, null, null)))
+ }
+ }
+ }
+ }
+
+ for (version <- Seq(2, 4)) {
+ test(s"a row whose eviction key is NULL is emitted on arrival, V$version")
{
+ withJoinConf(version) {
+ val (leftInput, rightInput, joined) = crossedKeyJoin()
+ testStream(joined)(
+ // The row can never match, and the key predicate on lb never evicts
it.
Review Comment:
**Nit (P3):** Since this change the key predicate for lb is Or(lb <=
watermark, lb IS NULL) (StreamingSymmetricHashJoinExec.scala:743-747), and the
eviction watermark is already 0 in the first batch, so by the review's reading
of the code, without the arrival skip at
StreamingSymmetricHashJoinExec.scala:910 the (5, NULL) row would be stored and
then evicted at the end of batch 0, and the full outer join would still emit
Row(5, null, null, null). The test checks only CheckNewAnswer, so it passes
whether or not the skip works, and this comment states the opposite of what the
key predicate now does. StreamingJoinRangeEvictionSuite.scala:147 has the same
stale comment, though its state-row assertion still catches a stored row.
**Verification:**
- **Regression:** On state formats 2 and 4, the NULL-key arrival test fails
when the arrival skip for a key that the opposite watermark selects is removed,
because its updated-row count includes the stored row, and passes otherwise.
- **Inspection:** The comments in the NULL-key and NULL range-column arrival
tests say that such a row is not stored and would be evicted at the next
eviction, not that the eviction predicate never removes it.
##########
docs/streaming/ss-migration-guide.md:
##########
@@ -25,6 +25,27 @@ 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 join whose condition bounds an input with
its own watermark
+ only through another TIMESTAMP column, for example `rightTime BETWEEN
leftTime AND expiry`,
+ evicts the state of that input by the bounded column instead of its event
time. Earlier versions
+ could emit outer join rows too early and lose matches. Such a join can now
emit rows below its
+ output watermark, which still assumes eviction by the event time, so a
stateful operator after
+ it can drop them (SPARK-62001). With state format version 4, such a join
cannot restart from a
+ checkpoint of an earlier version, or after a change of
+ `spark.sql.streaming.statefulOperator.allowMultiple`; start it with a new
checkpoint. With
+ state format versions 1 to 3, it restarts, and rows that an earlier version
evicted are not
+ restored. With `spark.sql.streaming.statefulOperator.allowMultiple` set to
false, joins keep the
+ earlier behavior.
+
+- Since Spark 4.4, a stream-stream join whose inputs have watermarks on
different equality keys,
+ for example `la = ra AND lb = rb` with watermarks on `la` and `rb`, evicts
the state of each
+ input by the key that the opposite input's watermark bounds. Earlier
versions evicted both by
+ the same key and could lose matches. With state format version 4, such a
join cannot restart
+ from a checkpoint of an earlier version, or after a change of
+ `spark.sql.streaming.statefulOperator.allowMultiple`; start it with a new
checkpoint. With
+ `spark.sql.streaming.statefulOperator.allowMultiple` set to false, joins
keep the earlier
Review Comment:
**Non-blocking (P2):** Legacy mode keeps master's join eviction, but it also
filters late rows by the current batch's watermark instead of the previous
batch's, and its documentation (SQLConf.scala:4477-4485) allows only a single
stateful operator in a pipeline, so it does not restore master's default mode.
A state format 4 `l FULL OUTER JOIN r ON la = ra AND lb = rb` with watermarks
on la and rb now fails to restart from a checkpoint master wrote, and when that
join feeds an aggregation, legacy mode is no supported way back. On the default
state format, a left outer join on `rightTime BETWEEN leftTime AND expiry`
whose rows carry a far-future expiry now keeps them in state where master
evicted them by leftTime. A behavior change that can leave users worse off
needs a rollback setting of its own that restores master's behavior, so the
review asks for one.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60668#issuecomment-6993169113).
**Recommended change:** Add an internal boolean SQL conf, off by default,
whose on state restores the base branch's eviction choice in the default mode,
and persist it through OffsetSeqMetadata.relevantSQLConfs with no default for
checkpoints that lack it. Read it together with allowMultiple as one effective
switch wherever the code now passes `!allowMultipleStatefulOperators` for the
eviction choice: the eviction predicates that IncrementalExecution builds
through getStateWatermarkPredicates, whose multiple event-time column check
stays on allowMultiple, the per-side key in processPartitions, the arrival-time
NULL check and the extra NULL eviction in OneSideHashJoiner, the state format 4
restart check in doExecute, and the index version 0 that StreamExecution
records for a new query. Name the setting in both 4.3-to-4.4 migration entries
as the way to keep the earlier join behavior in the default mode, and add
equality-key and range-eviction join tests with the setting on.
**Why this works:** One effective switch, legacy mode or the new setting,
selects the base branch's eviction choice for every reader of it: with the
setting on, both inputs of `la = ra AND lb = rb` are evicted by the shared key
again, an input bounded only through another TIMESTAMP column is evicted by its
event time with the whole-input cutoff, the new NULL handling is off, and a new
query records state format 4 index version 0, so the restart check accepts a
checkpoint of an earlier version. Late-row filtering and watermark propagation
keep following allowMultiple, so the setting changes only the join's eviction.
Recording the value in the offset log keeps a checkpoint on one rule across
restarts.
**Compatibility:** Legacy mode keeps its behavior, and with the setting off,
its default, the default mode keeps the new eviction, NULL handling and state
format 4 ordering.
**Risks:** With the setting on, joins lose matches as on the base branch,
because it restores the base branch's eviction, including the early eviction
this change fixes. A checkpoint keeps the value it recorded, so rolling back a
query that already ran on this version with the setting off needs a new
checkpoint, and a restart that changes the session value only logs a warning.
**Constraints:** Leave late-row filtering, watermark propagation and the
multiple event-time column checks on allowMultiple alone; the new setting
changes only the join's eviction key and column, its NULL handling and the
state format 4 ordering. Give the setting no default for checkpoints that lack
it, so the session value applies when a checkpoint of an earlier version first
restarts on this version. Every reader of the eviction choice consults the same
effective switch, including the analysis check that rejects a stateful operator
after an outer join whose eviction moved, which runs before the offset log is
restored and so must read the value an existing checkpoint records, as
StreamingQueryManager already does for the streaming EXCEPT setting.
**Verification:**
- **Behavior:** With the setting on in the default mode, the crossed-key
full outer join and the left outer join on `rightTime BETWEEN leftTime AND
expiry` return the base branch's results on state formats 2 and 4, such as the
left row (5, 50) emitted unmatched once la passes the watermark, while a
downstream append-mode aggregation still filters late rows by the previous
batch's watermark.
- **Compatibility:** With the setting on, the bundled state format 4
checkpoint of an earlier version and a state format 4 checkpoint whose index
version was removed restart in the default mode and keep their results, and a
new query records index version 0 and the setting in its offset log.
- **Regression:** A checkpoint that recorded the setting off keeps the new
eviction after a restart that sets it on, and a state format 4 checkpoint
started with the setting off still fails with
STREAMING_JOIN_STATE_V4_CHECKPOINT_INCOMPATIBLE when restarted with
allowMultiple set to false.
- **Behavior:** With the setting on, the crossed-key full outer join
followed by an append-mode aggregation over a window on la passes the analysis
check that rejects a stateful operator after an outer join whose eviction
moved, also when it restarts from a checkpoint that recorded the setting while
the session leaves it off.
- **Inspection:** Both 4.3-to-4.4 migration entries name the setting as the
way to keep the earlier join behavior in the default mode and say that a query
keeps the value its checkpoint recorded.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -722,6 +751,21 @@ case class StreamingSymmetricHashJoinExec(
private[this] val allowMultipleStatefulOperators: Boolean =
conf.getConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE)
+ // The join condition bounds the column that the value predicate tests, so
a row with a NULL
+ // in it can never match, and the predicate never evicts it. The legacy
mode tests the event
+ // time even when the condition bounds another column. The same holds for
an equality key
+ // that the opposite watermark selects; the key that
findJoinKeyOrdinalForWatermark selects
+ // keeps the previous behavior.
+ private[this] val isEvictionColumnNull: UnsafeRow => Boolean =
stateWatermarkPredicate match {
Review Comment:
Thanks, the fix holds: on state formats 2 and 3, stored rows whose newly
selected key or column is NULL are now evicted, and an outer join emits them.
This review raises a related issue: the same NULL check, both on arrival and in
this eviction, also applies to inputs bounded only through a cast column, whose
event time is not in the join condition, so rows that can still match are
dropped.
<!-- SPARK_DEV_REVIEW_REPLY
{"feedback_id":"inline:4616349079","thread_id":"inline:4616349079","verdict_sha256":"252e5ca7fc5d7d892f71bba103a2c92117de684a5d834c167792ae336cd89cf7"}
-->
--
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]