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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -403,19 +404,19 @@ case class StreamingSymmetricHashJoinExec(
     // Create left and right side hash joiners and store in the joiner manager.
     // Both sides should use the same store generator if we are re-using the 
same store instance.
     val joinStateManagerStoreGenerator = new JoinStateManagerStoreGenerator()
-    val joinKeyOrdinalForWatermark =
-      
StreamingSymmetricHashJoinHelper.findJoinKeyOrdinalForWatermark(leftKeys, 
rightKeys)
     val joinerManager = OneSideHashJoinerManager(
       new OneSideHashJoiner(
         LeftSide, left.output, leftKeys, leftInputIter,
         condition.leftSideOnly, postJoinFilter, stateWatermarkPredicates.left, 
partitionId,
         checkpointIds.left.keyToNumValues, 
checkpointIds.left.keyWithIndexToValue,
-        skippedNullValueCount, joinStateManagerStoreGenerator, 
joinKeyOrdinalForWatermark),
+        skippedNullValueCount, joinStateManagerStoreGenerator,
+        StreamingJoinHelper.getStateKeyWatermarkOrdinal(rightKeys, 
right.output)),

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.
   
   Confirmed. Results were unchanged, but each probe into that state became a 
prefix scan. In a one-sided join with 200k keys, probe batches were about 1.3 
to 1.5 times slower than on master. Fixed in 
[c4bdbf09fdb](https://github.com/apache/spark/pull/60280/commits/c4bdbf09fdbea72fee5ab22ad03b839f1d9d7a37):
 when no opposite key bounds a side, its V4 state manager still stores and 
looks up rows at its own event-time key, unless that side is evicted on another 
column. The stored timestamps are the same, so the state layout does not 
change, and probe time is back to master's.
   
   <!-- sp2k-review1 reply 4523185824 -->
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -224,98 +228,148 @@ object StreamingSymmetricHashJoinHelper extends Logging {
     WatermarkSupport.findEventTimeColumn(rightAttributes,
       allowMultipleEventTimeColumns = useFirstEventTimeColumn)
 
-    val joinKeyOrdinalForWatermark: Option[Int] = 
findJoinKeyOrdinalForWatermark(
-      leftKeys, rightKeys)
-
     def getOneSideStateWatermarkPredicate(
         oneSideInputAttributes: Seq[Attribute],
         oneSideJoinKeys: Seq[Expression],
-        otherSideInputAttributes: Seq[Attribute]): 
Option[JoinStateWatermarkPredicate] = {
+        otherSideInputAttributes: Seq[Attribute],
+        otherSideJoinKeys: Seq[Expression]): 
Option[JoinStateWatermarkPredicate] = {
+      // State is bounded by future input from the opposite side, not by its 
own watermark.
+      val joinKeyOrdinalForWatermark = 
StreamingJoinHelper.getStateKeyWatermarkOrdinal(
+        otherSideJoinKeys, otherSideInputAttributes)
       val isWatermarkDefinedOnInput = 
oneSideInputAttributes.exists(_.metadata.contains(delayKey))
       val isWatermarkDefinedOnJoinKey = joinKeyOrdinalForWatermark.isDefined
 
       if (isWatermarkDefinedOnJoinKey) { // case 1 and 3 in the 
StreamingSymmetricHashJoinExec docs
+        val ordinal = joinKeyOrdinalForWatermark.get
         val keyExprWithWatermark = BoundReference(
-          joinKeyOrdinalForWatermark.get,
-          oneSideJoinKeys(joinKeyOrdinalForWatermark.get).dataType,
-          oneSideJoinKeys(joinKeyOrdinalForWatermark.get).nullable)
-        val expr = watermarkExpression(Some(keyExprWithWatermark), 
eventTimeWatermarkForEviction)
-        expr.map { e =>
-          // V4 can skip keys at or below the previous watermark only if 
late-input filtering
-          // rejects new rows in that range on this same key. A watermark on 
the other input's
-          // equality key can drive eviction even when this input has no 
watermark, or has one
-          // on a different column. New rows can then pass late-input 
filtering with keys
-          // already eligible for eviction. V4 must scan from the beginning to 
find them;
-          // otherwise, outer joins can fail to emit null rows for these 
unmatched inputs.
-          val prevStateKeyWatermark =
-            if (oneSideInputAttributes.find(_.metadata.contains(delayKey))
-              
.exists(oneSideJoinKeys(joinKeyOrdinalForWatermark.get).semanticEquals)) {
-              eventTimeWatermarkForLateEvents
-            } else {
-              None
-            }
-          // watermarkExpression only provides the expression when 
eventTimeWatermarkForEviction
-          // is defined.
-          JoinStateKeyWatermarkPredicate(
-            e,
-            eventTimeWatermarkForEviction.get,
-            prevStateKeyWatermark)
+          ordinal, oneSideJoinKeys(ordinal).dataType, 
oneSideJoinKeys(ordinal).nullable)
+        // The opposite watermark bounds this key, shifted by any constant in 
the opposite key.
+        def keyWatermark(watermark: Option[Long]): Option[Long] =
+          StreamingJoinHelper.getStateKeyWatermark(
+            otherSideJoinKeys, otherSideInputAttributes, ordinal, watermark)
+        keyWatermark(eventTimeWatermarkForEviction).flatMap { stateWatermark =>
+          watermarkExpression(Some(keyExprWithWatermark), 
Some(stateWatermark)).map { e =>
+            // V4 can skip keys at or below the previous watermark only if 
late-input filtering
+            // rejects new rows in that range on this same key. A watermark on 
the other input's
+            // equality key can drive eviction even when this input has no 
watermark, or has one
+            // on a different column. New rows can then pass late-input 
filtering with keys
+            // already eligible for eviction. V4 must scan from the beginning 
to find them;
+            // otherwise, outer joins can fail to emit null rows for these 
unmatched inputs.
+            val prevStateKeyWatermark =
+              if (oneSideInputAttributes.find(_.metadata.contains(delayKey))
+                .exists(oneSideJoinKeys(ordinal).semanticEquals)) {
+                // A cutoff shifted above the late-input watermark also needs 
a full scan.
+                eventTimeWatermarkForLateEvents.flatMap { lateWatermark =>
+                  keyWatermark(Some(lateWatermark)).filter(_ <= lateWatermark)

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.
   
   Agreed, fixed in 
[c4bdbf09fdb](https://github.com/apache/spark/pull/60280/commits/c4bdbf09fdbea72fee5ab22ad03b839f1d9d7a37).
 Late filtering drops new keys at or below the late watermark, and the previous 
batch evicted keys up to the cutoff at that watermark. So the V4 scan now 
starts after the lower of the two, instead of at the start of the index. For a 
positive shift that is the late watermark, as on master; for a negative shift 
it is the shifted cutoff.
   
   <!-- sp2k-review1 reply 4523185831 -->
   



##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinEqualityWatermarkSuite.scala:
##########
@@ -0,0 +1,277 @@
+/*
+ * 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.Row
+import 
org.apache.spark.sql.execution.streaming.operators.stateful.join.StreamingSymmetricHashJoinExec
+import 
org.apache.spark.sql.execution.streaming.operators.stateful.join.StreamingSymmetricHashJoinHelper.{JoinStateKeyWatermarkPredicate,
 JoinStateValueWatermarkPredicate}
+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
+
+class StreamingJoinEqualityWatermarkSuite extends StreamTest {
+  import testImplicits._
+
+  for {
+    version <- Seq(2, 3, 4)
+    restart <- Seq(false, true)
+  } {
+    test(s"equality eviction follows the opposite watermark, V$version 
restart=$restart") {
+      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") {
+        val leftInput = MemoryStream[(Int, Int)]
+        val rightInput = MemoryStream[(Int, Int)]
+        val left = leftInput.toDF().toDF("a", "b")
+          .select(timestamp_seconds($"a").as("la"), 
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"))
+        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))
+          )): _*)
+        }
+      }
+    }
+  }
+
+  test("V4 window equality retains state for future unwatermarked input") {
+    withSQLConf(
+      SQLConf.STREAMING_JOIN_STATE_FORMAT_VERSION.key -> "4",
+      SQLConf.STATE_STORE_PROVIDER_CLASS.key -> 
classOf[RocksDBStateStoreProvider].getName) {
+      val leftInput = MemoryStream[Int]
+      val rightInput = MemoryStream[Int]
+      val left = leftInput.toDF()
+        .select($"value".as("key"), timestamp_seconds($"value").as("time"))
+        .withWatermark("time", "10 seconds")
+        .select($"key", window($"time", "10 seconds"))
+      val right = rightInput.toDF()
+        .select($"value".as("key"), timestamp_seconds($"value").as("time"))
+        .select($"key", window($"time", "10 seconds"))
+      val joined = left.join(right, Seq("key", "window"))
+        .select($"key", $"window.end".cast("long"))
+      testStream(joined)(
+        AddData(leftInput, 1), CheckNewAnswer(),
+        AddData(rightInput, 1), CheckNewAnswer(Row(1, 10L)),
+        AddData(leftInput, 25), CheckNewAnswer(),
+        StopStream, StartStream(),
+        // The right input has no late filter; its old window must still find 
left state.
+        AddData(rightInput, 1), CheckNewAnswer(Row(1, 10L)),
+        AddData(leftInput, 5), CheckNewAnswer())
+    }
+  }
+
+  for {
+    version <- Seq(2, 3, 4)
+    offset <- Seq(10, -10)
+  } {
+    test(s"equality on a shifted opposite event time evicts state, V$version 
offset=$offset") {
+      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") {
+        val leftInput = MemoryStream[(Int, Int)]
+        val rightInput = MemoryStream[(Int, Int)]
+        val left = leftInput.toDF().toDF("lk", "lt")
+          .select($"lk", timestamp_seconds($"lt").as("lt"))
+          .withWatermark("lt", "10 seconds")
+        val right = rightInput.toDF().toDF("rk", "rt")
+          .select($"rk", timestamp_seconds($"rt").as("rt"))
+          .withWatermark("rt", "10 seconds")
+        // A left row matches the right row whose time is `offset` seconds 
earlier.
+        val joined = left.join(right,
+          expr(s"lk = rk AND lt = rt + INTERVAL $offset SECONDS"), 
"left_outer")
+          .select($"lk", $"lt".cast("int"), $"rk", $"rt".cast("int"))
+        testStream(joined)(
+          MultiAddData(leftInput, (1, 100 + offset), (2, 90 + offset), (3, 145 
+ offset))(
+            rightInput, (9, 50)),
+          CheckNewAnswer(),
+          AddData(rightInput, (1, 100)),
+          CheckNewAnswer(Row(1, 100 + offset, 1, 100)),
+          MultiAddData(leftInput, (9, 300))(rightInput, (9, 150)),
+          // At watermark 90, a future right row can still have time 90.
+          CheckNewAnswer(),
+          AddData(rightInput, (9, 151)),
+          // At watermark 140, the left key cutoff is 140 + offset.
+          CheckNewAnswer(Row(2, 90 + offset, null, null)),

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.
   
   Agreed, fixed in 
[c4bdbf09fdb](https://github.com/apache/spark/pull/60280/commits/c4bdbf09fdbea72fee5ab22ad03b839f1d9d7a37).
 In the batch whose late watermark is 90 s and eviction watermark 140 s, the 
shifted-key test now adds left row (4, 95) and expects it null-padded, for both 
shift signs in V2, V3 and V4. If the previous cutoff is used uncapped, V4 never 
emits that row. The test also checks the previous-scan bound in that batch and 
its absence on the first batch, a new test checks its absence in legacy mode, 
and `StreamingSymmetricHashJoinHelperSuite` checks the bound for plus and minus 
10 seconds.
   
   <!-- sp2k-review1 reply 4523185837 -->
   



##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinV4Suite.scala:
##########
@@ -321,7 +321,7 @@ class StreamingInnerJoinV4Suite
       val df2 = input2.toDF().toDF("key", "time")
         .select($"key", timestamp_seconds($"time") as "ts", ($"key" * 3) as 
"rightValue")
       // Only left side has watermark; ts is part of the join key, so
-      // joinKeyOrdinalForWatermark is defined -> hasEventTime = true for both 
sides.
+      // joinKeyOrdinalForWatermark is defined -> hasTimestampForEviction = 
true for both sides.

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.
   
   Fixed in 
[c4bdbf09fdb](https://github.com/apache/spark/pull/60280/commits/c4bdbf09fdbea72fee5ab22ad03b839f1d9d7a37).
 The comments now say three things: only the right state is evicted, through 
`ts`, by the left watermark; the left state is never evicted; and both sides 
index their rows at `ts`.
   
   <!-- sp2k-review1 reply 4523185842 -->
   



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