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


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

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 SPARK-61345 (#60280, 
[c4bdbf09fdb](https://github.com/apache/spark/pull/60280/commits/c4bdbf09fdbea72fee5ab22ad03b839f1d9d7a37)).
 The shifted-key test now adds a left row between the late watermark and the 
previous shifted cutoff. In V4 that row is not emitted if the cutoff is used 
uncapped.
   
   <!-- sp2k-review1 reply 4523762436 -->
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -35,18 +34,130 @@ import org.apache.spark.unsafe.types.CalendarInterval
 object StreamingJoinHelper extends PredicateHelper with Logging {
 
   /**
-   * Check the provided logical plan to see if its join keys contain a 
watermark attribute.
-   *
-   * Will return false if the plan is not an equijoin.
-   * @param plan the logical plan to check
+   * Find the equality key filtered by this input's watermark. Its ordinal can 
be used to
+   * evict the opposite input's state, whose equality keys have the same 
ordering.
+   * For leftTime = rightTime, a watermark on rightTime bounds leftTime even 
when leftTime
+   * has no watermark. It does not bound right-side state without a watermark 
on leftTime.
+   * A key computed from the event time by adding a constant interval, such as
+   * leftTime = rightTime + INTERVAL 10 SECONDS, is bounded too; see 
[[getStateKeyWatermark]].
    */
-  def isWatermarkInJoinKeys(plan: LogicalPlan): Boolean = {
-    plan match {
-      case ExtractEquiJoinKeys(_, leftKeys, rightKeys, _, _, _, _, _) =>
-        (leftKeys ++ rightKeys).exists {
-          case a: AttributeReference => 
a.metadata.contains(EventTimeWatermark.delayKey)
-          case _ => false
-        }
+  def getStateKeyWatermarkOrdinal(
+      keys: Seq[Expression],
+      inputAttributes: Seq[Attribute]): Option[Int] = {
+    getEventTimeKeyOrdinal(keys, inputAttributes).orElse {
+      keys.indices.find(getStateKeyWatermark(keys, inputAttributes, _, 
Some(0L)).isDefined)
+    }
+  }
+
+  /** Find the equality key that is this input's event-time column itself. */
+  def getEventTimeKeyOrdinal(
+      keys: Seq[Expression],
+      inputAttributes: Seq[Attribute]): Option[Int] = {
+    // When multiple stateful operators are disabled, late filtering uses the 
first event-time
+    // column. Otherwise, execution rejects multiple distinct event-time 
columns.
+    inputAttributes.find(_.metadata.contains(delayKey)).flatMap { eventTime =>
+      keys.indexWhere(_.semanticEquals(eventTime)) match {
+        case ordinal if ordinal >= 0 => Some(ordinal)
+        case _ => None
+      }
+    }
+  }
+
+  /**
+   * Get the cutoff for the opposite input's equality key at `ordinal`, given 
this input's
+   * watermark. `keys` and `inputAttributes` belong to this input, whose 
future rows have an event
+   * time above the watermark. When the key is that event time, the equal key 
of any state row
+   * they can still match is above the watermark too. When the key is the 
event time shifted by
+   * an interval, solving `stateKey >= rightTime + INTERVAL 10 SECONDS` shifts 
the cutoff by that
+   * interval, less 1 ms as for range conditions. Returns None for any other 
key.
+   */
+  def getStateKeyWatermark(
+      keys: Seq[Expression],
+      inputAttributes: Seq[Attribute],
+      ordinal: Int,
+      eventWatermark: Option[Long]): Option[Long] = {
+    if (getEventTimeKeyOrdinal(keys, inputAttributes).contains(ordinal)) {
+      eventWatermark
+    } else {
+      eventTimeOfKey(keys(ordinal), inputAttributes).flatMap { eventTime =>
+        val stateKey = AttributeReference("stateKey", TimestampType)()
+        getStateValueWatermark(AttributeSet(Seq(stateKey)), 
AttributeSet(Seq(eventTime)),
+          Some(GreaterThanOrEqual(stateKey, keys(ordinal))), eventWatermark)
+      }
+    }
+  }
+
+  /**
+   * Get a bound on this input's event time for state rows whose equality key 
at `ordinal` is
+   * above `keyWatermark`. When the key is the event time, the bound is the 
key watermark. When
+   * the key is the event time shifted by an interval, solving
+   * `leftTime + INTERVAL 10 SECONDS >= keyWatermark` subtracts that constant, 
less 1 ms.
+   * Returns None for any other key.
+   */
+  def getEventTimeWatermarkFromKey(
+      keys: Seq[Expression],
+      inputAttributes: Seq[Attribute],
+      ordinal: Int,
+      keyWatermark: Long): Option[Long] = {
+    if (getEventTimeKeyOrdinal(keys, inputAttributes).contains(ordinal)) {
+      Some(keyWatermark)
+    } else {
+      eventTimeOfKey(keys(ordinal), inputAttributes).flatMap { eventTime =>
+        val keyWithWatermark = AttributeReference("stateKey", TimestampType,
+          metadata = new MetadataBuilder().putLong(delayKey, 0L).build())()
+        getStateValueWatermark(AttributeSet(Seq(eventTime)), 
AttributeSet(Seq(keyWithWatermark)),
+          Some(GreaterThanOrEqual(keys(ordinal), keyWithWatermark)), 
Some(keyWatermark))
+      }
+    }
+  }
+
+  /** The input's event-time column, if a timestamp key is that column shifted 
by intervals. */
+  private def eventTimeOfKey(key: Expression, inputAttributes: 
Seq[Attribute]): Option[Attribute] =
+    inputAttributes.find(_.metadata.contains(delayKey)).filter { eventTime =>
+      key.dataType == TimestampType && isIntervalShift(key, eventTime)
+    }
+
+  /**
+   * Whether the expression is the event time plus or minus constant 
intervals. Other functions
+   * and casts from other types are not accepted: a truncation such as
+   * CAST(CAST(rightTime AS BIGINT) AS TIMESTAMP) can map a later event time 
below the watermark.
+   */
+  private def isIntervalShift(expr: Expression, eventTime: Attribute): Boolean 
= {
+    // Spark adds the whole days of an interval in the session time zone, 
where a day can be 23
+    // or 25 hours across a daylight saving change, but the solver counts a 
day as 24 hours.
+    // Accept whole days only in a fixed-offset time zone.
+    def isExactInterval(e: Expression, timeZoneId: Option[String]): Boolean = {
+      def fixedOffset: Boolean =
+        timeZoneId.exists(id => 
DateTimeUtils.getZoneId(id).getRules.isFixedOffset)

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 with a test, fixed in SPARK-61345 (#60280, 
[c4bdbf09fdb](https://github.com/apache/spark/pull/60280/commits/c4bdbf09fdbea72fee5ab22ad03b839f1d9d7a37)).
   
   - **The failure.** A V4 inner join on `k = rt + INTERVAL 1 DAY`, started in 
America/Los_Angeles and restarted in UTC, lost every match for rows buffered 
before the restart.
   - **The fix.** Whole days now count as inexact in every time zone, so 
whether a key gets an ordinal depends only on its shape. Forward whole-day 
shifts get an ordinal in every zone, and backward ones get none in any zone, so 
the V4 layout no longer changes with the session time zone.
   - **Tests.** They restart in both directions, with a forward and a backward 
one-day shift.
   
   <!-- sp2k-review1 reply 4523762444 -->
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -224,98 +228,150 @@ 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] = {
-      val isWatermarkDefinedOnInput = 
oneSideInputAttributes.exists(_.metadata.contains(delayKey))
+        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 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)
-        }
-      } 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)
+          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 SPARK-61345 (#60280, 
[c4bdbf09fdb](https://github.com/apache/spark/pull/60280/commits/c4bdbf09fdbea72fee5ab22ad03b839f1d9d7a37)).
 The scan now starts after the lower of the late watermark and the shifted 
cutoff at it. For a positive shift it starts from the late watermark again.
   
   <!-- sp2k-review1 reply 4523762451 -->
   



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