spark-test commented on code in PR #60279:
URL: https://github.com/apache/spark/pull/60279#discussion_r4597569654


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala:
##########
@@ -630,6 +661,134 @@ class IncrementalExecution(
       watermarkPropagator.propagate(currentBatchId, plan, 
watermarkForCurrBatch)
     }
 
+    /**
+     * Find, for each stateful operator that applies its input watermark to an 
event-time column,
+     * which stream-stream join inputs' event times that column carries. The 
walk follows the
+     * column down through nodes that pass it on unchanged, to the same 
position in every input
+     * of a union, through windows built from it, which end after it, and into 
the one input of
+     * a node with several inputs, such as a stream-static join, that outputs 
it. It stops at a
+     * stream-stream join, at another operator that writes state or sets an 
event time, and at
+     * any node it does not recognize; a join that no traced column reaches 
holds back for both
+     * inputs.
+     */
+    private def joinWatermarkConsumers(plan: SparkPlan): 
Seq[JoinWatermarkConsumer] = {
+      def eventTime(output: Seq[Attribute]): Option[Attribute] =
+        output.find(_.metadata.contains(EventTimeWatermark.delayKey))
+
+      // A time or session window built from one column, plus constants, ends 
after that column.
+      def windowSource(window: Attribute, expression: Expression): 
Option[Attribute] = {
+        val isWindow = window.metadata.contains(TimeWindow.marker) ||
+          window.metadata.contains(SessionWindow.marker)
+        expression.references.toSeq match {
+          case Seq(source) if isWindow => Some(source)
+          case _ => None
+        }
+      }
+
+      def passThrough(child: SparkPlan, attribute: Attribute): Seq[(Long, 
JoinSide, Attribute)] =
+        child.output.find(_.exprId == 
attribute.exprId).toSeq.flatMap(findJoinSides(child, _))
+
+      def findJoinSides(
+          node: SparkPlan,
+          attribute: Attribute): Seq[(Long, JoinSide, Attribute)] = {
+        node match {
+          case j: StreamingSymmetricHashJoinExec =>
+            val side = if (eventTime(j.left.output).exists(_.exprId == 
attribute.exprId)) {
+              Some(LeftSide)
+            } else if (eventTime(j.right.output).exists(_.exprId == 
attribute.exprId)) {
+              Some(RightSide)
+            } else {
+              None
+            }
+            j.stateInfo.map(_.operatorId).zip(side).map { case (id, s) => (id, 
s, attribute) }
+              .toSeq
+          case p: ProjectExec =>
+            p.projectList.find(_.exprId == attribute.exprId).toSeq.flatMap {
+              case a: Attribute => passThrough(p.child, a)
+              case Alias(a: Attribute, _) => passThrough(p.child, a)
+              case alias: Alias =>

Review Comment:
   **Blocking (P1):** This case gives no join side for an alias whose child is 
neither an attribute nor a window, such as `impressionTime + INTERVAL 1 MINUTE 
AS t`. Such a column still reaches a watermark-using operator through a union: 
`UnionExec` keeps each attribute of its first child, so when the first child is 
another watermarked stream, `t` carries that stream's watermark metadata while 
the join's child supplies the computed value.
   
   Take the 'a union with the join second' case in 
`StreamingJoinOutputWatermarkSuite` and select `($"impressionTime" + 
expr("INTERVAL 1 MINUTE")).as("t")` instead of the plain event time. By this 
review's reading of the code, the trace stops here, the join keeps 
`outputWatermarkSides` at `None`, the unbounded click input contributes 0, and 
the deduplication's input watermark stays 0, so it never evicts. A later 
stream-stream outer join over such a union never emits its null rows, and the 
restart check rejects an older checkpoint of the query because both inputs 
count as consumed. On the base branch the click input contributed no state 
watermark, so the join forwarded the impression state watermark, which also 
bounds `impressionTime` plus one minute.
   
   A column that can fall below the bounded event time, such as that time minus 
an interval, is a different case: the base branch dropped its rows as late, so 
holding back there is part of the correction.
   
   This extends existing discussions 
[1](https://github.com/apache/spark/pull/60279#issuecomment-6941278598), 
[2](https://github.com/apache/spark/pull/60279#discussion_r4571551493).
   
   **Recommended change:** In findJoinSides, follow an alias whose expression 
references exactly one column and is built from it only in ways that keep the 
value at or above that column: adding constant intervals that are not negative, 
or greatest() over such expressions and constants. Trace that column and return 
the input it reaches, as windowSource already does for a window built from one 
column. Keep returning no input, so that the join holds back for both inputs, 
for every other expression, such as one that subtracts an interval, truncates, 
calls a UDF, or references a column that is not a join input's event time, 
columns of both inputs or no column, and say why in a comment at that fallback. 
Apply the same rule in the project and Expand cases. Update the migration 
note's example of an operator event time computed by a function, the tracer's 
doc comment and the PR description to say which computed columns Spark follows. 
Cover the change with output-watermark tests in which a uni
 on's join child computes the time column from the bounded input's event time, 
for a deduplication and for a later outer join, and with a restart case for an 
older checkpoint of that shape. The compatibility tests that exercise the 
fallback build their consumer column with greatest(leftTime, 
timestamp_seconds(lit(0))), which the tracer would now follow; switch them to a 
column it still does not follow, such as an identity UDF over leftTime.
   
   **Why this works:** The tracer then names the one input whose event time the 
operator's column stays at or above, so withJoinOutputWatermarkSides narrows 
the join to that input, as it already does for a plain or windowed event time, 
and the restart check counts only that input. That input's state watermark 
bounds the column, because the column never falls below the event time, so an 
input whose event time the column cannot carry no longer holds the output 
watermark at 0.
   
   **Scope:** Let the output-watermark tracer follow a column computed from one 
join input's event time when the computation keeps it at or above that time, 
and update the descriptions of what it follows.
   
   **Compatibility:** Every operator that the tracer follows today keeps its 
traced side, and operators whose column references both inputs, no input's 
event time, or an expression that can fall below its event time keep the 
hold-back for both inputs.
   
   **Risks:** Older checkpoints of joins followed by an operator over such a 
column, which the restart check now rejects, resume. Their rows keep their 
meaning, because the unbounded input contributed no bound in older versions 
either. An operator over a column computed by a UDF or another expression the 
tracer cannot analyze still gets output watermark 0 after this change, even 
when the column never falls below the bounded event time; projecting the plain 
event time, or a supported shift of it, avoids that.
   
   **Constraints:** Keep holding back for both inputs for an expression that 
can fall below its column or whose relation to it the tracer cannot establish, 
such as a subtraction, a truncation or a UDF, and for one that references 
columns of both inputs, a column that is not a join input's event time, or no 
column at all. Keep the existing handling of plain attributes, attribute 
aliases, window aliases and nodes with several inputs.
   
   **Exclusions:**
   - Columns that reach the next operator through typed Dataset operations, 
which drop watermark metadata, so that the operator has no event-time column to 
trace.
   - Columns computed by an expression whose relation to the event time the 
tracer cannot establish, such as a UDF, which keep holding back for both inputs 
even when their values stay above the event time, because forwarding the 
bounded watermark for them could drop rows as late.
   
   **Success:** A deduplication over a union whose first child is another 
watermarked stream and whose join child supplies the bounded input's event time 
plus a constant interval, or greatest() of that time and a constant, receives 
the bounded input's state watermark and evicts its state, as on the base 
branch. A later stream-stream left outer join over such a union emits its 
unmatched rows padded with nulls once the watermark passes them. An operator 
whose column is computed from the unbounded input's event time, from both 
inputs, or by an expression that can fall below the bounded input's event time, 
such as that time minus an interval or a UDF, still holds the join's output 
watermark at 0. An older checkpoint of a one-directional interval join followed 
by such a deduplication resumes, the compatibility tests of the fallback still 
build a column the tracer does not follow, and the migration note and the 
tracer's doc comment say which computed columns Spark follows.
   
   **Verification:**
   - **Regression:** Over a one-directional interval join with watermarks on 
both inputs, followed by a union whose first child is another watermarked 
stream and whose join child supplies the bounded event time plus a non-negative 
constant interval, and again with greatest() of that time and a constant, a 
deduplication evicts its state and the join's traced side is the bounded input, 
in state formats 2 and 4.
   - **Behavior:** A later stream-stream left outer join over such a union 
emits its unmatched rows padded with nulls.
   - **Compatibility:** An operator over a column computed from the unbounded 
input's event time, from both event times, or as the bounded event time minus 
an interval or through a UDF, still sees output watermark 0, and the traced 
shapes that already work (plain columns, aliases, sliding and session windows, 
stream-static joins) keep their traced sides.
   - **Compatibility:** An older-marker checkpoint of the bounded-consumer 
union shape resumes, while the same shape over the unbounded input's time is 
still rejected, and the compatibility tests of the fallback, rebuilt with a 
column the tracer does not follow, keep their accept and reject outcomes.



##########
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:
   **Nit (P3):** Read as written, "compares the two inputs' event times with 
each other, each optionally cast and offset by constant intervals or numbers" 
also covers an equality such as `leftTime = rightTime + INTERVAL 1 SECOND` or 
`CAST(leftTime AS BIGINT) = CAST(rightTime AS BIGINT)`. Such an equality 
becomes a join key, and the restart check rejects every key that references an 
event time unless the keys are the two event times themselves at the same 
position, as the suite's 'interval with a shifted event-time key' case expects. 
Saying that the cast and offset allowance applies to ordering comparisons (`<`, 
`<=`, `>`, `>=` and `BETWEEN`) between the two event times, and that an 
equality with a shifted or cast event time is rejected, would match the check.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60279#discussion_r4537966892).
   
   **Verification:**
   - **Inspection:** Every shape that the note says is reused is accepted by 
the restart check's rules, and the note describes as rejected the shifted 
event-time equality that the compatibility tests expect to be rejected.



##########
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:
   **Nit (P3):** This arm makes the restart check reuse older checkpoints of 
interval joins written with a month-free calendar interval, such as `rightTime 
BETWEEN leftTime AND leftTime + CAST('5 seconds' AS INTERVAL)` or a legacy 
interval literal. The only `CalendarInterval` in 
`StreamingJoinCheckpointCompatibilitySuite` is the one-month case, which must 
be rejected, and `StreamingJoinHelperSuite` does not call `isConstantOffsetOf`, 
so nothing fails if this arm stops accepting month-free intervals and those 
users start getting `STREAMING_JOIN_CHECKPOINT_INCOMPATIBLE`. An accepting row 
with such an interval in the compatibility table, an older-marker checkpoint 
that resumes and emits the expected match, would cover it.
   
   **Verification:**
   - **Regression:** With the calendar-interval arm of the constant-offset rule 
made to reject month-free intervals, the new case fails; with the arm as 
written, the checkpoint resumes and emits the expected match.



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

Review Comment:
   **Nit (P3):** Since round 7, `findJoinSides` also follows the event time 
through a stream-static join, or any node with several inputs of which exactly 
one outputs the column, which `StreamingJoinOutputWatermarkSuite` tests for 
broadcast hash, sort merge and broadcast nested loop joins. A user with a 
stream-static enrichment join between the stream-stream join and the 
aggregation would read this list as saying that Spark holds back for both 
inputs. `transformWithState` also has a time mode and timers rather than 
timeouts, and the tracer counts every `transformWithState` in event-time mode. 
Adding stream-static joins to the followed nodes, and naming the operators as 
`flatMapGroupsWithState` and `applyInPandasWithState` with event-time timeouts 
and `transformWithState` in event-time mode, would bring the list up to date.
   
   **Verification:**
   - **Inspection:** The note names stream-static joins among the nodes Spark 
follows the event time through, lists aggregations, deduplication, 
stream-stream joins, flatMapGroupsWithState and applyInPandasWithState with 
event-time timeouts, and transformWithState in event-time mode as the operators 
it counts, and describes transformWithState by its time mode.



##########
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:
   **Nit (P3):** `leftTime < rightTime + INTERVAL 1 HOUR` gives a cutoff only 
to `rightTime`: for `leftTime` the solver's constraint term is not negated, so 
it returns no bound, and neither bound conjunct gives the left side a predicate 
either. The right joiner reaches the shifted bound because its own side has the 
value predicate, since `isV4TimeIntervalJoin` tests the joiner's own 
`stateWatermarkPredicate`. A reader who trusts this comment could change the 
conjunct to bound `leftTime`, which would stop that range scan and take away 
this case's failure signal.
   
   ```suggestion
     // In state format 4, the extra conjunct gives the right side a 
value-eviction predicate on its
   ```
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60279#discussion_r4571551497).
   
   **Verification:**
   - **Inspection:** The comment names the right side as the one that the extra 
conjunct gives a predicate, matching what the solver derives from that 
conjunct, and no longer names the left side.



##########
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:
   **Nit (P3):** With `allowMultiple=false` both watermarks are 100 seconds, 
and in this PR the right cutoff, 130 seconds less 1 ms, applies to 
`rightExpiry`. This right row has `rightExpiry` 1000 seconds, so it is not 
evicted in its batch and is stored whatever `(joinType == LeftSemi && 
!noLeftRowCanMatch(key, thisRow))` decides; the test passes with that clause 
removed and duplicates the default-mode case above it. With equal watermarks 
and this exact bound, an evicted right row cannot match a left row that passes 
late filtering, so the case arises only for a bound with no exact cutoff. Using 
the truncating-cast condition of the default-mode test here, and skipping state 
format 4 as that test does, would make the clause store a right row that its 
batch evicts; the comment above should then describe that cutoff.
   
   **Verification:**
   - **Regression:** With the left semi clause removed from the store decision, 
the single-watermark test fails because the matching left row is not emitted; 
with the clause in place, it emits that row in state formats 2 and 3.



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