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


##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinOutputWatermarkSuite.scala:
##########
@@ -0,0 +1,171 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.streaming
+
+import org.apache.spark.sql.{DataFrame, Row}
+import 
org.apache.spark.sql.execution.streaming.operators.stateful.join.StreamingSymmetricHashJoinExec
+import 
org.apache.spark.sql.execution.streaming.operators.stateful.join.StreamingSymmetricHashJoinHelper.{JoinSide,
 LeftSide, RightSide}
+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.{col, count, expr, timestamp_seconds, 
window}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.tags.SlowSQLTest
+
+@SlowSQLTest
+class StreamingJoinOutputWatermarkSuite extends StreamTest {
+  import testImplicits._
+
+  for (version <- Seq(2, 3, 4)) {
+    test(s"unbounded join state can emit an old event time after watermarks 
advance, 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("key", "seconds")
+          .select($"key", timestamp_seconds($"seconds").as("leftTime"))
+          .withWatermark("leftTime", "10 seconds")
+        val right = rightInput.toDF().toDF("key", "seconds")
+          .select($"key", timestamp_seconds($"seconds").as("rightTime"))
+          .withWatermark("rightTime", "10 seconds")
+        val result = left.join(right, Seq("key"))
+          .select($"key", $"leftTime")
+          .dropDuplicatesWithinWatermark("key")
+          .select($"key", $"leftTime".cast("long"))
+
+        testStream(result)(
+          MultiAddData((leftInput, Seq((1, 5L))), (rightInput, Seq((9, 5L)))),
+          CheckNewAnswer(),
+          MultiAddData((leftInput, Seq((2, 30L))), (rightInput, Seq((3, 
30L)))),
+          CheckNewAnswer(),
+          // Process another batch so the join's output watermark reaches 
downstream operators.
+          AddData(rightInput, (4, 40L)),
+          CheckNewAnswer(),
+          // The retained left key 1 can still join after both input 
watermarks reach 20 seconds.
+          // The right event is newer than that watermark, but the joined left 
time is only 5.
+          AddData(rightInput, (1, 100L)),
+          CheckNewAnswer((1, 5L)),
+          Execute { query =>
+            val join = query.lastExecution.executedPlan.collectFirst {
+              case j: StreamingSymmetricHashJoinExec => j
+            }.get
+            assert(join.eventTimeWatermarkForLateEvents.contains(20000L))
+            assert(join.produceOutputWatermark(20000L).contains(0L))
+          })
+      }
+    }
+  }
+
+  // Impressions are bounded by the click watermark; clicks have no lower 
bound on clickTime.
+  private def oneDirectionalJoin(): (MemoryStream[(Int, Long)], 
MemoryStream[(Int, Long)],
+      DataFrame) = {
+    val impressionInput = MemoryStream[(Int, Long)]
+    val clickInput = MemoryStream[(Int, Long)]
+    val impressions = impressionInput.toDF().toDF("impressionAdId", "seconds")
+      .select($"impressionAdId", 
timestamp_seconds($"seconds").as("impressionTime"))
+      .withWatermark("impressionTime", "10 seconds")
+    val clicks = clickInput.toDF().toDF("clickAdId", "seconds")
+      .select($"clickAdId", timestamp_seconds($"seconds").as("clickTime"))
+      .withWatermark("clickTime", "10 seconds")
+    val joined = impressions.join(clicks,
+      expr("clickAdId = impressionAdId AND clickTime <= impressionTime + 
INTERVAL 10 SECONDS"))
+    (impressionInput, clickInput, joined)
+  }
+
+  private def windowCounts(df: DataFrame, timeColumn: String): DataFrame = {
+    df.groupBy(window(col(timeColumn), "10 
seconds")).agg(count("*").as("count"))
+      .select($"window.start".cast("long"), $"count")
+  }
+
+  private def join(query: StreamExecution): StreamingSymmetricHashJoinExec = {
+    query.lastExecution.executedPlan.collectFirst {
+      case j: StreamingSymmetricHashJoinExec => j
+    }.get
+  }
+
+  private def runOneDirectionalJoin(
+      impressionInput: MemoryStream[(Int, Long)],
+      clickInput: MemoryStream[(Int, Long)],
+      result: DataFrame,
+      expectedRows: Seq[Row],
+      expectedSides: Option[Set[JoinSide]],
+      expectedOutputWatermark: Long): Unit = {
+    withSQLConf(SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> 
"false") {
+      testStream(result, OutputMode.Append())(
+        MultiAddData((impressionInput, Seq((1, 5L), (2, 15L), (3, 25L))),
+          (clickInput, Seq((1, 8L), (2, 20L)))),
+        ProcessAllAvailable(),
+        // The click at 30 seconds joins the retained impression at 25 seconds.
+        MultiAddData((impressionInput, Seq((4, 60L))), (clickInput, Seq((3, 
30L), (9, 70L)))),
+        ProcessAllAvailable(),
+        MultiAddData((impressionInput, Seq((5, 100L))), (clickInput, Seq((9, 
110L)))),
+        ProcessAllAvailable(),
+        AddData(clickInput, (9, 150L)),
+        ProcessAllAvailable(),
+        AddData(impressionInput, (6, 200L)),
+        ProcessAllAvailable(),
+        CheckAnswer(expectedRows: _*),
+        Execute { query =>
+          val j = join(query)
+          assert(j.outputWatermarkSides == expectedSides)
+          assert(j.produceOutputWatermark(j.eventTimeWatermarkForEviction.get)
+            .contains(expectedOutputWatermark))
+          // No joined row arrives behind the watermark of the operator after 
the join.
+          assert(query.recentProgress.flatMap(_.stateOperators)
+            .map(_.numRowsDroppedByWatermark).sum == 0)
+        })
+    }
+  }
+
+  test("output watermark follows the bounded input when only its event time is 
used") {

Review Comment:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM: Claude Opus 5.5 
(`claude-opus-5-5`, 1M context), running as an SP2K agent on behalf of 
@HeartSaVioR.
   
   Fixed in SPARK-61344 (#60279, 
[f9762a3d955](https://github.com/apache/spark/pull/60279/commits/f9762a3d9553a75e07fe884d6a60ef3253a2b8d1)).
 New tests cover deduplication, deduplication within the watermark and a 
downstream stream-stream join, with multiple stateful operators enabled. Each 
test checks that the join's output watermark follows the bounded input, at 
79999 ms, when the operator reads `impressionTime`, and holds back at 0 for 
`clickTime`. Dropping a consumer kind from the tracer, or mapping its column to 
the wrong input, fails the test.
   
   <!-- sp2k-review2 reply 4531361681 -->
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala:
##########
@@ -630,6 +633,71 @@ class IncrementalExecution(
       watermarkPropagator.propagate(currentBatchId, plan, 
watermarkForCurrBatch)
     }
 
+    /**
+     * Tell each stream-stream join which input's event time reaches the 
stateful operator that
+     * consumes its output watermark, so that the join holds back that 
watermark only for that
+     * input's state. The consumers below apply the watermark only to the 
event-time column of
+     * their input. The walk down to the join follows that column through 
nodes that pass it on
+     * unchanged, or turn it into a window that ends after it. Any other node 
or consumer leaves
+     * the join holding back for both inputs.
+     */
+    private def withJoinOutputWatermarkSides(plan: SparkPlan): SparkPlan = {
+      def eventTime(output: Seq[Attribute]): Option[Attribute] =
+        output.find(_.metadata.contains(EventTimeWatermark.delayKey))
+
+      def passThrough(child: SparkPlan, attribute: Attribute): Option[(Long, 
JoinSide)] =
+        child.output.find(_.exprId == 
attribute.exprId).flatMap(findJoinSide(child, _))
+
+      def findJoinSide(node: SparkPlan, attribute: Attribute): Option[(Long, 
JoinSide)] = {
+        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)
+          case p: ProjectExec =>
+            p.projectList.find(_.exprId == attribute.exprId).flatMap {
+              case a: Attribute => passThrough(p.child, a)
+              case Alias(a: Attribute, _) => passThrough(p.child, a)
+              case alias: Alias if alias.metadata.contains(TimeWindow.marker) 
=>
+                alias.child.references.toSeq match {
+                  case Seq(a) => passThrough(p.child, a)
+                  case _ => None
+                }
+              case _ => None
+            }
+          case a: BaseAggregateExec => passThrough(a.child, attribute)
+          case _: FilterExec | _: SortExec | _: ShuffleExchangeLike | _: 
StateStoreRestoreExec =>
+            passThrough(node.children.head, attribute)
+          case _ => None

Review Comment:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM: Claude Opus 5.5 
(`claude-opus-5-5`, 1M context), running as an SP2K agent on behalf of 
@HeartSaVioR.
   
   Agreed, fixed in SPARK-61344 (#60279, 
[f9762a3d955](https://github.com/apache/spark/pull/60279/commits/f9762a3d9553a75e07fe884d6a60ef3253a2b8d1)).
 The tracer now follows the event-time column:
   
   - through a union, to the column at the same position in each of its inputs;
   - through Expand, which plans a sliding window, when every projection builds 
the column from the same input column;
   - through a session window, as through a tumbling window;
   - through any other node that keeps the column's expression ID, such as the 
key column that `groupByKey` appends.
   
   It treats as consumers the streaming aggregations, including session windows 
and the streamline aggregate, both deduplication operators, a downstream 
stream-stream join, and `flatMapGroupsWithState`, `applyInPandasWithState` and 
`transformWithState` with event-time timeouts or timers. It still stops at any 
other operator that writes state or sets an event time, and at nodes it does 
not recognize; there the join holds back for both inputs. An event time 
computed by a function, such as a UDF, stays held back.
   
   Tests: for each path, the impressions and clicks join gives the base 
branch's results over `impressionTime`, with an output watermark of 79999 ms. 
Over `clickTime` it holds back at 0 and drops no joined row as late. A step 
that mapped a column to the wrong input fails one of the two. The union test 
now expects the windows at 0, 10 and 20 seconds, also with the join as the 
second input of the union. The Python operators are recognized the same way but 
have no Scala test. The start-time check in SPARK-61345 (#60280) uses this 
tracer, so it rejects only an aggregation that the tracer traces to a held 
input.
   
   <!-- sp2k-review2 reply 4531361691 -->
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala:
##########
@@ -721,14 +789,46 @@ class IncrementalExecution(
 
     override def apply(plan: SparkPlan): SparkPlan = {
       val planWithStateOpId = plan transform composedRule
+      // Validate the checkpoint-pinned semantics before writing state 
metadata or opening state,
+      // including a restart retrying an incomplete batch zero.
+      val requiredWatermarkSemanticsVersion =
+        
SQLConf.STREAMING_JOIN_CHECKPOINT_WATERMARK_SEMANTICS_VERSION.defaultValue.get
+      if (isFirstBatch &&
+          
conf.getConf(SQLConf.STREAMING_JOIN_CHECKPOINT_WATERMARK_SEMANTICS_VERSION) <
+            requiredWatermarkSemanticsVersion) {
+        def watermarkColumns(input: SparkPlan): String = {
+          val columns = input.output.filter(
+            _.metadata.contains(EventTimeWatermark.delayKey))
+          if (columns.isEmpty) "none" else columns.map(_.name).mkString(", ")
+        }
+        planWithStateOpId.foreach {
+          case j: StreamingSymmetricHashJoinExec
+              if 
!StreamingSymmetricHashJoinHelper.isWatermarkCheckpointCompatible(
+                j.left.output, j.right.output, j.leftKeys, j.rightKeys, 
j.condition.full) =>
+            // Name the side of each equality key; both inputs often use the 
same column names.
+            val keyConditions = j.leftKeys.zip(j.rightKeys).map { case (left, 
right) =>
+              s"left.${left.sql} = right.${right.sql}"
+            }
+            val conditions = keyConditions ++ j.condition.full.map(_.sql)
+            val joinCondition = if (conditions.isEmpty) "none" else 
conditions.mkString(" AND ")
+            throw new AnalysisException(
+              errorClass = "STREAMING_JOIN_CHECKPOINT_INCOMPATIBLE",
+              messageParameters = Map(
+                "joinCondition" -> joinCondition,
+                "leftWatermarkColumns" -> watermarkColumns(j.left),
+                "rightWatermarkColumns" -> watermarkColumns(j.right)))
+          case _ =>
+        }
+      }
       // Need to check before write to metadata because we need to detect add 
operator
       // Only check when streaming is restarting and is first batch
       if (isFirstBatch && currentBatchId != 0) {
         checkOperatorValidWithMetadata(planWithStateOpId, currentBatchId - 1)
       }
 
       stateStoreWritersWithMetadata = Some(Seq.empty)
-      val planWithSchemas = planWithStateOpId transform 
StateSchemaAndOperatorMetadataRule.rule
+      val planWithSchemas = withJoinOutputWatermarkSides(

Review Comment:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM: Claude Opus 5.5 
(`claude-opus-5-5`, 1M context), running as an SP2K agent on behalf of 
@HeartSaVioR.
   
   Confirmed, and fixed in 
[f9762a3d955](https://github.com/apache/spark/pull/60279/commits/f9762a3d9553a75e07fe884d6a60ef3253a2b8d1)
 as you suggested. We reproduced it with a V4 checkpoint of your chained joins 
written by the base branch. On resume, the downstream left outer join never 
emitted a row whose time lay between the old cutoff and the re-simulated scan 
start. Now, on the first batch after restoring a checkpoint pinned to an older 
generation, every stream-stream join gets no V4 scan start, as on a query's 
first batch and in legacy mode. That batch evicts every entry at or below its 
cutoff. Restarts of current-generation checkpoints keep their scan starts. A 
new checkpoint test checks both cases, and the checkpoint written by the base 
branch now resumes with the base branch's output. Because the fix applies to 
every join, it also covers plans that a wider output-watermark tracer narrows.
   
   <!-- sp2k-review2 reply 4531361702 -->
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/SymmetricHashJoinStateManager.scala:
##########
@@ -441,11 +451,26 @@ class SymmetricHashJoinStateManagerV4(
   private val tsWithKey = new TsWithKeyTypeStore
 
   override def append(key: UnsafeRow, value: UnsafeRow, matched: Boolean): 
Unit = {
-    val eventTime = 
extractEventTimeFnFromKey(key).getOrElse(extractEventTimeFn(value))
+    // A null selected key or indexed value timestamp makes the eviction 
predicate SQL-unknown.
+    // Keep such a row in a primary random bucket only, so timestamp eviction 
cannot remove it.
+    val timestamp = if (joinKeyOrdinalForWatermark.isDefined) {
+      extractTimestampFromKey(key)
+    } else {
+      extractTimestampFromValue(value)
+    }
+    // When no timestamp is available, we will use random bucketing strategy 
to decide where the
+    // new value will be stored. There is a trade-off between the bucket size 
and the number of
+    // values in each bucket; we can tune the bucket size with the 
configuration if we figure out
+    // the magic number to not work well. On a side that is indexed by 
timestamp, evicting a real
+    // row removes every value with the same key and timestamp, which must not 
include a row
+    // without a timestamp. Use the lowest timestamps for such rows: a real 
event time within
+    // the first 1024 microseconds of the timestamp range (year -290308) would 
still share them.
+    val bucket = random.nextInt(bucketCountWithoutTimestamp)

Review Comment:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM: Claude Opus 5.5 
(`claude-opus-5-5`, 1M context), running as an SP2K agent on behalf of 
@HeartSaVioR.
   
   Fixed in 
[f9762a3d955](https://github.com/apache/spark/pull/60279/commits/f9762a3d9553a75e07fe884d6a60ef3253a2b8d1):
 append now draws the random bucket only inside the fallback for a row without 
a timestamp. The stored rows are the same, and the V4 state manager tests for 
rows without a timestamp pass.
   
   <!-- sp2k-review2 reply 4531361706 -->
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -224,98 +228,221 @@ object StreamingSymmetricHashJoinHelper extends Logging {
     WatermarkSupport.findEventTimeColumn(rightAttributes,
       allowMultipleEventTimeColumns = useFirstEventTimeColumn)
 
-    val joinKeyOrdinalForWatermark: Option[Int] = 
findJoinKeyOrdinalForWatermark(
-      leftKeys, rightKeys)
-
     def getOneSideStateWatermarkPredicate(
         oneSideInputAttributes: Seq[Attribute],
         oneSideJoinKeys: Seq[Expression],
-        otherSideInputAttributes: Seq[Attribute]): 
Option[JoinStateWatermarkPredicate] = {
-      val isWatermarkDefinedOnInput = 
oneSideInputAttributes.exists(_.metadata.contains(delayKey))
+        otherSideInputAttributes: Seq[Attribute],
+        otherSideJoinKeys: Seq[Expression]): 
Option[JoinStateWatermarkPredicate] = {
+      // State is bounded by future input from the opposite side, not by its 
own watermark.
+      val joinKeyOrdinalForWatermark = 
StreamingJoinHelper.getStateKeyWatermarkOrdinal(
+        otherSideJoinKeys, otherSideInputAttributes)
       val isWatermarkDefinedOnJoinKey = joinKeyOrdinalForWatermark.isDefined
 
       if (isWatermarkDefinedOnJoinKey) { // case 1 and 3 in the 
StreamingSymmetricHashJoinExec docs
+        val ordinal = joinKeyOrdinalForWatermark.get
         val keyExprWithWatermark = BoundReference(
-          joinKeyOrdinalForWatermark.get,
-          oneSideJoinKeys(joinKeyOrdinalForWatermark.get).dataType,
-          oneSideJoinKeys(joinKeyOrdinalForWatermark.get).nullable)
-        val expr = watermarkExpression(Some(keyExprWithWatermark), 
eventTimeWatermarkForEviction)
-        expr.map { e =>
-          // V4 can skip keys at or below the previous watermark only if 
late-input filtering
-          // rejects new rows in that range on this same key. A watermark on 
the other input's
-          // equality key can drive eviction even when this input has no 
watermark, or has one
-          // on a different column. New rows can then pass late-input 
filtering with keys
-          // already eligible for eviction. V4 must scan from the beginning to 
find them;
-          // otherwise, outer joins can fail to emit null rows for these 
unmatched inputs.
-          val prevStateKeyWatermark =
-            if (oneSideInputAttributes.find(_.metadata.contains(delayKey))
-              
.exists(oneSideJoinKeys(joinKeyOrdinalForWatermark.get).semanticEquals)) {
-              eventTimeWatermarkForLateEvents
-            } else {
-              None
-            }
-          // watermarkExpression only provides the expression when 
eventTimeWatermarkForEviction
-          // is defined.
-          JoinStateKeyWatermarkPredicate(
-            e,
-            eventTimeWatermarkForEviction.get,
-            prevStateKeyWatermark)
-        }
-      } else if (isWatermarkDefinedOnInput) { // case 2 in the 
StreamingSymmetricHashJoinExec docs
-        val stateValueWatermark = StreamingJoinHelper.getStateValueWatermark(
-          attributesToFindStateWatermarkFor = 
AttributeSet(oneSideInputAttributes),
-          attributesWithEventWatermark = 
AttributeSet(otherSideInputAttributes),
-          condition,
-          eventTimeWatermarkForEviction)
-        // A row can pass late-input filtering but already be eligible for 
eviction in this batch.
-        // When the previous join-derived state cutoff is ahead of the 
late-input watermark, a new
-        // row can fall at or below that cutoff. V4 must scan from the 
beginning to find such rows.
-        val prevStateValueWatermark = eventTimeWatermarkForLateEvents.flatMap 
{ lateWatermark =>
-          StreamingJoinHelper.getStateValueWatermark(
-            attributesToFindStateWatermarkFor = 
AttributeSet(oneSideInputAttributes),
-            attributesWithEventWatermark = 
AttributeSet(otherSideInputAttributes),
-            condition,
-            eventTimeWatermarkForLateEvents).filter(_ <= lateWatermark)
+          ordinal, oneSideJoinKeys(ordinal).dataType, 
oneSideJoinKeys(ordinal).nullable)
+        // The opposite watermark bounds this key, shifted by an exact 
constant in the opposite
+        // key. See StreamingJoinHelper.getStateKeyWatermark for the shifts it 
accepts.
+        def keyWatermark(watermark: Option[Long]): Option[Long] =
+          StreamingJoinHelper.getStateKeyWatermark(
+            otherSideJoinKeys, otherSideInputAttributes, ordinal, watermark)
+        keyWatermark(eventTimeWatermarkForEviction).flatMap { stateWatermark =>
+          watermarkExpression(Some(keyExprWithWatermark), 
Some(stateWatermark)).map { e =>
+            // V4 can skip keys at or below the previous watermark only if 
late-input filtering
+            // rejects new rows in that range on this same key. A watermark on 
the other input's
+            // equality key can drive eviction even when this input has no 
watermark, or has one
+            // on a different column. New rows can then pass late-input 
filtering with keys
+            // already eligible for eviction. V4 must scan from the beginning 
to find them;
+            // otherwise, outer joins can fail to emit null rows for these 
unmatched inputs.
+            val prevStateKeyWatermark =
+              if (oneSideInputAttributes.find(_.metadata.contains(delayKey))
+                .exists(oneSideJoinKeys(ordinal).semanticEquals)) {
+                // Late filtering drops new keys at or below the late-input 
watermark, and the
+                // previous batch evicted keys up to its cutoff, which is the 
cutoff at that
+                // watermark. A shifted cutoff can lie on either side of the 
watermark, so the
+                // scan starts after the lower of the two.
+                eventTimeWatermarkForLateEvents.flatMap { lateWatermark =>
+                  keyWatermark(Some(lateWatermark)).map(math.min(_, 
lateWatermark))
+                }
+              } else {
+                None
+              }
+            JoinStateKeyWatermarkPredicate(e, stateWatermark, 
prevStateKeyWatermark)
+          }
         }
-        val inputAttributeWithWatermark = 
oneSideInputAttributes.find(_.metadata.contains(delayKey))
-        val expr = watermarkExpression(inputAttributeWithWatermark, 
stateValueWatermark)
-        expr.map { e =>
-          // watermarkExpression only provides the expression when 
eventTimeWatermarkForEviction
-          // is defined
-          JoinStateValueWatermarkPredicate(e, stateValueWatermark.get, 
prevStateValueWatermark)
+      } else { // case 2 in the StreamingSymmetricHashJoinExec docs
+        // Future matches are limited by the opposite watermark. This input 
needs no watermark;
+        // its event-time column may also have been pruned from the physical 
join.
+        val otherSideEventTime = 
otherSideInputAttributes.find(_.metadata.contains(delayKey))
+        getStateValueWatermarkForInput(oneSideInputAttributes, 
otherSideInputAttributes,
+          condition, eventTimeWatermarkForEviction).flatMap { case (attribute, 
watermark) =>
+          // Late filtering only constrains the input's event-time column. A 
different indexed
+          // column can admit values below the previous cutoff and must be 
scanned from the start.
+          val prevStateValueWatermark = eventTimeWatermarkForLateEvents.filter 
{ _ =>
+            oneSideInputAttributes.find(_.metadata.contains(delayKey))
+              .exists(_.semanticEquals(attribute))
+          }.flatMap { lateWatermark =>
+            // Also scan from the start if the derived cutoff exceeds the 
late-input watermark.
+            
StreamingJoinHelper.getStateValueWatermark(AttributeSet(Seq(attribute)),
+              AttributeSet(otherSideEventTime.toSeq), condition, 
Some(lateWatermark))
+              .filter(_ <= lateWatermark)
+          }
+          watermarkExpression(Some(attribute), Some(watermark)).map { e =>
+            JoinStateValueWatermarkPredicate(e, watermark, 
prevStateValueWatermark)
+          }
         }
-      } else {
-        None
       }
     }
 
     val leftStateWatermarkPredicate =
-      getOneSideStateWatermarkPredicate(leftAttributes, leftKeys, 
rightAttributes)
+      getOneSideStateWatermarkPredicate(leftAttributes, leftKeys, 
rightAttributes, rightKeys)
     val rightStateWatermarkPredicate =
-      getOneSideStateWatermarkPredicate(rightAttributes, rightKeys, 
leftAttributes)
+      getOneSideStateWatermarkPredicate(rightAttributes, rightKeys, 
leftAttributes, leftKeys)
     JoinStateWatermarkPredicates(leftStateWatermarkPredicate, 
rightStateWatermarkPredicate)
   }
 
-  private[join] def findJoinKeyOrdinalForWatermark(
+  /** Keep each cutoff attached to the column constrained by the join 
condition. */
+  private def getStateValueWatermarkForInput(
+      inputAttributes: Seq[Attribute],
+      otherInputAttributes: Seq[Attribute],
+      condition: Option[Expression],
+      eventWatermark: Option[Long]): Option[(Attribute, Long)] = {
+    val eventTime = inputAttributes.find(_.metadata.contains(delayKey))
+    // Only the first marked column is checked for late input in compatibility 
mode.
+    val otherEventTime = 
otherInputAttributes.find(_.metadata.contains(delayKey))
+    // First try the watermarked column. If it has no inferable bound, try the 
other timestamp
+    // columns in input schema order and use the first with a bound. This 
makes the indexed column
+    // deterministic for a fixed input schema and join condition.
+    val candidates = eventTime.toSeq ++ inputAttributes.filter { attribute =>
+      attribute.dataType == TimestampType && 
!eventTime.exists(_.semanticEquals(attribute))
+    }
+    candidates.iterator.flatMap { attribute =>
+      StreamingJoinHelper.getStateValueWatermark(AttributeSet(Seq(attribute)),
+        AttributeSet(otherEventTime.toSeq), condition, eventWatermark,
+        exactForUnwatermarkedColumns = true).map(attribute -> _)

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.
   
   Thanks, confirmed: whether the expiry bound gave a cutoff decided the V4 
index column and lookup ordinal, and that followed the session time zone. Fixed 
in 
[0ad26f2a1fa](https://github.com/apache/spark/pull/60282/commits/0ad26f2a1fadc24b49703e6d3d849eaf80f650e1)
 by making the rule independent of the zone, as for equality keys. For a column 
without its own watermark, an interval of a day or more now counts as inexact 
in every session time zone, including UTC. In your example the left side gets 
no cutoff in either zone, so V4 stores and finds its rows by `leftTime` before 
and after a restart. New V4 tests restart that join from UTC to 
America/Los_Angeles and back, and still return the match after the right 
watermark passes the old expiry cutoff. The cost is that in UTC such a bound no 
longer finalizes an input without its own watermark either; the analysis error 
and the guides now say so. We chose this over separating the stored column from 
the cutoff because it keeps one rule for k
 eys and range bounds and leaves the V4 layout code as it is. Counting whole 
days conservatively, which would let these bounds evict again, is SPARK-61381.
   
   <!-- sp2k-review2 reply 4531361718 -->
   



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