HeartSaVioR commented on code in PR #60668:
URL: https://github.com/apache/spark/pull/60668#discussion_r4625588840
##########
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:
> [!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 in #60667, which owns the NULL rule, and merged here: the rule
now applies only to a column that the default mode picked, so an input bounded
only through a cast column keeps master's handling.
##########
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:
> [!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.
We'll keep the legacy mode as the only way back. This changes eviction to
fix wrong results, and a separate setting that restores the earlier eviction
would restore those results too.
##########
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:
> [!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.
Added in #60667 and merged here: a TODO naming
[SPARK-62044](https://issues.apache.org/jira/browse/SPARK-62044) above the
fallback.
##########
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:
> [!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.
Added in #60667 and merged here: a cast-bounded join test that fails if the
fallback is removed.
##########
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:
> [!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.
Good catch. The test now also checks that only the two key-6 rows are
stored, so it fails if the arrival skip goes away, and the comment says the row
would be evicted at the next eviction.
--
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]