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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -147,7 +155,9 @@ case class StreamingSymmetricHashJoinExec(
     stateFormatVersion: Int,
     left: SparkPlan,
     right: SparkPlan,
-    outputMode: Option[OutputMode])
+    outputMode: Option[OutputMode],
+    outputWatermarkSides: Option[Set[JoinSide]] = None,
+    eventTimeCopies: EventTimeCopies = EventTimeCopies.empty)

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.
   
   Removed: the join no longer takes the copy pairs. Only the V4 key ordinals 
used them, and V4
   rejects any input with two watermarked columns, so the argument never 
changed a result. Plan
   strings are back to what they were.
   
   <!-- sp2k-review8 reply 4577114417 -->
   



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationsSuite.scala:
##########
@@ -511,52 +517,338 @@ class UnsupportedOperationsSuite extends SparkFunSuite 
with SQLHelper {
       Seq("is not supported in Complete output mode", allowedModesMsg))
   }
 
-  // Left outer, right outer, full outer, left semi joins
-  Seq(LeftOuter, RightOuter, FullOuter, LeftSemi).foreach { joinType =>
-    // Stream-stream allowed with join on watermark attribute
-    // Note that the attribute need not be watermarked on both sides.
-    assertSupportedInStreamingPlan(
-      s"$joinType join with stream-stream relations and join on attribute with 
left watermark",
-      streamRelation.join(streamRelation, joinType = joinType,
-        condition = Some(attributeWithWatermark === attribute)),
-      OutputMode.Append())
-    assertSupportedInStreamingPlan(
-      s"$joinType join with stream-stream relations and join on attribute with 
right watermark",
-      streamRelation.join(streamRelation, joinType = joinType,
-        condition = Some(attribute === attributeWithWatermark)),
-      OutputMode.Append())
-    assertNotSupportedInStreamingPlan(
-      s"$joinType join with stream-stream relations and join on 
non-watermarked attribute",
-      streamRelation.join(streamRelation, joinType = joinType,
-        condition = Some(attribute === attribute)),
-      OutputMode.Append(),
-      Seq("without a watermark in the join keys"))
-
-    val timeWithWatermark =
-      AttributeReference("b", IntegerType)().withMetadata(watermarkMetadata)
-    val relationWithWatermark = new TestStreamingRelation(timeWithWatermark)
-    val (leftRelation, rightRelation) =
-      if (joinType == RightOuter) {
-        (relationWithWatermark, streamRelation)
-      } else {
-        (streamRelation, relationWithWatermark)
+  for {
+    joinType <- Seq(LeftOuter, RightOuter, FullOuter, LeftSemi)
+    leftWatermark <- Seq(false, true)
+    rightWatermark <- Seq(false, true)
+    conditionType <- Seq("equality", "range", "left bound", "right bound")
+  } {
+    val leftTime = AttributeReference("leftTime", TimestampType)()
+    val rightTime = AttributeReference("rightTime", TimestampType)()
+    val left = if (leftWatermark) leftTime.withMetadata(watermarkMetadata) 
else leftTime
+    val right = if (rightWatermark) rightTime.withMetadata(watermarkMetadata) 
else rightTime
+    val condition = conditionType match {
+      case "equality" => left === right
+      case "range" => left > right - 10 && left < right + 10
+      case "left bound" => left > right - 10
+      case "right bound" => left < right + 10
+    }
+    val leftCanEvict = rightWatermark && conditionType != "right bound"
+    val rightCanEvict = leftWatermark && conditionType != "left bound"
+    val correctedSupported = joinType match {
+      case LeftOuter | LeftSemi => leftCanEvict
+      case RightOuter => rightCanEvict
+      case FullOuter => leftCanEvict && rightCanEvict
+      case _ => false
+    }
+    val plan = new TestStreamingRelation(left).join(new 
TestStreamingRelation(right),
+      joinType = joinType, condition = Some(condition))
+    val name = s"$joinType $conditionType with watermarks " +
+      s"left=$leftWatermark right=$rightWatermark"
+    if (correctedSupported) {
+      assertSupportedInStreamingPlan(name, plan, OutputMode.Append())
+    } else {
+      assertNotSupportedInStreamingPlan(name, plan, OutputMode.Append(),
+        Seq("requires", "allow unmatched state to be finalized"))
+    }
+  }
+
+  {
+    val leftTime = AttributeReference("leftTime", TimestampType)()
+    val leftOther = AttributeReference("leftOther", TimestampType)()
+      .withMetadata(watermarkMetadata)
+    val rightTime = AttributeReference("rightTime", TimestampType)()
+      .withMetadata(watermarkMetadata)
+    val rightOther = AttributeReference("rightOther", TimestampType)()
+    val left = new TestStreamingRelation(Seq(leftTime, leftOther))
+    val right = new TestStreamingRelation(Seq(rightTime, rightOther))
+
+    // Each side's state is evicted by the key that the opposite watermark 
bounds.
+    assertSupportedInStreamingPlan("full outer with different watermark key 
ordinals",
+      left.join(right, joinType = FullOuter,
+        condition = Some(leftTime === rightTime && leftOther === rightOther)), 
OutputMode.Append())
+  }
+
+  {
+    val leftTime = AttributeReference("leftTime", TimestampType)()
+      .withMetadata(watermarkMetadata)
+    val rightTime = AttributeReference("rightTime", TimestampType)()
+      .withMetadata(watermarkMetadata)
+    val rightOther = AttributeReference("rightOther", TimestampType)()
+    val left = new TestStreamingRelation(leftTime)
+    val right = new TestStreamingRelation(Seq(rightTime, rightOther))
+
+    def shift(time: Expression, seconds: Int): Expression =
+      TimestampAddInterval(time, Literal(Duration.ofSeconds(seconds)))
+
+    // A key computed from the opposite event time by a constant is bounded by 
its watermark.
+    Seq(10, -10).foreach { offset =>
+      Seq(LeftOuter, RightOuter, FullOuter, LeftSemi).foreach { joinType =>
+        assertSupportedInStreamingPlan(s"$joinType with a key shifted by 
$offset",
+          left.join(right, joinType = joinType,
+            condition = Some(leftTime === shift(rightTime, offset))), 
OutputMode.Append())
       }
+      assertNotSupportedInStreamingPlan(
+        s"LeftOuter with a key shifted by $offset from an unwatermarked 
column",
+        left.join(right, joinType = LeftOuter,
+          condition = Some(leftTime === shift(rightOther, offset))), 
OutputMode.Append(),
+        Seq("requires a watermark on the right input"))
+    }
 
-    // stream-stream allowed with range condition yielding state value 
watermark
-    assertSupportedInStreamingPlan(
-      s"$joinType join with stream-stream relations and state value watermark",
-      leftRelation.join(rightRelation, joinType = joinType,
-        condition = Some(attribute > timeWithWatermark + 10)),
-      OutputMode.Append())
+    // The admission check sees the analyzed plan, where an interval 
expression such as
+    // INTERVAL 1 HOUR * 2 is not folded yet. It is bounded as its value is.
+    val twoHours = MultiplyDTInterval(Literal(Duration.ofHours(1)), Literal(2))
+    Seq(LeftOuter, FullOuter, LeftSemi).foreach { joinType =>
+      assertSupportedInStreamingPlan(s"$joinType with a key shifted by an 
interval expression",
+        left.join(right, joinType = joinType,
+          condition = Some(leftTime === TimestampAddInterval(rightTime, 
twoHours, Some("UTC")))),
+        OutputMode.Append())
+    }
+    Seq(
+      "minus two days" -> TimestampAddInterval(rightTime,
+        MultiplyDTInterval(Literal(Duration.ofDays(1)), Literal(-2)), 
Some("UTC")),
+      "minus two months" -> TimestampAddYMInterval(rightTime,
+        MultiplyYMInterval(Literal(Period.ofMonths(1)), Literal(-2)), 
Some("UTC")),
+      "an unwatermarked column" -> TimestampAddInterval(rightOther, twoHours, 
Some("UTC")),
+      "a truncated time" -> TimestampAddInterval(
+        rightTime.cast(LongType).cast(TimestampType), twoHours, 
Some("UTC"))).foreach {
+      case (name, key) =>
+        assertNotSupportedInStreamingPlan(
+          s"LeftOuter with a key shifted by an interval expression: $name",
+          left.join(right, joinType = LeftOuter, condition = Some(leftTime === 
key)),
+          OutputMode.Append(), Seq("requires a watermark on the right input"))
+    }
 
-    // stream-stream not allowed with insufficient range condition
-    assertNotSupportedInStreamingPlan(
-      s"$joinType join with stream-stream relations and state value watermark",
-      leftRelation.join(rightRelation, joinType = joinType,
-        condition = Some(attribute < timeWithWatermark + 10)),
-      OutputMode.Append(),
-      Seq("is not supported without a watermark in the join keys, or a 
watermark on " +
-        "the nullable side and an appropriate range condition"))
+    // timestampadd is a shift too: exact for a sub-day unit, and forward-only 
for days, weeks,
+    // months, quarters and years with a non-negative amount.
+    Seq(
+      ("one hour", TimestampAdd("HOUR", Literal(1), rightTime, Some("UTC")), 
true),
+      ("one day", TimestampAdd("DAY", Literal(1), rightTime, 
Some("America/Los_Angeles")), true),
+      ("minus one day", TimestampAdd("DAY", Literal(-1), rightTime, 
Some("UTC")), false),
+      ("one hour of an unwatermarked column",
+        TimestampAdd("HOUR", Literal(1), rightOther, Some("UTC")), 
false)).foreach {
+      case (name, key, supported) =>
+        Seq(LeftOuter, FullOuter, LeftSemi).foreach { joinType =>
+          val plan = left.join(right, joinType = joinType, condition = 
Some(leftTime === key))
+          val testName = s"$joinType with a key shifted by timestampadd of 
$name"
+          if (supported) {
+            assertSupportedInStreamingPlan(testName, plan, OutputMode.Append())
+          } else {
+            val requirement = if (joinType == FullOuter) {
+              "watermarks on both inputs"
+            } else {
+              "a watermark on the right input"
+            }
+            assertNotSupportedInStreamingPlan(testName, plan, 
OutputMode.Append(),
+              Seq(s"requires $requirement"))
+          }
+        }
+    }
+
+    // Whole days are added in the session time zone, where a day can be 23 or 
25 hours, and
+    // months vary in length. A shift that never moves a time backward still 
bounds the key, in
+    // every time zone; one that can move a time backward does not.
+    for {
+      zone <- Seq("UTC", "America/Los_Angeles")
+      (name, interval, supported) <- Seq(
+        ("one day", Literal(Duration.ofDays(1)), true),
+        ("minus one day", Literal(Duration.ofDays(-1)), false),
+        ("one month", Literal(Period.ofMonths(1)), true),
+        ("minus one month", Literal(Period.ofMonths(-1)), false))
+    } {
+      val shifted = interval.dataType match {
+        case _: YearMonthIntervalType => TimestampAddYMInterval(rightTime, 
interval, Some(zone))
+        case _ => TimestampAddInterval(rightTime, interval, Some(zone))
+      }
+      Seq(LeftOuter, LeftSemi, FullOuter).foreach { joinType =>
+        val plan = left.join(right, joinType = joinType, condition = 
Some(leftTime === shifted))
+        val testName = s"$joinType with a key shifted by $name in $zone"
+        if (supported) {
+          assertSupportedInStreamingPlan(testName, plan, OutputMode.Append())
+        } else {
+          val requirement = if (joinType == FullOuter) {
+            "watermarks on both inputs"
+          } else {
+            "a watermark on the right input"
+          }
+          assertNotSupportedInStreamingPlan(testName, plan, 
OutputMode.Append(),
+            Seq(s"requires $requirement"))
+        }
+      }
+    }
+
+    // Truncation can map a future right row below the watermark, so it does 
not bound the key.
+    assertNotSupportedInStreamingPlan("LeftOuter with a key truncated from the 
right event time",
+      left.join(right, joinType = LeftOuter,
+        condition = Some(leftTime === 
rightTime.cast(LongType).cast(TimestampType))),
+      OutputMode.Append(), Seq("requires a watermark on the right input"))
+  }
+
+  // With allowMultiple=false, late rows are filtered by an input's first 
watermarked column, so
+  // a time window key after it bounds the opposite state only when the input 
builds the window
+  // from that column, which a relation that outputs both does not show.
+  {
+    val windowType = new StructType().add("start", TimestampType).add("end", 
TimestampType)
+    val windowMetadata = new MetadataBuilder()
+      .withMetadata(watermarkMetadata)
+      .putBoolean(TimeWindow.marker, true)
+      .build()
+    def windowJoin(joinType: JoinType, windowFirst: Boolean): LogicalPlan = {
+      def input(side: String): (LogicalPlan, Attribute, Attribute) = {
+        val key = AttributeReference(s"${side}Key", IntegerType)()
+        val time = AttributeReference(s"${side}Time", TimestampType)()
+          .withMetadata(watermarkMetadata)
+        val window = AttributeReference(s"${side}Window", windowType)()
+          .withMetadata(windowMetadata)
+        val output = if (windowFirst) Seq(key, window, time) else Seq(key, 
time, window)
+        (TestStreamingRelation(output), key, window)
+      }
+      val (left, leftKey, leftWindow) = input("left")
+      val (right, rightKey, rightWindow) = input("right")
+      left.join(right, joinType = joinType,
+        condition = Some(leftKey === rightKey && leftWindow === rightWindow))
+    }
+    val legacyMode = SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key -> "false"
+    Seq(
+      LeftOuter -> Seq("right"),
+      LeftSemi -> Seq("right"),
+      RightOuter -> Seq("left"),
+      FullOuter -> Seq("left", "right")).foreach { case (joinType, sides) =>
+      test(s"$joinType on a window after its event time in legacy mode names 
the column order") {
+        val error = intercept[AnalysisException] {
+          withSQLConf(legacyMode) {
+            UnsupportedOperationChecker.checkForStreaming(
+              wrapInStreaming(windowJoin(joinType, windowFirst = false)), 
OutputMode.Append())
+          }
+        }
+        sides.foreach { side =>
+          assert(error.getMessage.contains(s"the $side input filters late rows 
by its first " +
+            s"watermarked column, ${side}Time, so its window key ${side}Window 
is a time " +
+            "constraint only if that input computes it as a tumbling or 
sliding window over " +
+            s"${side}Time itself, through projections, filters and unions 
only. Otherwise, put " +
+            s"${side}Window before ${side}Time in that input's columns, or 
drop ${side}Time"))
+        }
+        Seq("left", "right").diff(sides).foreach { side =>
+          assert(!error.getMessage.contains(s"the $side input filters late 
rows"))
+        }
+      }
+
+      test(s"$joinType on a window after its event time in the default mode 
has no window hint") {
+        val error = intercept[AnalysisException] {
+          UnsupportedOperationChecker.checkForStreaming(
+            wrapInStreaming(windowJoin(joinType, windowFirst = false)), 
OutputMode.Append())
+        }
+        assert(error.getMessage.contains("allow unmatched state to be 
finalized"))
+        
assert(!error.getMessage.contains(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key))
+      }
+
+      assertSupportedInStreamingPlan(s"$joinType on a window before its event 
time in legacy mode",
+        windowJoin(joinType, windowFirst = true), OutputMode.Append(), 
legacyMode)
+    }
+  }
+
+  // Disabling the finalization check turns the admission failure into a 
warning.
+  Seq(LeftOuter, LeftSemi).foreach { joinType =>
+    val leftTime = AttributeReference("leftTime", 
TimestampType)().withMetadata(watermarkMetadata)
+    val rightTime = AttributeReference("rightTime", TimestampType)()
+    val plan = new TestStreamingRelation(leftTime).join(new 
TestStreamingRelation(rightTime),
+      joinType = joinType, condition = Some(leftTime === rightTime))
+    val checkConf = SQLConf.STREAMING_JOIN_CHECK_FINALIZATION_ENABLED.key
+    assertNotSupportedInStreamingPlan(s"$joinType without a right watermark",
+      plan, OutputMode.Append(), Seq("requires a watermark on the right 
input", checkConf))
+    assertSupportedInStreamingPlan(s"$joinType without a right watermark and 
$checkConf=false",
+      plan, OutputMode.Append(), checkConf -> "false")
+
+    // Joins that earlier versions rejected still fail, and the error does not 
offer the conf.
+    val noWatermark = AttributeReference("leftTime", TimestampType)()
+    val noWatermarkRight = AttributeReference("rightTime", TimestampType)()
+    val unsupported = new TestStreamingRelation(noWatermark).join(
+      new TestStreamingRelation(noWatermarkRight), joinType = joinType,
+      condition = Some(noWatermark === noWatermarkRight))
+    Seq("true", "false").foreach { enabled =>
+      test(s"$joinType without any watermark fails analysis when 
$checkConf=$enabled") {
+        withSQLConf(checkConf -> enabled) {
+          val e = intercept[AnalysisException] {
+            UnsupportedOperationChecker.checkForStreaming(
+              wrapInStreaming(unsupported), OutputMode.Append())
+          }
+          assert(e.getMessage.contains("requires a watermark on the right 
input"))
+          assert(!e.getMessage.contains(checkConf))
+        }
+      }
+    }
+
+    test(s"$joinType without a right watermark logs a warning when 
$checkConf=false") {
+      val appender = new LogAppender("finalization check")
+      withLogAppender(appender, level = Some(Level.WARN)) {
+        withSQLConf(checkConf -> "false") {
+          UnsupportedOperationChecker.checkForStreaming(wrapInStreaming(plan), 
OutputMode.Append())
+        }
+      }
+      val warnings = 
appender.loggingEvents.map(_.getMessage.getFormattedMessage)
+        .filter(_.contains("requires a watermark on the right input"))
+      assert(warnings.nonEmpty)
+      // The query starts with the check disabled, so the aggregation that the 
error says fails at
+      // start never emits instead.
+      if (joinType == LeftOuter) {
+        assert(warnings.forall { message =>
+          message.contains("an append-mode aggregation over that event time 
never emits results") &&
+            !message.contains("fails at start")
+        })
+      }
+    }
+  }
+
+  // The range-bound arm of the check that earlier versions applied keeps a 
join runnable with the
+  // conf false only when the range bounds the state of every input the join 
must finalize.

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 
[e03f9977b87](https://github.com/apache/spark/pull/60280/commits/e03f9977b8722bd5783107c6c4cb0ba933e10e52).
 The comment now says that the arm keeps a join runnable with the conf set to
   `false` when the range bounds the state of any input the join must finalize, 
which is what the full
   outer test below it expects.
   
   <!-- sp2k-review8 reply 4577114387 -->
   



##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinEqualityWatermarkSuite.scala:
##########
@@ -0,0 +1,409 @@
+/*
+ * 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.{DataFrame, 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.operators.stateful.join.StreamingSymmetricHashJoinHelper.{JoinStateKeyWatermarkPredicate,
 JoinStateValueWatermarkPredicate}
+import org.apache.spark.sql.execution.streaming.runtime.{MemoryStream, 
StreamExecution}
+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())
+    }
+  }
+
+  private def joinExec(query: StreamExecution): StreamingSymmetricHashJoinExec 
=
+    query.lastExecution.executedPlan.collectFirst {
+      case j: StreamingSymmetricHashJoinExec => j
+    }.get
+
+  /** Where the V4 eviction scan of the left key predicate starts in the last 
batch. */
+  private def leftPreviousScanBound(query: StreamExecution): Option[Long] =
+    joinExec(query).stateWatermarkPredicates.left.collect {
+      case p: JoinStateKeyWatermarkPredicate => p.prevStateWatermark
+    }.get
+
+  for {
+    version <- Seq(2, 3, 4)
+    offset <- Seq(10, -10)
+    // The analyzed plan keeps an interval expression unfolded; admission must 
still bound it.
+    (shiftedRightTime, spelling) <- Seq(
+      (s"rt + INTERVAL $offset SECONDS", ""),
+      (s"rt + INTERVAL 1 SECOND * $offset", " as an interval expression"),
+      (s"timestampadd(SECOND, $offset, rt)", " with timestampadd"))
+  } {
+    test(s"equality on a shifted opposite event time evicts state, V$version 
offset=$offset" +
+        spelling) {
+      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 = $shiftedRightTime"), "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(),
+          // The first batch has no previous eviction to start the V4 scan 
after.
+          Execute { query => assert(leftPreviousScanBound(query).isEmpty) },
+          AddData(rightInput, (1, 100)),
+          CheckNewAnswer(Row(1, 100 + offset, 1, 100)),
+          MultiAddData(leftInput, (9, 300))(rightInput, (9, 150)),
+          // At watermark 90, the left key cutoff is (90 + offset) s less the 
1 ms the solver
+          // subtracts for >=, so (2, 90 + offset) stays in state for one more 
batch.
+          CheckNewAnswer(),
+          // (4, 95) passes late filtering at 90 s. For offset 10 it is below 
the previous
+          // cutoff, 99.999 s, so the V4 scan must start after 90 s, not after 
that cutoff.
+          MultiAddData(leftInput, (4, 95))(rightInput, (9, 151)),
+          // At watermark 140, the left key cutoff is (140 + offset) s less 1 
ms.
+          CheckNewAnswer(Row(2, 90 + offset, null, null), Row(4, 95, null, 
null)),
+          Execute { query =>
+            val shiftedLateCutoff = 90000L + offset * 1000L - 1
+            assert(leftPreviousScanBound(query) === 
Some(math.min(shiftedLateCutoff, 90000L)))
+            // Retained left rows are above 140 + offset, retained right rows 
above 140 - offset.
+            
assert(joinExec(query).produceOutputWatermark(140000L).contains(129999L))
+          },
+          // Right time 145 is above watermark 140, so (3, 145 + offset) must 
still be in state.
+          AddData(rightInput, (3, 145)),
+          CheckNewAnswer(Row(3, 145 + offset, 3, 145)))
+      }
+    }
+  }
+
+  test("shifted key eviction scans from the start in legacy mode") {
+    withSQLConf(
+      SQLConf.STREAMING_JOIN_STATE_FORMAT_VERSION.key -> "4",
+      SQLConf.STATE_STORE_PROVIDER_CLASS.key -> 
classOf[RocksDBStateStoreProvider].getName,
+      SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> "false",
+      SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.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")
+      val joined = left.join(right, expr("lk = rk AND lt = rt + INTERVAL 10 
SECONDS"), "left_outer")
+        .select($"lk", $"lt".cast("int"), $"rk", $"rt".cast("int"))
+      testStream(joined)(
+        MultiAddData(leftInput, (1, 95), (8, 300))(rightInput, (9, 100)),
+        CheckNewAnswer(),
+        AddData(rightInput, (9, 120)),
+        // Legacy mode filters late rows and evicts at the same watermark, so 
it gives no earlier
+        // cutoff to start the V4 scan after.
+        CheckNewAnswer(Row(1, 95, null, null)),
+        Execute { query => assert(leftPreviousScanBound(query).isEmpty) })
+    }
+  }
+
+  for (version <- Seq(2, 3, 4)) {
+    test(s"key eviction on one side and value eviction on the other keep a 
match, V$version") {
+      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, Long)]
+        val rightInput = MemoryStream[(Int, Long, Long)]
+        val left = leftInput.toDF().toDF("leftId", "seconds")
+          .select($"leftId", timestamp_seconds($"seconds").as("leftTime"))
+          .withWatermark("leftTime", "1 hour")
+        val right = rightInput.toDF().toDF("rightId", "keySeconds", "seconds")
+          .select($"rightId", 
timestamp_seconds($"keySeconds").as("rightKeyTime"),
+            timestamp_seconds($"seconds").as("rightTime"))
+          .withWatermark("rightTime", "1 hour")
+        // The leftTime watermark bounds rightKeyTime, so the right side 
evicts by key, while the
+        // left side evicts on leftTime. The V4 left joiner derives a time 
window for its lookups
+        // into the right state, which must use the exact key timestamp 
instead.
+        val joined = left.join(right, expr(
+          "leftId = rightId AND leftTime = rightKeyTime AND " +
+            "rightTime >= leftTime + INTERVAL 10 SECONDS AND " +
+            "rightTime <= leftTime + INTERVAL 20 SECONDS"))
+          .select($"leftId", $"leftTime".cast("long"), 
$"rightTime".cast("long"))
+        testStream(joined)(
+          AddData(rightInput, (1, 100L, 115L)),
+          CheckNewAnswer(),
+          Execute { query =>
+            val join = query.lastExecution.executedPlan.collectFirst {
+              case j: StreamingSymmetricHashJoinExec => j
+            }.get
+            assert(join.stateWatermarkPredicates.left.exists(
+              _.isInstanceOf[JoinStateValueWatermarkPredicate]))
+            assert(join.stateWatermarkPredicates.right.exists(
+              _.isInstanceOf[JoinStateKeyWatermarkPredicate]))
+          },
+          AddData(leftInput, (1, 100L)),
+          CheckNewAnswer(Row(1, 100L, 115L)))
+      }
+    }
+  }
+
+  for (version <- Seq(2, 3, 4)) {
+    test(s"equality on a truncated opposite event time keeps matchable state, 
V$version") {
+      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, Long)]
+        val rightInput = MemoryStream[(Int, Long)]
+        val left = leftInput.toDF().toDF("lk", "ms")
+          .select($"lk", timestamp_millis($"ms").as("lt"))
+          .withWatermark("lt", "10 seconds")
+        val right = rightInput.toDF().toDF("rk", "ms")
+          .select($"rk", timestamp_millis($"ms").as("rt"))
+          .withWatermark("rt", "10 seconds")
+        val joined = left.join(right,
+          expr("lk = rk AND lt = CAST(CAST(rt AS BIGINT) AS TIMESTAMP)"))
+          .select($"lk", $"rk")
+        testStream(joined)(
+          MultiAddData(leftInput, (1, 25000L))(rightInput, (9, 25000L)),
+          CheckNewAnswer(),
+          MultiAddData(leftInput, (8, 35500L))(rightInput, (9, 35500L)),
+          CheckNewAnswer(),
+          AddData(rightInput, (9, 35600L)),
+          CheckNewAnswer(),
+          // rt = 25.7 seconds is above the watermark 25.5 seconds but 
truncates to lt = 25.
+          AddData(rightInput, (1, 25700L)),
+          CheckNewAnswer(Row(1, 1)))
+      }
+    }
+  }
+
+  // (shift, watermark row, evicting row, right time, left time by zone, other 
left rows)
+  // Each left time is the right time shifted in that zone. In Los Angeles a 
day across the
+  // spring-forward change is 23 hours and across the fall-back change 25 
hours.
+  private val dayShifts = Seq(
+    // One day after 2024-03-09T20:00Z.
+    ("+ INTERVAL 1 DAY", 1710012600000L, 1710012660000L, 1710014400000L,
+      Map("UTC" -> 1710100800000L, "America/Los_Angeles" -> 1710097200000L), 
Nil),
+    // One day and 36 hours before 2024-11-03T20:00Z. The other left row keeps 
the left
+    // watermark above the right one.
+    ("- INTERVAL 1 DAY", 1730662200000L, 1730662260000L, 1730664000000L,
+      Map("UTC" -> 1730577600000L, "America/Los_Angeles" -> 1730574000000L),
+      Seq(1730678400000L)),
+    ("- INTERVAL 36 HOURS", 1730662200000L, 1730662260000L, 1730664000000L,
+      Map("UTC" -> 1730534400000L, "America/Los_Angeles" -> 1730530800000L),
+      Seq(1730678400000L)))
+
+  for {
+    version <- Seq(2, 3, 4)
+    zone <- Seq("America/Los_Angeles", "UTC")
+    (shift, watermarkRow, evictingRow, rightTime, leftTimes, otherLeftRows) <- 
dayShifts
+  } {
+    test(s"equality on an opposite event time $shift across DST, V$version 
$zone") {
+      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",
+        SQLConf.SESSION_LOCAL_TIMEZONE.key -> zone) {
+        val leftInput = MemoryStream[(Int, Long)]
+        val rightInput = MemoryStream[(Int, Long)]
+        val left = leftInput.toDF().toDF("lk", "ms")
+          .select($"lk", timestamp_millis($"ms").as("lt"))
+          .withWatermark("lt", "0 seconds")
+        val right = rightInput.toDF().toDF("rk", "ms")
+          .select($"rk", timestamp_millis($"ms").as("rt"))
+          .withWatermark("rt", "0 seconds")
+        val joined = left.join(right, expr(s"lk = rk AND lt = rt $shift"))
+          .select($"lk", $"rk")
+        val leftRows = (1, leftTimes(zone)) +: otherLeftRows.map(time => (8, 
time))
+        testStream(joined)(
+          StreamProgressLockedActions(Seq(
+            AddData(leftInput, leftRows: _*), AddData(rightInput, (9, 
watermarkRow)))),
+          CheckNewAnswer(),
+          // Evicts at the right watermark, which is below rightTime.
+          AddData(rightInput, (9, evictingRow)),
+          CheckNewAnswer(),
+          AddData(rightInput, (1, rightTime)),
+          CheckNewAnswer(Row(1, 1)))
+      }
+    }
+  }
+
+  // A V4 input whose key is not its own event time is stored at the key 
timestamp only when the
+  // opposite key bounds that key. A restart may change the session time zone, 
which the offset
+  // log does not keep, so that choice must not depend on it: otherwise rows 
stored before the
+  // restart are looked up at another timestamp and no longer match.
+  for {
+    (shift, keyOffset) <- Seq(("+ INTERVAL 1 DAY", 86400000L), ("- INTERVAL 1 
DAY", -86400000L))
+    (firstZone, secondZone) <- Seq(("America/Los_Angeles", "UTC"), ("UTC", 
"America/Los_Angeles"))
+  } {
+    test(s"V4 keeps matching k = rt $shift after a restart from $firstZone to 
$secondZone") {
+      val leftInput = MemoryStream[(Int, Long)]
+      val rightInput = MemoryStream[(Int, Long)]
+      def joined(zone: String): DataFrame = {
+        var df: DataFrame = null
+        withSQLConf(SQLConf.SESSION_LOCAL_TIMEZONE.key -> zone) {
+          val left = leftInput.toDF().toDF("lk", "ms")
+            .select($"lk", timestamp_millis($"ms").as("k"))
+          val right = rightInput.toDF().toDF("rk", "ms")
+            .select($"rk", timestamp_millis($"ms").as("rt"))
+            .withWatermark("rt", "0 seconds")
+          df = left.join(right, expr(s"lk = rk AND k = rt 
$shift")).select($"lk", $"rk")
+        }
+        df
+      }
+      // 2024-01-15T00:00Z. January has no daylight saving change, so a day is 
24 hours in both
+      // zones.
+      val rightTime = 1705276800000L
+      def run(zone: String, checkpoint: String)(actions: StreamAction*): Unit =
+        withSQLConf(
+          SQLConf.STREAMING_JOIN_STATE_FORMAT_VERSION.key -> "4",
+          SQLConf.STATE_STORE_PROVIDER_CLASS.key -> 
classOf[RocksDBStateStoreProvider].getName,
+          SQLConf.SESSION_LOCAL_TIMEZONE.key -> zone) {
+          testStream(joined(zone))(StartStream(checkpointLocation = 
checkpoint) +: actions: _*)
+        }
+      withTempDir { dir =>
+        val checkpoint = dir.getCanonicalPath
+        run(firstZone, checkpoint)(
+          AddData(leftInput, (1, rightTime + keyOffset)), CheckNewAnswer(), 
StopStream)
+        run(secondZone, checkpoint)(AddData(rightInput, (1, rightTime)), 
CheckNewAnswer(Row(1, 1)))
+      }
+    }
+  }
+
+  for (version <- Seq(2, 4)) {
+    test(s"lookup key ordinals are not derived in every task, V$version") {
+      // A shifted key makes the lookup ordinal run the cutoff solver, which 
logs each cutoff it
+      // derives. Planning derives the same cutoffs whatever the number of 
partitions.
+      def solverLogLines(numPartitions: Int): Int = {
+        val logAppender = new LogAppender("stream-stream join state 
constraints")
+        withLogAppender(logAppender,
+            loggerNames = 
Seq(StreamingJoinHelper.getClass.getName.stripSuffix("$")),
+            level = Some(Level.INFO)) {
+          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",
+              SQLConf.SHUFFLE_PARTITIONS.key -> numPartitions.toString) {
+            val leftInput = MemoryStream[(Int, Int)]
+            val rightInput = MemoryStream[(Int, Int)]
+            val left = leftInput.toDF().toDF("lk", "t")
+              .select($"lk", timestamp_seconds($"t").as("lt"))
+              .withWatermark("lt", "0 seconds")
+            val right = rightInput.toDF().toDF("rk", "t")
+              .select($"rk", timestamp_seconds($"t").as("rt"))
+              .withWatermark("rt", "0 seconds")
+            val joined = left.join(right, expr("lk = rk AND lt = rt + INTERVAL 
10 SECONDS"))
+              .select($"lk", $"lt".cast("long"), $"rt".cast("long"))
+            testStream(joined)(
+              MultiAddData(leftInput, (1, 20))(rightInput, (1, 10)),
+              CheckNewAnswer(Row(1, 20L, 10L)),
+              MultiAddData(leftInput, (2, 40))(rightInput, (2, 30)),
+              CheckNewAnswer(Row(2, 40L, 30L)))
+          }
+        }
+        
logAppender.loggingEvents.count(_.getMessage.getFormattedMessage.contains(
+          "Final expression to evaluate constraint"))
+      }
+      assert(solverLogLines(numPartitions = 1) === 
solverLogLines(numPartitions = 5))

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 
[e03f9977b87](https://github.com/apache/spark/pull/60280/commits/e03f9977b8722bd5783107c6c4cb0ba933e10e52).
 The test now asserts that the run with one shuffle partition logs at least one
   solver line before it compares that count with the run with five partitions, 
so a reworded or moved log
   line makes the test fail instead of comparing 0 with 0.
   
   <!-- sp2k-review8 reply 4577114401 -->
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala:
##########
@@ -630,6 +671,231 @@ 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, and through windows built from it, which end after it. It 
stops at a 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 =>
+                windowSource(alias.toAttribute, 
alias.child).toSeq.flatMap(passThrough(p.child, _))
+              case _ => Nil
+            }
+          case e: ExpandExec =>
+            // A sliding window is one projection per window; each must carry 
the same column.
+            val index = e.output.indexWhere(_.exprId == attribute.exprId)
+            val traced = e.projections.map { projection =>
+              projection.lift(index).toSeq.flatMap {
+                case a: Attribute => passThrough(e.child, a)
+                case expression =>
+                  windowSource(e.output(index), 
expression).toSeq.flatMap(passThrough(e.child, _))
+              }
+            }
+            if (traced.nonEmpty && traced.forall(_.nonEmpty) && 
traced.distinct.size == 1) {
+              traced.head
+            } else {
+              Nil
+            }
+          case u: UnionExec =>
+            val index = u.output.indexWhere(_.exprId == attribute.exprId)
+            if (index < 0) Nil else u.children.flatMap(c => findJoinSides(c, 
c.output(index)))
+          case _: StateStoreWriter | _: EventTimeWatermarkExec | _: 
UpdateEventTimeColumnExec =>
+            Nil
+          case u: UnaryExecNode if u.output.exists(_.exprId == 
attribute.exprId) =>
+            passThrough(u.child, attribute)
+          case _ => Nil
+        }
+      }
+
+      // The inputs whose event-time column each operator compares with its 
input watermark.
+      def watermarkedInputs(node: SparkPlan): Seq[SparkPlan] = node match {
+        case _: StateStoreSaveExec | _: StatefulStreamlineAggregateExec |
+            _: SessionWindowStateStoreSaveExec | _: StreamingDeduplicateExec |
+            _: StreamingDeduplicateWithinWatermarkExec | _: 
StreamingSymmetricHashJoinExec =>
+          node.children
+        case f: FlatMapGroupsWithStateExec if f.timeoutConf == 
EventTimeTimeout => Seq(f.child)
+        case f: FlatMapGroupsInPandasWithStateExec if f.timeoutConf == 
EventTimeTimeout =>
+          Seq(f.child)
+        case t: TransformWithStateExec if t.timeMode == TimeMode.EventTime() 
=> Seq(t.child)
+        case t: TransformWithStateInPySparkExec if t.timeMode == 
TimeMode.EventTime() =>
+          Seq(t.child)
+        case _ => Nil
+      }
+
+      plan.flatMap { consumer =>
+        watermarkedInputs(consumer).flatMap { input =>
+          Try(WatermarkSupport.findEventTimeColumn(input.output,
+            allowMultipleEventTimeColumns = 
false)).toOption.flatten.toSeq.flatMap { column =>
+            findJoinSides(input, column).map { case (joinOperatorId, side, 
joinEventTime) =>
+              JoinWatermarkConsumer(consumer, joinOperatorId, side, 
joinEventTime)
+            }
+          }
+        }
+      }
+    }
+
+    /**
+     * Tell each stream-stream join which inputs' event times reach the 
stateful operator that
+     * consumes its output watermark, so that the join holds back that 
watermark only for those
+     * inputs' state. A join without a traced consumer holds back for both 
inputs.
+     */
+    private def withJoinOutputWatermarkSides(plan: SparkPlan): SparkPlan = {
+      val sides = 
joinWatermarkConsumers(plan).groupMap(_.joinOperatorId)(_.side)
+      if (sides.isEmpty) {
+        plan
+      } else {
+        plan transform {
+          case j: StreamingSymmetricHashJoinExec
+              if j.stateInfo.exists(info => sides.contains(info.operatorId)) =>
+            j.copy(outputWatermarkSides = 
Some(sides(j.stateInfo.get.operatorId).toSet))
+        }
+      }
+    }
+
+    /**
+     * Reject an append-mode aggregation whose event time comes from a 
stream-stream join input
+     * that the join cannot bound: the join holds back its output watermark 
for that input, so
+     * the aggregation would never emit a result. Only an aggregation that the 
tracer of
+     * [[joinWatermarkConsumers]] reaches fails; with the finalization check 
disabled, it is only
+     * logged.
+     */
+    private def checkJoinOutputWatermarkConsumers(plan: SparkPlan): Unit = {

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 
[e03f9977b87](https://github.com/apache/spark/pull/60280/commits/e03f9977b8722bd5783107c6c4cb0ba933e10e52).
 The Scaladoc of the start-time check now carries `TODO(SPARK-61509)` and names
   the operators that it does not reject yet: a later outer join, event-time 
timeouts in
   `flatMapGroupsWithState` and `transformWithState`, and an aggregation behind 
a later join.
   
   <!-- sp2k-review8 reply 4577114406 -->
   



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