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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -17,36 +17,395 @@
 
 package org.apache.spark.sql.catalyst.analysis
 
+import java.util.Locale
+
 import scala.util.control.NonFatal
 
 import org.apache.spark.internal.Logging
 import org.apache.spark.internal.LogKeys._
 import org.apache.spark.sql.catalyst.expressions._
-import org.apache.spark.sql.catalyst.planning.ExtractEquiJoinKeys
-import org.apache.spark.sql.catalyst.plans.logical.{EventTimeWatermark, 
LogicalPlan}
+import org.apache.spark.sql.catalyst.plans.logical.{EventTimeWatermark, 
Expand, Filter, Join, LogicalPlan, Project, SubqueryAlias, Union}
 import org.apache.spark.sql.catalyst.plans.logical.EventTimeWatermark._
-import org.apache.spark.sql.catalyst.util.DateTimeConstants.MICROS_PER_DAY
+import org.apache.spark.sql.catalyst.util.DateTimeConstants.{MICROS_PER_DAY, 
MICROS_PER_HOUR, MICROS_PER_MILLIS, MICROS_PER_MINUTE, MICROS_PER_SECOND}
 import org.apache.spark.sql.types._
 import org.apache.spark.unsafe.types.CalendarInterval
 
+/**
+ * Pairs of attributes `(key, eventTime)` where `key` is a copy of 
`eventTime`, or a tumbling or
+ * sliding time window over it, in every row of every stream-stream join input 
that outputs both.
+ * See [[StreamingJoinHelper.findEventTimeCopies]].
+ */
+case class EventTimeCopies(pairs: Set[(ExprId, ExprId)]) {
+  def isCopyOf(key: Expression, eventTime: Attribute): Boolean = key match {
+    case a: Attribute => pairs.contains((a.exprId, eventTime.exprId))
+    case _ => false
+  }
+
+  def keys: Set[ExprId] = pairs.map(_._1)
+}
+
+object EventTimeCopies {
+  val empty: EventTimeCopies = EventTimeCopies(Set.empty)
+}
+
 /**
  * Helper object for stream joins. See [[StreamingSymmetricHashJoinExec]] in 
SQL for more details.
  */
 object StreamingJoinHelper extends PredicateHelper with Logging {
 
   /**
-   * Check the provided logical plan to see if its join keys contain a 
watermark attribute.
-   *
-   * Will return false if the plan is not an equijoin.
-   * @param plan the logical plan to check
+   * Find the equality key filtered by this input's watermark. Its ordinal can 
be used to
+   * evict the opposite input's state, whose equality keys have the same 
ordering.
+   * For leftTime = rightTime, a watermark on rightTime bounds leftTime even 
when leftTime
+   * has no watermark. It does not bound right-side state without a watermark 
on leftTime.
+   * A key computed from the event time by adding constant intervals, such as
+   * leftTime = rightTime + INTERVAL 10 SECONDS or leftTime = 
timestampadd(HOUR, 1, rightTime),
+   * is bounded too if the solver can count the intervals exactly or they 
never move a time
+   * backward; see [[getStateKeyWatermark]]. The result does not depend on the 
session time zone,
+   * so neither does the V4 state layout.
+   */
+  def getStateKeyWatermarkOrdinal(
+      keys: Seq[Expression],
+      inputAttributes: Seq[Attribute],
+      eventTimeCopies: EventTimeCopies = EventTimeCopies.empty): Option[Int] = 
{
+    getEventTimeKeyOrdinal(keys, inputAttributes, eventTimeCopies).orElse {
+      keys.indices.find(getStateKeyWatermark(keys, inputAttributes, _, 
Some(0L)).isDefined)
+    }
+  }
+
+  /**
+   * Find the equality key that is this input's event-time column itself, or 
else one that
+   * `eventTimeCopies` names as a copy of that column or a time window over 
it. Such a key is
+   * above the watermark in every row that passes late filtering, as the 
column is: a window
+   * ends after every time it contains.
+   */
+  def getEventTimeKeyOrdinal(
+      keys: Seq[Expression],
+      inputAttributes: Seq[Attribute],
+      eventTimeCopies: EventTimeCopies = EventTimeCopies.empty): Option[Int] = 
{
+    // When multiple stateful operators are disabled, late filtering uses the 
first event-time
+    // column. Otherwise, execution rejects multiple distinct event-time 
columns.
+    inputAttributes.find(_.metadata.contains(delayKey)).flatMap { eventTime =>
+      Seq(keys.indexWhere(_.semanticEquals(eventTime)),
+        keys.indexWhere(eventTimeCopies.isCopyOf(_, eventTime))).find(_ >= 0)
+    }
+  }
+
+  /**
+   * In legacy mode 
(spark.sql.streaming.statefulOperator.allowMultiple=false), an input can keep
+   * its event time and a copy of it or a time window over it, all 
watermarked, and it filters
+   * late rows by the first of them. Find, for each stream-stream join input 
in `plan`, which of
+   * its watermarked columns are a copy of, or a tumbling or sliding time 
window over, another of
+   * them. A pair counts only if every join input that outputs both columns 
builds it that way,
+   * so the result does not depend on how a physical join is matched to its 
logical one: the
+   * physical inputs output the same values under the same expression IDs, or 
fewer columns.
+   */
+  def findEventTimeCopies(plan: LogicalPlan): EventTimeCopies = {
+    val verdicts = plan.collect {
+      case j: Join if j.left.isStreaming && j.right.isStreaming => Seq(j.left, 
j.right)
+    }.flatten.flatMap { input =>
+      val watermarked = 
input.output.filter(_.metadata.contains(delayKey)).map(_.exprId).distinct
+      for (key <- watermarked; eventTime <- watermarked if key != eventTime) 
yield {
+        (key, eventTime) -> isCopyOrWindowOf(input, key, eventTime, 
allowWindow = true)
+      }
+    }
+    val rejected = verdicts.collect { case (pair, false) => pair }.toSet
+    EventTimeCopies(verdicts.collect { case (pair, true) if !rejected(pair) => 
pair }.toSet)
+  }
+
+  /**
+   * Whether `key` is `eventTime`, or a tumbling or sliding time window over 
it when
+   * `allowWindow`, in every row of `plan`. The walk follows both columns down 
by expression ID
+   * through nodes that pass values on unchanged, to the same positions in 
every input of a union,
+   * and to the node that [[TimeWindowResolution.TIME_WINDOW_SOURCE_TAG]] 
marks as building the
+   * window from an attribute, which must then be a copy of `eventTime`. Any 
other node, or any
+   * other expression, such as a shifted time, a session window or a window 
over another column,
+   * gives false.
    */
-  def isWatermarkInJoinKeys(plan: LogicalPlan): Boolean = {
-    plan match {
-      case ExtractEquiJoinKeys(_, leftKeys, rightKeys, _, _, _, _, _) =>
-        (leftKeys ++ rightKeys).exists {
-          case a: AttributeReference => 
a.metadata.contains(EventTimeWatermark.delayKey)
-          case _ => false
+  private def isCopyOrWindowOf(
+      plan: LogicalPlan,
+      key: ExprId,
+      eventTime: ExprId,
+      allowWindow: Boolean): Boolean = {
+    def passedOn(e: Expression): Option[ExprId] = e match {
+      case a: Attribute => Some(a.exprId)
+      case Alias(a: Attribute, _) => Some(a.exprId)
+      case _ => None
+    }
+    // The time column that the node tagged by the window rewrite builds 
`window` from.
+    def timeColumnOf(node: LogicalPlan, window: ExprId): Option[ExprId] =
+      node.getTagValue(TimeWindowResolution.TIME_WINDOW_SOURCE_TAG).collect {
+        case (id, timeColumn) if allowWindow && id == window => timeColumn
+      }
+    if (key == eventTime) {
+      true
+    } else {
+      plan match {
+        case p: Project =>
+          val keyEntry = p.projectList.find(_.exprId == key)
+          val eventTimeEntry = p.projectList.find(_.exprId == eventTime)
+          (keyEntry, eventTimeEntry.flatMap(passedOn)) match {
+            case (Some(entry), Some(childEventTime)) => passedOn(entry) match {
+              case Some(childKey) =>
+                isCopyOrWindowOf(p.child, childKey, childEventTime, 
allowWindow)
+              case None => timeColumnOf(p, key).exists { timeColumn =>
+                entry.references.map(_.exprId).toSet == Set(timeColumn) &&
+                  isCopyOrWindowOf(p.child, timeColumn, childEventTime, 
allowWindow = false)
+              }
+            }
+            case _ => false
+          }
+        case e: Expand =>
+          // The rewrite of a sliding window puts one window per projection 
beside the child's
+          // columns, which every projection passes on.
+          val keyIndex = e.output.indexWhere(_.exprId == key)
+          val eventTimeIndex = e.output.indexWhere(_.exprId == eventTime)
+          lazy val childEventTimes = e.projections.map(p => 
passedOn(p(eventTimeIndex))).distinct
+          keyIndex >= 0 && eventTimeIndex >= 0 && childEventTimes.size == 1 &&
+            childEventTimes.head.isDefined && timeColumnOf(e, key).exists { 
timeColumn =>
+              e.projections.forall(_(keyIndex).references.map(_.exprId).toSet 
== Set(timeColumn)) &&
+                isCopyOrWindowOf(e.child, timeColumn, childEventTimes.head.get,
+                  allowWindow = false)
+            }
+        case u: Union =>
+          val keyIndex = u.output.indexWhere(_.exprId == key)
+          val eventTimeIndex = u.output.indexWhere(_.exprId == eventTime)
+          keyIndex >= 0 && eventTimeIndex >= 0 && u.children.forall { child =>
+            isCopyOrWindowOf(child, child.output(keyIndex).exprId,
+              child.output(eventTimeIndex).exprId, allowWindow)
+          }
+        case _: Filter | _: SubqueryAlias | _: EventTimeWatermark =>
+          isCopyOrWindowOf(plan.children.head, key, eventTime, allowWindow)
+        case _ => false

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. Fixed in 
[e03f9977b87](https://github.com/apache/spark/pull/60280/commits/e03f9977b8722bd5783107c6c4cb0ba933e10e52)
 by changing the legacy-mode rule the other way round. With
   `spark.sql.streaming.statefulOperator.allowMultiple=false`, every 
watermarked equality key
   now bounds the other input's state again, as on the base branch. The plan 
walk no longer has
   to recognize a shape to accept it. It only rejects a key when it can show 
that some rows hold
   the key below a watermarked column that comes before it in the same input: a 
copy of, or a
   window over, a time shifted backward; a copy of a column that an earlier 
watermarked window is
   built over; and a union whose inputs build the key differently, including an 
input that does
   not watermark that column although the union, which takes its first input's 
metadata, does.
   Anything the walk cannot see through keeps the key.
   
   The walk follows both columns through any node with one input whose child 
outputs both, so a
   repartition, a temporary view read from SQL, a typed filter, `observe`, a 
hint and the
   streaming side of a stream-static join no longer matter, and a shifted 
window behind them is
   still rejected. It recognizes windows by the marker metadata and their 
single attribute
   reference instead of a tag, so self-joins work, and session windows bound 
state. Default mode
   is unchanged. The tests cover each of these shapes for every join type on 
state formats 2 and
   3, a restart and self-joins, and the rejected shapes: an inner join on a 
shifted window, and
   on a copy of the event time after a window over it, keeps the match that 
evicting by the key
   would drop. The error hint and the migration guide describe the new rule.
   
   One shape is rejected on purpose: a copy of the event time placed after a 
window over it, such as `[k, t, w = window(t), c = t]` joined on `c`. In legacy 
mode, late rows are filtered by the input's first watermarked column in the 
planned query, and whether `t` survives depends on column pruning, which 
analysis cannot see. If the optimizer prunes `t`, rows are filtered by the 
window instead, and evicting by `c` drops rows that can still match, as the 
base branch does; the test "inner join on a copy after a window with the time 
pruned" shows the lost match. Accepting it safely would need a start-time check 
on the planned query, which is the fragile check that this commit removes. 
Joining on `t` itself or on the window avoids the rejection, and the error hint 
and the migration guide say so.
   
   If you see a way to accept this shape that does not depend on a start-time 
check of the planned query, please suggest it. Otherwise we keep the rejection, 
for the reason above.
   
   <!-- sp2k-review8 reply 4577114370 -->
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala:
##########
@@ -721,14 +987,77 @@ 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.
+      if (isFirstBatchWithOlderJoinWatermarkSemantics) {
+        def watermarkColumns(input: SparkPlan): String = {
+          val columns = input.output.filter(
+            _.metadata.contains(EventTimeWatermark.delayKey))
+          if (columns.isEmpty) "none" else columns.map(_.name).mkString(", ")
+        }
+        // A join's output watermark reaches every stateful operator above it. 
One that uses its
+        // input watermark reads the inputs that the tracer names, or both 
inputs when it cannot
+        // be traced. An operator uses it when an input carries an event-time 
column, when it
+        // fires event-time timeouts, or when it passes the watermark to user 
code, as
+        // transformWithState does in every time mode. The join's output 
watermark changes
+        // nothing for any other operator, such as an update-mode count on a 
key.
+        def usesInputWatermark(operator: StatefulOperator): Boolean = operator 
match {
+          case _: TransformWithStateExec | _: TransformWithStateInPySparkExec 
=> true
+          case f: FlatMapGroupsWithStateExec if f.timeoutConf == 
EventTimeTimeout => true
+          case f: FlatMapGroupsInPandasWithStateExec if f.timeoutConf == 
EventTimeTimeout => true
+          case _ => operator.children.exists(
+            _.output.exists(_.metadata.contains(EventTimeWatermark.delayKey)))
+        }
+        val joinsBelowStatefulOperators = planWithStateOpId.collect {
+          case s: StatefulOperator if usesInputWatermark(s) => 
s.children.flatMap(_.collect {
+            case j: StreamingSymmetricHashJoinExec => 
j.stateInfo.map(_.operatorId)
+          }.flatten)
+        }.flatten.toSet
+        val tracedSides = joinWatermarkConsumers(planWithStateOpId)
+          .groupMap(_.joinOperatorId)(_.side)
+        def consumedSides(j: StreamingSymmetricHashJoinExec): Set[JoinSide] =
+          j.stateInfo.map(_.operatorId) match {
+            case Some(id) if joinsBelowStatefulOperators.contains(id) =>
+              tracedSides.get(id).map(_.toSet).getOrElse(Set(LeftSide, 
RightSide))
+            case _ => Set.empty
+          }
+        planWithStateOpId.foreach {
+          case j: StreamingSymmetricHashJoinExec
+              if 
!StreamingSymmetricHashJoinHelper.isWatermarkCheckpointCompatible(
+                j.left.output, j.right.output, j.leftKeys, j.rightKeys, 
j.condition.full,
+                consumedSides(j)) =>
+            // 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 _ =>
+        }
+      }
+      // Like the checkpoint check, this runs before state metadata is written 
or state opened.
+      // With a single global watermark, the join's output watermark does not 
reach the consumers.
+      if (isFirstBatch && allowMultipleStatefulOperators) {
+        checkJoinOutputWatermarkConsumers(planWithStateOpId)
+      }
+      if (isFirstBatch && eventTimeCopies.pairs.nonEmpty) {

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. This check is gone in 
[e03f9977b87](https://github.com/apache/spark/pull/60280/commits/e03f9977b8722bd5783107c6c4cb0ba933e10e52).
 There is no tag any more: the walk reads only
   the plan's operators, which every batch's analyzed plan keeps, and anything 
it cannot read
   keeps the key, as on the base branch. A key is now checked against every 
watermarked column
   before it, not only the first one, so the column that the planned input 
filters late rows by
   is either the key itself or one of those columns. A key that the analysis 
accepts is
   therefore accepted at execution too, and a batch can only accept more, which 
is the base
   branch behaviour. I also fixed the comments that said both read the same 
analyzed plan.
   
   <!-- sp2k-review8 reply 4577114376 -->
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -4237,6 +4237,40 @@ object SQLConf {
       .checkValue(v => Set(1, 2, 3, 4).contains(v), "Valid versions are 1, 2, 
3, and 4")
       .createWithDefault(2)
 
+  val STREAMING_JOIN_CHECKPOINT_WATERMARK_SEMANTICS_VERSION =
+    buildConf("spark.sql.streaming.join.checkpointWatermarkSemanticsVersion")
+      .internal()
+      .doc("Checkpoint generation for stream-stream join watermark semantics, 
persisted in " +
+        "the offset log. Older generations are accepted only when the query 
plan proves that " +
+        "its state and output watermark semantics are unchanged. The 
generation validates " +
+        "compatibility; it does not select a legacy execution path.")
+      .version("4.4.0")
+      .withBindingPolicy(ConfigBindingPolicy.NOT_APPLICABLE)
+      .intConf
+      .checkValue(v => v >= 0 && v <= 2, "Supported versions are 0 through 2")
+      .createWithDefault(2)
+
+  val STREAMING_JOIN_CHECK_FINALIZATION_ENABLED =
+    buildConf("spark.sql.streaming.join.checkFinalization.enabled")
+      .internal()
+      .doc("When true, a stream-stream left outer, right outer, full outer or 
left semi join " +
+        "fails analysis unless the watermarks and time constraints let Spark 
finalize the " +
+        "rows of each input whose unmatched rows it outputs or whose state it 
must bound for " +
+        "a semi join: such an input needs a bound derived from the other 
input's watermark. " +
+        "When false, Spark logs a warning instead and runs the query, as long 
as the join " +
+        "has a watermarked equality key or a range bound for a finalized 
input, which earlier " +
+        "versions required; other joins still fail analysis. Unmatched rows 
are " +
+        "still finalized only with that bound, so such a query keeps the 
input's state " +
+        "without bound, and an outer join never outputs the rows that the 
bound would " +
+        "finalize. Before Spark 4.4, a weaker check that ignored the direction 
of each " +
+        "watermark admitted some of these joins. The conf also controls the 
start-time check " +

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 together with the planned-key start check, so the conf again 
controls only the
   analysis check and the start-time check for aggregations after a join, which 
its doc and the
   migration guide already describe.
   
   <!-- sp2k-review8 reply 4577114381 -->
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -705,33 +715,138 @@ object UnsupportedOperationChecker extends Logging {
       plan = operator)
   }
 
-  private def checkForStreamStreamJoinWatermark(join: Join): Unit = {
-    val watermarkInJoinKeys = StreamingJoinHelper.isWatermarkInJoinKeys(join)
-
-    // Check if the nullable side has a watermark, and there's a range 
condition which
-    // implies a state value watermark on the first side.
-    val hasValidWatermarkRange = join.joinType match {
-      case LeftOuter | LeftSemi => StreamingJoinHelper.getStateValueWatermark(
-        join.left.outputSet, join.right.outputSet, join.condition, 
Some(1000000)).isDefined
-      case RightOuter => StreamingJoinHelper.getStateValueWatermark(
-        join.right.outputSet, join.left.outputSet, join.condition, 
Some(1000000)).isDefined
-      case FullOuter =>
-        Seq((join.left.outputSet, join.right.outputSet),
-          (join.right.outputSet, join.left.outputSet)).exists {
-          case (attributesToFindStateWatermarkFor, 
attributesWithEventWatermark) =>
-            
StreamingJoinHelper.getStateValueWatermark(attributesToFindStateWatermarkFor,
-              attributesWithEventWatermark, join.condition, 
Some(1000000)).isDefined
-        }
+  private def checkForStreamStreamJoinWatermark(
+      join: Join,
+      eventTimeCopies: EventTimeCopies): Unit = {
+    val keys = ExtractEquiJoinKeys.unapply(join)
+    val leftKeys = keys.map(_._2).getOrElse(Nil)
+    val rightKeys = keys.map(_._3).getOrElse(Nil)
+
+    // TODO(SPARK-61347): this accepts a range bound on an input without its 
own watermark,
+    //   which eviction does not finalize yet.
+    // TODO(SPARK-61348): this also accepts a range bound on a column that is 
not TIMESTAMP,
+    //   which eviction never finalizes.
+    // TODO(SPARK-61349): this also accepts a bound that uses only constants, 
which does not
+    //   follow the other input's watermark and so cannot finalize unmatched 
state.
+    def canEvictState(
+        stateInput: LogicalPlan,
+        otherInput: LogicalPlan,
+        otherKeys: Seq[Expression]): Boolean = {
+      val eventTime = 
otherInput.output.find(_.metadata.contains(EventTimeWatermark.delayKey))
+      StreamingJoinHelper.getStateKeyWatermarkOrdinal(
+        otherKeys, otherInput.output, eventTimeCopies).isDefined ||
+        StreamingJoinHelper.getStateValueWatermark(stateInput.outputSet,
+          AttributeSet(eventTime.toSeq), join.condition, 
Some(1000000)).isDefined
+    }
+
+    // The rule of Spark versions before 4.4: a watermarked equality key, or a 
range bound that the
+    // solver finds for a finalized input. Disabling the finalization check 
never goes below it.
+    def admittedBeforeFinalizationCheck: Boolean = {
+      def hasRangeBound(stateInput: LogicalPlan, otherInput: LogicalPlan): 
Boolean =
+        StreamingJoinHelper.getStateValueWatermark(stateInput.outputSet, 
otherInput.outputSet,
+          join.condition, Some(1000000)).isDefined
+      (leftKeys ++ rightKeys).exists {
+        case a: AttributeReference => 
a.metadata.contains(EventTimeWatermark.delayKey)
+        case _ => false
+      } || (join.joinType match {
+        case LeftOuter | LeftSemi => hasRangeBound(join.left, join.right)
+        case RightOuter => hasRangeBound(join.right, join.left)
+        case _ => hasRangeBound(join.left, join.right) || 
hasRangeBound(join.right, join.left)
+      })
+    }
+
+    val leftCanEvict = canEvictState(join.left, join.right, rightKeys)
+    val rightCanEvict = canEvictState(join.right, join.left, leftKeys)
+    val hasRequiredWatermarks = join.joinType match {
+      case LeftOuter | LeftSemi => leftCanEvict
+      case RightOuter => rightCanEvict
+      case FullOuter => leftCanEvict && rightCanEvict
       case _ =>
         throwError(
           s"Join type ${join.joinType} is not supported with streaming 
DataFrame/Dataset")(join)
     }
 
-    if (!watermarkInJoinKeys && !hasValidWatermarkRange) {
-      throwError(
+    if (!hasRequiredWatermarks) {
+      val requirement = join.joinType match {
+        case FullOuter => "watermarks on both inputs and time constraints in 
both directions"
+        case RightOuter => "a watermark on the left input and a time 
constraint"
+        case _ => "a watermark on the right input and a time constraint"
+      }
+      // The join holds back its output watermark for an input whose state is 
unbounded.
+      val downstreamRequirement = join.joinType match {
+        case LeftOuter => Some(("right", "left"))
+        case RightOuter => Some(("left", "right"))
+        case _ => None
+      }
+      // The error says that such an aggregation fails at start. The warning 
is logged only with
+      // the finalization check disabled, which lets the query start, so it 
never emits instead.
+      def downstreamNote(aggregationOutcome: String): String =

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: the error and the warning now add the note about a stateful operator 
after the join
   only when multiple stateful operators are allowed. Tests check that a 
legacy-mode left outer
   join has no such note in the error, or in the warning with the finalization 
check disabled.
   
   <!-- sp2k-review8 reply 4577114383 -->
   



##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinLegacyEventTimeKeySuite.scala:
##########
@@ -0,0 +1,332 @@
+/*
+ * 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.{AnalysisException, DataFrame, Row}
+import org.apache.spark.sql.catalyst.analysis.StreamingJoinHelper
+import org.apache.spark.sql.catalyst.plans.Inner
+import org.apache.spark.sql.catalyst.plans.logical.{Join, JoinHint, Union}
+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
+
+/**
+ * With spark.sql.streaming.statefulOperator.allowMultiple=false, an input 
filters late rows by
+ * its first watermarked column. An equality key on a later watermarked column 
bounds the other
+ * input's state only when the input builds it from that first column, as a 
copy or as a
+ * tumbling or sliding time window.
+ */
+class StreamingJoinLegacyEventTimeKeySuite extends StreamTest {
+  import testImplicits._
+
+  private val legacyMode = SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key -> 
"false"
+
+  /** Adds the key column `<side>w` to an input whose event time is `<side>t`. 
*/
+  private type KeyBuilder = (DataFrame, String) => DataFrame
+
+  private val tumbling: KeyBuilder =
+    (df, side) => df.withColumn(s"${side}w", window(col(s"${side}t"), "10 
seconds"))
+  private val sliding: KeyBuilder =
+    (df, side) => df.withColumn(s"${side}w", window(col(s"${side}t"), "10 
seconds", "5 seconds"))
+  private val copy: KeyBuilder = (df, side) => df.withColumn(s"${side}w", 
col(s"${side}t"))
+  private val copyThenWindow: KeyBuilder = (df, side) =>
+    df.withColumn(s"${side}c", col(s"${side}t"))
+      .withColumn(s"${side}w", window(col(s"${side}c"), "10 seconds"))
+  private val renamedWindow: KeyBuilder = (df, side) =>
+    df.withColumn(s"${side}x", window(col(s"${side}t"), "10 seconds"))
+      .filter(col(s"${side}k") >= 0)
+      .withColumnRenamed(s"${side}x", s"${side}w")
+  // A window over the event time less 20 seconds, in a column that keeps the 
event time's
+  // watermark metadata. Its end can be at or below the watermark while the 
event time is above.
+  private val shiftedWindow: KeyBuilder = (df, side) => {
+    val time = s"${side}t"
+    df.select(col("*"),
+        (col(time) - expr("INTERVAL 20 SECONDS")).as(s"${side}s", 
df.schema(time).metadata))
+      .withColumn(s"${side}w", window(col(s"${side}s"), "10 seconds"))
+  }
+  private val sessionWindow: KeyBuilder =
+    (df, side) => df.withColumn(s"${side}w", session_window(col(s"${side}t"), 
"10 seconds"))
+
+  private def eventTimeInput(memory: MemoryStream[(Int, Int)], side: String): 
DataFrame =
+    memory.toDF().toDF(s"${side}k", "time")
+      .select(col(s"${side}k"), timestamp_seconds($"time").as(s"${side}t"))
+      .withWatermark(s"${side}t", "1 second")
+
+  private def keyed(memory: MemoryStream[(Int, Int)], side: String, key: 
KeyBuilder): DataFrame =
+    key(eventTimeInput(memory, side), side)
+      .select(col(s"${side}k"), col(s"${side}t"), col(s"${side}w"))
+
+  /** The (key, event time) pairs that the shared rule accepts, by column 
name. */
+  private def eventTimeCopies(df: DataFrame): Set[(String, String)] = {
+    val plan = df.queryExecution.analyzed
+    val names = plan.flatMap(_.output).map(a => a.exprId -> a.name).toMap
+    StreamingJoinHelper.findEventTimeCopies(plan).pairs.map { case (key, 
eventTime) =>
+      (names(key), names(eventTime))
+    }
+  }
+
+  private def joinWithRight(left: DataFrame, key: KeyBuilder = tumbling): 
DataFrame =
+    left.join(keyed(MemoryStream[(Int, Int)], "r", key), expr("lk = rk AND lw 
= rw"))
+
+  Seq(
+    "tumbling window" -> tumbling,
+    "sliding window" -> sliding,
+    "copy" -> copy,
+    "window over a copy" -> copyThenWindow,
+    "renamed window after a filter" -> renamedWindow).foreach { case (name, 
key) =>
+    test(s"$name of the event time after it is accepted") {
+      val copies = eventTimeCopies(joinWithRight(keyed(MemoryStream[(Int, 
Int)], "l", key), key))
+      assert(copies.contains(("lw", "lt")))
+      assert(copies.contains(("rw", "rt")))
+    }
+  }
+
+  test("window over a shifted time is not accepted") {
+    val left = shiftedWindow(eventTimeInput(MemoryStream[(Int, Int)], "l"), 
"l")
+    val copies = eventTimeCopies(joinWithRight(left))
+    assert(!copies.contains(("lw", "lt")))
+    assert(!copies.contains(("ls", "lt")))
+    // The window is over ls itself, which late filtering does not use while 
lt comes first.
+    assert(copies.contains(("lw", "ls")))
+  }
+
+  test("session window is not accepted") {
+    val copies = eventTimeCopies(joinWithRight(keyed(MemoryStream[(Int, Int)], 
"l", sessionWindow)))
+    assert(!copies.exists(_._1 == "lw"))
+  }
+
+  test("window over another input's event time is not accepted") {
+    val a = MemoryStream[(Int, Int)]
+    val b = MemoryStream[(Int, Int)]
+    val left = eventTimeInput(a, "a").join(eventTimeInput(b, "b"), expr("ak = 
bk AND at = bt"))
+      .withColumn("lk", $"ak")
+      .withColumn("lw", window($"bt", "10 seconds"))
+    val copies = eventTimeCopies(joinWithRight(left))
+    // The left input filters late rows by at, but the window is over bt.
+    assert(!copies.contains(("lw", "at")))
+    assert(copies.contains(("lw", "bt")))
+  }
+
+  test("union is accepted only when every input builds the key from the same 
position") {
+    def union(first: KeyBuilder, second: KeyBuilder): DataFrame =
+      keyed(MemoryStream[(Int, Int)], "l", first)
+        .union(keyed(MemoryStream[(Int, Int)], "l", second))
+    assert(eventTimeCopies(joinWithRight(union(tumbling, 
sliding))).contains(("lw", "lt")))
+    assert(!eventTimeCopies(joinWithRight(union(tumbling, 
shiftedWindow))).contains(("lw", "lt")))
+    assert(!eventTimeCopies(joinWithRight(union(shiftedWindow, 
tumbling))).contains(("lw", "lt")))
+  }
+
+  test("a pair rejected by one join input is rejected for every join") {
+    // The second join's left input is a union whose first input is the first 
join's input, so
+    // both inputs output the same expression IDs, but only the first builds 
the window from lt.
+    val windowed = keyed(MemoryStream[(Int, Int)], "l", 
tumbling).queryExecution.analyzed
+    val shifted = keyed(MemoryStream[(Int, Int)], "l", 
shiftedWindow).queryExecution.analyzed
+    val right = keyed(MemoryStream[(Int, Int)], "r", 
tumbling).queryExecution.analyzed
+    val first = Join(windowed, right, Inner, None, JoinHint.NONE)
+    val second = Join(Union(Seq(windowed, shifted)), right, Inner, None, 
JoinHint.NONE)
+    val Seq(_, lt, lw) = windowed.output
+    val pair = (lw.exprId, lt.exprId)
+    assert(StreamingJoinHelper.findEventTimeCopies(first).pairs.contains(pair))
+    
assert(!StreamingJoinHelper.findEventTimeCopies(second).pairs.contains(pair))
+    assert(!StreamingJoinHelper.findEventTimeCopies(Union(Seq(first, 
second))).pairs
+      .contains(pair))
+  }
+
+  // Batches of left and right rows of (key, seconds), with 10-second windows. 
The watermark is
+  // 30 seconds in the third batch, so it finalizes the rows at 5 and 6 
seconds, whose windows end
+  // by 15 seconds, and keeps those at 31 and 40 seconds.
+  private def legacyJoin(
+      joinType: String,
+      key: KeyBuilder,
+      windowsPerRow: Int,
+      version: Int,
+      restart: Boolean): Unit = {
+    withSQLConf(legacyMode,
+        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 joined = keyed(leftInput, "l", key)
+        .join(keyed(rightInput, "r", key), expr("lk = rk AND lw = rw"), 
joinType)
+      val (result, matched, unmatchedLeft) = if (joinType == "left_semi") {
+        (joined.select($"lk", $"lt".cast("int")), Row(1, 5), Nil)
+      } else {
+        val unmatched = if (joinType == "left_outer" || joinType == 
"full_outer") {
+          Seq(Row(2, 6, null, null))
+        } else {
+          Nil
+        }
+        (joined.select($"lk", $"lt".cast("int"), $"rk", $"rt".cast("int")), 
Row(1, 5, 1, 5),
+          unmatched)
+      }
+      def times(rows: Seq[Row]): Seq[Row] = 
rows.flatMap(Seq.fill(windowsPerRow)(_))
+      withTempDir { checkpoint =>
+        val start = StartStream(checkpointLocation = 
checkpoint.getCanonicalPath)
+        val restartActions = if (restart) Seq(StopStream, start) else Nil
+        testStream(result)((Seq(
+          start,
+          MultiAddData(leftInput, (1, 5), (2, 6))(rightInput, (1, 5)),
+          CheckNewAnswer(times(Seq(matched)): _*),
+          MultiAddData(leftInput, (3, 31))(rightInput, (9, 31)),
+          CheckNewAnswer()) ++ restartActions ++ Seq(
+          AddData(rightInput, (9, 40)),
+          CheckNewAnswer(times(unmatchedLeft): _*),
+          // Only the rows at 31 and 40 seconds stay, as in Spark 4.3. Without 
the bound, all
+          // six rows would stay in state.
+          Execute { query =>
+            assert(query.lastProgress.stateOperators.head.numRowsTotal === 3 * 
windowsPerRow)
+          })): _*)
+      }
+    }
+  }
+
+  for {
+    (keyName, key, windowsPerRow) <- Seq(
+      ("tumbling window", tumbling, 1), ("sliding window", sliding, 2), 
("copy", copy, 1))
+    joinType <- Seq("inner", "left_outer", "right_outer", "full_outer", 
"left_semi")
+    version <- Seq(2, 3)
+  } {
+    test(s"legacy-mode $joinType join on a $keyName after the event time 
evicts by it, " +
+        s"V$version") {
+      legacyJoin(joinType, key, windowsPerRow, version, restart = false)
+    }
+  }
+
+  for {
+    joinType <- Seq("left_outer", "full_outer")
+    version <- Seq(2, 3)
+  } {
+    test(s"legacy-mode $joinType join on a window after the event time evicts 
after a " +
+        s"restart, V$version") {
+      legacyJoin(joinType, tumbling, 1, version, restart = true)
+    }
+  }
+
+  // The V4 state manager accepts one event-time column per input, as in Spark 
4.3, so these
+  // inputs keep failing there whichever key bounds them.
+  test("legacy-mode V4 join on an input with a window after the event time 
still fails") {
+    withSQLConf(legacyMode,
+        SQLConf.STREAMING_JOIN_STATE_FORMAT_VERSION.key -> "4",
+        SQLConf.STATE_STORE_PROVIDER_CLASS.key -> 
classOf[RocksDBStateStoreProvider].getName) {
+      val leftInput = MemoryStream[(Int, Int)]
+      val rightInput = MemoryStream[(Int, Int)]
+      val joined = keyed(leftInput, "l", tumbling)
+        .join(keyed(rightInput, "r", tumbling), expr("lk = rk AND lw = rw"))
+      testStream(joined)(
+        MultiAddData(leftInput, (1, 5))(rightInput, (1, 5)),
+        ExpectFailure[AnalysisException](assertFailure = error =>
+          assert(error.getMessage.contains("MULTIPLE_EVENT_TIME_COLUMNS"))))
+    }
+  }
+
+  for (version <- Seq(2, 3)) {
+    test(s"legacy-mode inner join on a window over a shifted time keeps rows 
that can still " +
+        s"match, V$version") {
+      withSQLConf(legacyMode,
+          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 joined = keyed(leftInput, "l", shiftedWindow)
+          .join(keyed(rightInput, "r", shiftedWindow), expr("lk = rk AND lw = 
rw"))
+          .select($"lk", $"lt".cast("int"), $"rk", $"rt".cast("int"))
+        testStream(joined)(
+          MultiAddData(leftInput, (1, 55))(rightInput, (9, 50)),
+          CheckNewAnswer(),
+          // The watermark is 49 seconds. The window of (1, 55) is [30, 40), 
so evicting by the
+          // window end would remove it here.
+          AddData(rightInput, (9, 51)),
+          CheckNewAnswer(),
+          // (1, 56) is above the watermark of 50 seconds and has the same 
window.
+          AddData(rightInput, (1, 56)),
+          CheckNewAnswer(Row(1, 55, 1, 56)))
+      }
+    }
+  }
+
+  private def assertLegacyWindowHint(left: DataFrame, right: DataFrame): Unit 
= {
+    withSQLConf(legacyMode) {
+      val error = intercept[AnalysisException] {
+        testStream(left.join(right, expr("lk = rk AND lw = rw"), 
"left_outer"))(
+          StartStream(), CheckNewAnswer())
+      }
+      assert(error.getMessage.contains("the right input filters late rows by 
its first " +
+        "watermarked column, rt, so its window key rw is a time constraint 
only if that input " +
+        "computes it as a tumbling or sliding window over rt itself"))
+    }
+  }
+
+  test("legacy-mode left outer join on a window over a shifted time fails 
analysis") {
+    assertLegacyWindowHint(keyed(MemoryStream[(Int, Int)], "l", tumbling),
+      keyed(MemoryStream[(Int, Int)], "r", shiftedWindow))
+  }
+
+  test("legacy-mode left outer join on a session window fails analysis") {
+    assertLegacyWindowHint(keyed(MemoryStream[(Int, Int)], "l", tumbling),
+      keyed(MemoryStream[(Int, Int)], "r", sessionWindow))
+  }
+
+  test("legacy-mode left outer join on a union of different windows fails 
analysis") {
+    val right = keyed(MemoryStream[(Int, Int)], "r", tumbling)
+      .union(keyed(MemoryStream[(Int, Int)], "r", shiftedWindow))
+    assertLegacyWindowHint(keyed(MemoryStream[(Int, Int)], "l", tumbling), 
right)
+  }
+
+  test("default-mode left outer join on a window after the event time still 
fails analysis") {
+    val error = intercept[AnalysisException] {
+      val joined = keyed(MemoryStream[(Int, Int)], "l", tumbling)
+        .join(keyed(MemoryStream[(Int, Int)], "r", tumbling), expr("lk = rk 
AND lw = rw"),
+          "left_outer")
+      testStream(joined)(StartStream(), CheckNewAnswer())
+    }
+    assert(error.getMessage.contains("allow unmatched state to be finalized"))
+    
assert(!error.getMessage.contains(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key))
+  }
+
+  test("legacy-mode join fails at start when the planned input filters late 
rows by " +

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.
   
   The planned-key check and its error are removed in 
[e03f9977b87](https://github.com/apache/spark/pull/60280/commits/e03f9977b8722bd5783107c6c4cb0ba933e10e52)
 (see the reply on
   IncrementalExecution), so there are no branches left to test. The case that 
test covered, a
   copy of the event time after a window over it, now fails analysis with the 
hint for right
   outer joins, and an inner join on it keeps the match that evicting by the 
key would drop.
   
   <!-- sp2k-review8 reply 4577114385 -->
   



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