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


##########
docs/streaming/ss-migration-guide.md:
##########
@@ -25,6 +25,44 @@ Please refer [Migration Guide: SQL, Datasets and 
DataFrame](../sql-migration-gui
 
 ## Upgrading from Structured Streaming 4.3 to 4.4
 
+- Spark 4.4 holds back the output watermark of a stream-stream join when 
retained state can
+  still emit old event times. Downstream stateful operators may retain more 
state, take longer
+  to finalize results, or stop making progress while the join has no 
event-time eviction bound.
+  The join holds back only for an input whose event time reaches the next 
stateful operator: in
+  a join on `clickTime <= impressionTime + INTERVAL 1 HOUR`, a window 
aggregation over
+  `impressionTime` makes progress, and one over `clickTime` does not. Spark 
follows the event
+  time through projections, filters, unions, and time and session windows, to 
aggregations,
+  deduplication, stream-stream joins, and `flatMapGroupsWithState` or 
`transformWithState` with
+  event-time timeouts. When Spark cannot tell which input's event time the 
operator uses, for
+  example when the operator's event time is computed from the join output by a 
function, it
+  holds back for both inputs.
+
+- When restarting a stream-stream join from an older Spark version, Spark may 
reject the
+  existing checkpoint with `STREAMING_JOIN_CHECKPOINT_INCOMPATIBLE`. Spark 
reuses the checkpoint
+  of a join without watermarks, of a join with an equality condition between 
the two inputs'
+  event times, such as `leftTime = rightTime`, and of a join whose time 
condition compares the
+  two inputs' event times with each other, each optionally cast and offset by 
constant intervals or

Review Comment:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM: Claude Sonnet 5.5 
(`claude-sonnet-5-5`, 1M context), running as an SP2K agent on behalf of 
@HeartSaVioR.
   
   Fixed in 
[90dfad8d848](https://github.com/apache/spark/pull/60279/commits/90dfad8d84808a6c4e00b41b0c6ffa24c713db31).
 The note now says that the cast and offset allowance applies to ordering 
comparisons (`<`, `<=`, `>`, `>=` and `BETWEEN`) between the two event times, 
and that an equality in which one event time is shifted or cast, such as 
`leftTime = rightTime + INTERVAL 1 SECOND`, is rejected, as the compatibility 
suite expects.
   
   <!-- sp2k-review11 reply 4597569680 -->
   



##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinRangeEvictionSuite.scala:
##########
@@ -0,0 +1,190 @@
+/*
+ * 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.logging.log4j.Level
+
+import org.apache.spark.sql.Row
+import org.apache.spark.sql.catalyst.analysis.StreamingJoinHelper
+import 
org.apache.spark.sql.execution.streaming.operators.stateful.join.StreamingSymmetricHashJoinExec
+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 StreamingJoinRangeEvictionSuite 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)
+  }
+
+  // V3 shares V2's eviction code. BETWEEN is replaced by the conjunction 
before planning, so it
+  // only adds coverage for the outer-join watermark check during analysis.
+  for {
+    version <- Seq(2, 4)
+    joinType <- Seq("inner", "left_outer", "right_outer")
+    shape <- Seq("between", "conjunction", "upper", "interval", "downstream")
+    if shape != "between" || joinType != "inner"
+  } {
+    test(s"range eviction uses bounded timestamp, V$version $joinType $shape") 
{
+      withJoinConf(version) {
+        val leftInput = MemoryStream[(Int, Long, Long)]
+        val rightInput = MemoryStream[(Int, Long)]
+        val left = leftInput.toDF().toDF("leftKey", "start", "end")
+          .select($"leftKey", timestamp_seconds($"start").as("leftTime"),
+            timestamp_seconds($"end").as("expiry"))
+          .withWatermark("leftTime", "60 seconds")
+        val right = rightInput.toDF().toDF("rightKey", "time")
+          .select($"rightKey", timestamp_seconds($"time").as("rightTime"))
+          .withWatermark("rightTime", "60 seconds")
+        val range = shape match {
+          case "between" | "downstream" => "rightTime BETWEEN leftTime AND 
expiry"
+          case "conjunction" => "rightTime >= leftTime AND rightTime <= expiry"
+          case "interval" => "rightTime BETWEEN leftTime AND leftTime + 
INTERVAL 10 MINUTES"
+          case _ => "rightTime <= expiry"
+        }
+        val condition = expr(s"leftKey = rightKey AND $range")
+        val joined = if (joinType == "right_outer") {
+          right.join(left, condition, joinType)
+        } else {
+          left.join(right, condition, joinType)
+        }
+        val output = joined.select($"leftKey", $"leftTime",
+          $"rightTime".cast("long").as("matchTime"))
+        val deduplicated = if (shape == "downstream") {
+          output.dropDuplicates("leftKey", "matchTime")
+        } else {
+          output
+        }
+        val result = deduplicated.select($"leftKey", $"matchTime", 
$"leftTime".cast("long"))
+        val matched = Row(1, 460L, 100L)
+        val unmatched = Row(2, null, 100L)
+        testStream(result)(
+          StreamProgressLockedActions(Seq(
+            AddData(leftInput, (1, 100L, 700L), (2, 100L, 700L)), 
AddData(rightInput, (9, 100L)))),
+          CheckNewAnswer(),
+          StreamProgressLockedActions(Seq(
+            AddData(leftInput, (8, 400L, 1000L)), AddData(rightInput, (9, 
400L)))),
+          CheckNewAnswer(),
+          AddData(rightInput, (9, 400L)),
+          // The watermark has passed the start time, but the interval has not 
expired.
+          CheckNewAnswer(),
+          Execute { query =>
+            val join = query.lastExecution.executedPlan.collectFirst {
+              case j: StreamingSymmetricHashJoinExec => j
+            }.get
+            assert(join.eventTimeWatermarkForEviction.contains(340000L))
+            if (shape != "interval") {
+              assert(join.produceOutputWatermark(340000L).contains(0L))
+            }
+          },
+          AddData(rightInput, (1, 460L)),
+          CheckNewAnswer(matched),
+          StreamProgressLockedActions(Seq(
+            AddData(leftInput, (8, 1000L, 1600L)), AddData(rightInput, (9, 
1000L)))),
+          CheckNewAnswer(),
+          AddData(rightInput, (9, 1100L)),
+          CheckNewAnswer((if (joinType != "inner") Seq(unmatched) else 
Seq.empty): _*)
+        )
+      }
+    }
+  }
+
+  for {
+    version <- Seq(2, 3, 4)
+    joinType <- Seq("left_outer", "right_outer")
+  } {
+    test(s"range eviction includes newly admitted expired values, V$version 
$joinType") {
+      withJoinConf(version) {
+        val leftInput = MemoryStream[(Int, Long, Long)]
+        val rightInput = MemoryStream[(Int, Long)]
+        val left = leftInput.toDF().toDF("leftKey", "start", "end")
+          .select($"leftKey", timestamp_seconds($"start").as("leftTime"),
+            timestamp_seconds($"end").as("expiry"))
+          .withWatermark("leftTime", "60 seconds")
+        val right = rightInput.toDF().toDF("rightKey", "time")
+          .select($"rightKey", timestamp_seconds($"time").as("rightTime"))
+          .withWatermark("rightTime", "60 seconds")
+        val condition = expr("leftKey = rightKey AND rightTime <= expiry")
+        val joined = if (joinType == "right_outer") {
+          right.join(left, condition, joinType)
+        } else {
+          left.join(right, condition, joinType)
+        }
+        val result = joined.select($"leftKey", $"rightKey", 
$"leftTime".cast("long"))
+        testStream(result)(
+          StreamProgressLockedActions(Seq(
+            AddData(leftInput, (8, 100L, 700L)), AddData(rightInput, (9, 
100L)))),
+          CheckNewAnswer(),
+          StreamProgressLockedActions(Seq(
+            AddData(leftInput, (8, 400L, 1000L)), AddData(rightInput, (9, 
400L)))),
+          CheckNewAnswer(),
+          AddData(rightInput, (9, 400L)), CheckNewAnswer(),
+          // The start passes late filtering, but expiry is below the previous 
eviction cutoff.
+          AddData(leftInput, (3, 460L, 200L)), CheckNewAnswer(Row(3, null, 
460L)),
+          AddData(rightInput, (9, 500L)), CheckNewAnswer())
+      }
+    }
+  }
+
+  // In state format 4, the extra conjunct gives the left side a 
value-eviction predicate on its

Review Comment:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM: Claude Sonnet 5.5 
(`claude-sonnet-5-5`, 1M context), running as an SP2K agent on behalf of 
@HeartSaVioR.
   
   Fixed in 
[90dfad8d848](https://github.com/apache/spark/pull/60279/commits/90dfad8d84808a6c4e00b41b0c6ffa24c713db31).
 The comment now says that the extra conjunct gives the right side a 
value-eviction predicate on `rightTime`, so that the range scan of the right 
joiner solves the bound that shifts by a column of the other input.
   
   <!-- sp2k-review11 reply 4597569692 -->
   



##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinSuite.scala:
##########
@@ -2425,6 +2529,267 @@ abstract class StreamingLeftSemiJoinBase extends 
StreamingJoinSuite {
     }
   }
 
+  // A left semi join processes the right input before the left input. A right 
row at or below
+  // its eviction cutoff passes late filtering when it is above the 
late-events watermark, and
+  // the left rows of the same batch must still find it. Each case runs a 
batch whose
+  // late-events watermark is 100 seconds and whose eviction watermark is 
`watermark` seconds.
+  // (name, condition, left time, right time, watermark, state rows after the 
second batch and
+  // after the third)
+  for ((name, condition, leftTime, rightTime, watermark, rowsBefore, 
rowsAfter) <- Seq(
+      ("equal event times", "leftTime = rightTime", 102, 102, 105, 2L, 0L),
+      // The left key leftTime + 10 seconds of (7, 100) stays above the 
100-second cutoff.
+      ("a key shifted by less than the watermark step",
+        "leftTime + INTERVAL 10 SECONDS = rightTime", 120, 130, 150, 3L, 1L),
+      // A value cutoff of the watermark less 10 seconds and 1 ms: (1, 130) is 
below 139.999 s.
+      ("a time interval",
+        "leftTime BETWEEN rightTime - INTERVAL 10 SECONDS AND rightTime + 
INTERVAL 10 SECONDS",
+        125, 130, 150, 4L, 2L))) {
+    test(s"left semi join keeps a same-batch match between the watermarks: 
$name") {
+      withSQLConf(SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> 
"false") {
+        val leftInput = MemoryStream[(Int, Int)]
+        val rightInput = MemoryStream[(Int, Int)]
+        val left = leftInput.toDF()
+          .select($"_1".as("leftKey"), timestamp_seconds($"_2").as("leftTime"))
+          .withWatermark("leftTime", "0 seconds")
+        val right = rightInput.toDF()
+          .select($"_1".as("rightKey"), 
timestamp_seconds($"_2").as("rightTime"))
+          .withWatermark("rightTime", "0 seconds")
+        val joined = left.join(right, expr(s"leftKey = rightKey AND 
$condition"), "left_semi")
+          .select($"leftKey", $"leftTime".cast("int"))
+
+        testStream(joined)(
+          MultiAddData(leftInput, (7, 100))(rightInput, (8, 100)),
+          CheckNewAnswer(),
+          MultiAddData(leftInput, (7, watermark))(rightInput, (8, watermark)),
+          CheckNewAnswer(),
+          assertNumStateRows(total = rowsBefore, updated = 4),
+          MultiAddData(leftInput, (1, leftTime))(rightInput, (1, rightTime)),
+          CheckNewAnswer((1, leftTime)),
+          // The right row is stored for the left row to probe and removed at 
the end of the
+          // batch, together with the other rows at or below the cutoffs.
+          assertNumStateRows(total = rowsAfter, updated = 1))
+      }
+    }
+  }
+
+  // The right cutoff comes from a bound on rightExpiry. The right row (1, 
110, 160) matches the
+  // left row (1, 120) of the same batch and is evicted at its end, whether 
the cutoff is applied
+  // to rightExpiry or to rightTime. Storing only the right rows above the 
cutoff at the
+  // late-events watermark would drop this match when the cutoff is applied to 
rightTime.
+  test("left semi join keeps a same-batch match bounded by another right 
column") {
+    withSQLConf(SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> 
"false") {
+      val leftInput = MemoryStream[(Int, Int, Int)]
+      val rightInput = MemoryStream[(Int, Int, Int)]
+      val left = leftInput.toDF()
+        .select($"_1".as("leftKey"), timestamp_seconds($"_2").as("leftTime"))
+        .withWatermark("leftTime", "0 seconds")
+      val right = rightInput.toDF()
+        .select($"_1".as("rightKey"), timestamp_seconds($"_2").as("rightTime"),
+          timestamp_seconds($"_3").as("rightExpiry"))
+        .withWatermark("rightTime", "0 seconds")
+      val joined = left.join(right, expr("leftKey = rightKey AND " +
+        "rightExpiry >= leftTime + INTERVAL 30 SECONDS AND " +
+        "leftTime >= rightTime - INTERVAL 1 HOUR"), "left_semi")
+        .select($"leftKey", $"leftTime".cast("int"))
+
+      testStream(joined)(
+        MultiAddData(leftInput, (7, 100, 0))(rightInput, (8, 100, 100)),
+        CheckNewAnswer(),
+        MultiAddData(leftInput, (7, 150, 0))(rightInput, (8, 150, 150)),
+        CheckNewAnswer(),
+        assertNumStateRows(total = 3, updated = 4),
+        // The late-events watermark is 100 seconds, and the right cutoff at 
it is 130 seconds
+        // less 1 ms: above the right row's rightTime of 110 seconds, below 
its rightExpiry.
+        MultiAddData(leftInput, (1, 120, 0))(rightInput, (1, 110, 160)),
+        CheckNewAnswer((1, 120)),
+        assertNumStateRows(total = 2, updated = 1))
+    }
+  }
+
+  test("left semi join keeps a same-batch match bounded by another right 
column when both " +
+      "watermarks are equal") {
+    withSQLConf(SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> "false",
+        SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key -> "false") {
+      val leftInput = MemoryStream[(Int, Int, Int)]
+      val rightInput = MemoryStream[(Int, Int, Int)]
+      val left = leftInput.toDF()
+        .select($"_1".as("leftKey"), timestamp_seconds($"_2").as("leftTime"))
+        .withWatermark("leftTime", "0 seconds")
+      val right = rightInput.toDF()
+        .select($"_1".as("rightKey"), timestamp_seconds($"_2").as("rightTime"),
+          timestamp_seconds($"_3").as("rightExpiry"))
+        .withWatermark("rightTime", "0 seconds")
+      val joined = left.join(right, expr("leftKey = rightKey AND " +
+        "rightExpiry >= leftTime + INTERVAL 30 SECONDS AND " +
+        "leftTime >= rightTime - INTERVAL 1 HOUR"), "left_semi")
+        .select($"leftKey", $"leftTime".cast("int"))
+
+      testStream(joined)(
+        MultiAddData(leftInput, (7, 100, 0))(rightInput, (8, 100, 100)),
+        CheckNewAnswer(),
+        // Both watermarks are 100 seconds, and the right cutoff is 130 
seconds less 1 ms. The
+        // right row passes late filtering but is at or below the cutoff on 
rightTime, and the
+        // left row of the same batch must still find it. The output stays the 
same when
+        // SPARK-61344 applies the cutoff to rightExpiry and the row is no 
longer evicted.
+        MultiAddData(leftInput, (1, 120, 0))(rightInput, (1, 110, 1000)),

Review Comment:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM: Claude Sonnet 5.5 
(`claude-sonnet-5-5`, 1M context), running as an SP2K agent on behalf of 
@HeartSaVioR.
   
   Fixed in 
[90dfad8d848](https://github.com/apache/spark/pull/60279/commits/90dfad8d84808a6c4e00b41b0c6ffa24c713db31).
 You are right that the legacy-mode test with a second right column cannot 
reach the same-batch decision: with equal watermarks, a right row that its 
batch evicts cannot match a left row that passes late filtering unless the 
cutoff is not exact. The test is renamed and its comment says that the right 
cutoff applies to `rightExpiry`, so the right row stays in state and matches 
the later left row, and that the default-mode test and the tests of the exact 
cutoffs cover the same-batch decision. A new test with the truncating-cast 
condition of the default-mode test, in legacy mode and skipped in state format 
4, makes the join store the right row that its batch evicts when the cutoff is 
not exact: with the left semi clause removed from the store decision, the left 
row at 100.6 seconds does not match.
   
   <!-- sp2k-review11 reply 4597569720 -->
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -51,6 +51,37 @@ object StreamingJoinHelper extends PredicateHelper with 
Logging {
     }
   }
 
+  /**
+   * Whether the expression is the event time, optionally cast to TIMESTAMP or 
a numeric type,
+   * plus or minus constants: intervals without months, or numbers. The solver 
reads such a cast
+   * as the column itself and counts such an interval as a fixed duration, a 
day as 24 hours, in
+   * every version and every time zone, so a range condition built from it 
derives the same
+   * cutoff before and after the stream-stream join corrections. Months have 
no fixed length.
+   */
+  private[sql] def isConstantOffsetOf(expr: Expression, eventTime: Attribute): 
Boolean = {
+    def isConstant(e: Expression): Boolean = {
+      // A constant that fails to evaluate gives no bound; the query reports 
the error at run time.
+      def value: Option[Any] = try Option(e.eval()) catch { case NonFatal(_) 
=> None }
+      e.foldable && (e.dataType match {
+        case _: DayTimeIntervalType | _: NumericType => value.isDefined
+        case CalendarIntervalType => 
value.exists(_.asInstanceOf[CalendarInterval].months == 0)

Review Comment:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM: Claude Sonnet 5.5 
(`claude-sonnet-5-5`, 1M context), running as an SP2K agent on behalf of 
@HeartSaVioR.
   
   Added in 
[90dfad8d848](https://github.com/apache/spark/pull/60279/commits/90dfad8d84808a6c4e00b41b0c6ffa24c713db31).
 The compatibility table has a row for an interval join with `leftTime + 
CAST('5 seconds' AS INTERVAL)`, a calendar interval without months, in state 
formats 2 and 4: the older-marker checkpoint resumes and emits the expected 
match. If the calendar-interval arm of the constant-offset rule rejected 
month-free intervals, the row would fail with 
`STREAMING_JOIN_CHECKPOINT_INCOMPATIBLE`.
   
   <!-- sp2k-review11 reply 4597569726 -->
   



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