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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -17,36 +17,500 @@
 
 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.{Expand, Join, LogicalPlan, 
Project, UnaryNode, 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
 
+/**
+ * In legacy mode (spark.sql.streaming.statefulOperator.allowMultiple=false), 
the watermarked
+ * equality keys that do not count as their input's event time. See
+ * [[StreamingJoinHelper.findLegacyEventTimeKeys]].
+ */
+case class LegacyEventTimeKeys(rejected: Set[ExprId]) {
+  /** Whether the key carries a watermark and is not rejected, so it bounds as 
in Spark 4.3. */
+  def isEventTimeKey(key: Expression): Boolean = key match {
+    case n: NamedExpression => n.metadata.contains(delayKey) && 
!rejected(n.exprId)
+    case _ => false
+  }
+}
+
 /**
  * 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],
+      legacyKeys: Option[LegacyEventTimeKeys] = None): Option[Int] = {
+    getEventTimeKeyOrdinal(keys, inputAttributes, legacyKeys).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, in legacy
+   * mode, a watermarked key that `legacyKeys` does not reject. Spark 4.3 used 
every watermarked
+   * key so; see [[findLegacyEventTimeKeys]].
+   */
+  def getEventTimeKeyOrdinal(
+      keys: Seq[Expression],
+      inputAttributes: Seq[Attribute],
+      legacyKeys: Option[LegacyEventTimeKeys] = None): 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(key => 
legacyKeys.exists(_.isEventTimeKey(key)))).find(_ >= 0)
+    }
+  }
+
+  /**
+   * In legacy mode 
(spark.sql.streaming.statefulOperator.allowMultiple=false), an input can keep
+   * several watermarked columns, such as its event time and a copy of it or a 
time window over
+   * it, and it filters late rows by the first of them. Spark 4.3 counted 
every watermarked
+   * equality key as the input's event time, which is right when the key is 
never below the
+   * column that filters late rows. Keep doing so, and reject only a key that 
`plan` shows some
+   * row can hold below a watermarked column before it, because the planned 
input filters late
+   * rows by one of those: the optimizer can prune the ones before it. 
Evicting by such a key
+   * would drop state that later rows still match. A key rejected by one 
stream-stream join input
+   * is rejected for every join, so the analysis check and execution, which 
read the result by
+   * expression ID on the analyzed and the planned join, decide the same.
+   */
+  def findLegacyEventTimeKeys(plan: LogicalPlan): LegacyEventTimeKeys = {
+    val rejected = 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
+      watermarked.indices.collect {
+        case i if watermarked.take(i).exists { eventTime =>
+          canBeBelow(input, watermarked(i), eventTime, SameValue, 
eventTimeIsWindow = false)
+        } => watermarked(i)
+      }
+    }
+    LegacyEventTimeKeys(rejected.toSet)
+  }
+
+  /** How the join input's key relates to the column that [[canBeBelow]] 
follows for it. */
+  private sealed trait KeyBound
+  /** The key is that column. */
+  private case object SameValue extends KeyBound
+  /** The key is a time window over that column, which ends at most a window 
after it. */
+  private case object WindowEnd extends KeyBound
+  /** The key is at or above that column, by an amount the walk does not know. 
*/
+  private case object AtOrAbove extends KeyBound
+  /** Some rows hold the key more than a microsecond below that column. */
+  private case object Below extends KeyBound
+
+  /**
+   * Whether `plan` shows that some row holds the join input's key below the 
bound of its column
+   * `eventTime`, which late filtering compares with the watermark: the column 
itself, or its end
+   * when `eventTimeIsWindow`. `bound` says how that key relates to the column 
`key` of `plan`.
+   * The walk follows both columns down by expression ID: through a projection 
or an expansion
+   * that passes them on, builds a time or session window from a single 
column, or shifts a
+   * timestamp by constant intervals; through any other node with one input 
that outputs both,
+   * as such a node keeps an expression ID only for an unchanged value; into 
the input of a join
+   * that outputs both; and into every input of a union, at the same 
positions. Where both reach
+   * the same column, a key below it, or equal to it while the late-filtered 
column is a window
+   * over it, can be below. A union input that does not watermark a column 
that the union, which
+   * takes its first input's metadata, watermarks builds it some other way. 
Everything else gives
+   * false, so such a key keeps the Spark 4.3 behaviour.
+   */
+  private def canBeBelow(
+      plan: LogicalPlan,
+      key: ExprId,
+      eventTime: ExprId,
+      bound: KeyBound,
+      eventTimeIsWindow: Boolean): Boolean = {
+    def outputsBoth(p: LogicalPlan): Boolean =
+      p.output.exists(_.exprId == key) && p.output.exists(_.exprId == 
eventTime)
+    if (key == eventTime) {
+      bound == Below || (eventTimeIsWindow && bound == SameValue)

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, and thanks for the bound in the other thread. I checked it and 
adopted it. Late
   filtering on a window of length D over t keeps a row only when the window 
ends after the
   watermark W, and the window ends at most D after t, so t, and a copy of it, 
is above W - D. When
   t survives pruning, the copy is above W itself. The new commit replaces the 
yes-or-no rule with
   a lag for each watermarked column: how far below the column that filters 
late rows it can be.
   A key or range column then bounds the other input's state at the watermark 
less that lag.
   
   Analysis takes the largest lag against every watermarked column before it, 
because pruning can
   leave any of them first. Execution reads the optimized plan that runs and 
takes the lag against
   the column that the planned input really filters late rows by. So for `[k, 
t, w = window(t), c
   = t]` joined on `c`, the join now passes analysis, evicts the other input at 
the watermark when
   the query reads `t`, and at the watermark less the window length when it 
does not. A sliding
   window gives its duration, and a session window with a constant gap gives 
the gap. A session
   window with a gap from a column has no bound, so that shape is still 
rejected. No start-time
   check is involved. The tests cover inner, left, right and full outer and 
left semi joins on state
   formats 2 and 3, once with `t` kept and once pruned, and check when the 
unmatched row comes out
   and how many rows stay in state.
   
   <!-- sp2k-review9 reply 4579272747 -->
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -705,33 +715,145 @@ 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,
+      legacyKeys: Option[LegacyEventTimeKeys]): 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))

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 
[634eb849aa4](https://github.com/apache/spark/pull/60280/commits/634eb849aa45f01a4799fd376645126dcfbd3ad4)
 without predicting the optimizer. With multiple stateful
   operators allowed, any watermarked column of the other input now counts for 
keys and range
   conditions. This holds for every plan: execution fails at start with
   `MULTIPLE_EVENT_TIME_COLUMNS` when a planned input keeps two distinct 
watermarked columns, so
   the one that remains filters late rows itself. A join on a window appended 
after a pruned event
   time therefore passes analysis and evicts at the window end, as on the base 
branch. If the query
   keeps both columns, it fails at start, as on the base branch, instead of at 
analysis.
   
   In legacy mode the same check uses the lags described in the reply on 
`StreamingJoinHelper`:
   analysis takes the worst case over the columns that pruning can leave first, 
and execution the
   lag against the planned late-filtered column. So a range condition on a 
later copy of the event
   time, such as `lt BETWEEN rc - INTERVAL 5 SECONDS AND rc + INTERVAL 5 
SECONDS`, is bounded
   again. The restart check from SPARK-61344 needs no change: it reads the 
planned attributes, so
   legacy inputs with several watermarked columns are still rejected at 
restart, and in the
   default mode the planned window is that input's own event time. Tests cover 
left outer, left
   semi and full outer joins on state formats 2 to 4, with and without a 
restart, and the range
   case in both modes.
   
   <!-- sp2k-review9 reply 4579272731 -->
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -17,36 +17,500 @@
 
 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.{Expand, Join, LogicalPlan, 
Project, UnaryNode, 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
 
+/**
+ * In legacy mode (spark.sql.streaming.statefulOperator.allowMultiple=false), 
the watermarked
+ * equality keys that do not count as their input's event time. See
+ * [[StreamingJoinHelper.findLegacyEventTimeKeys]].
+ */
+case class LegacyEventTimeKeys(rejected: Set[ExprId]) {
+  /** Whether the key carries a watermark and is not rejected, so it bounds as 
in Spark 4.3. */
+  def isEventTimeKey(key: Expression): Boolean = key match {
+    case n: NamedExpression => n.metadata.contains(delayKey) && 
!rejected(n.exprId)
+    case _ => false
+  }
+}
+
 /**
  * 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],
+      legacyKeys: Option[LegacyEventTimeKeys] = None): Option[Int] = {
+    getEventTimeKeyOrdinal(keys, inputAttributes, legacyKeys).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, in legacy
+   * mode, a watermarked key that `legacyKeys` does not reject. Spark 4.3 used 
every watermarked
+   * key so; see [[findLegacyEventTimeKeys]].
+   */
+  def getEventTimeKeyOrdinal(
+      keys: Seq[Expression],
+      inputAttributes: Seq[Attribute],
+      legacyKeys: Option[LegacyEventTimeKeys] = None): 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(key => 
legacyKeys.exists(_.isEventTimeKey(key)))).find(_ >= 0)
+    }
+  }
+
+  /**
+   * In legacy mode 
(spark.sql.streaming.statefulOperator.allowMultiple=false), an input can keep
+   * several watermarked columns, such as its event time and a copy of it or a 
time window over
+   * it, and it filters late rows by the first of them. Spark 4.3 counted 
every watermarked
+   * equality key as the input's event time, which is right when the key is 
never below the
+   * column that filters late rows. Keep doing so, and reject only a key that 
`plan` shows some
+   * row can hold below a watermarked column before it, because the planned 
input filters late
+   * rows by one of those: the optimizer can prune the ones before it. 
Evicting by such a key
+   * would drop state that later rows still match. A key rejected by one 
stream-stream join input
+   * is rejected for every join, so the analysis check and execution, which 
read the result by
+   * expression ID on the analyzed and the planned join, decide the same.
+   */
+  def findLegacyEventTimeKeys(plan: LogicalPlan): LegacyEventTimeKeys = {
+    val rejected = 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
+      watermarked.indices.collect {
+        case i if watermarked.take(i).exists { eventTime =>
+          canBeBelow(input, watermarked(i), eventTime, SameValue, 
eventTimeIsWindow = false)
+        } => watermarked(i)
+      }
+    }
+    LegacyEventTimeKeys(rejected.toSet)
+  }
+
+  /** How the join input's key relates to the column that [[canBeBelow]] 
follows for it. */
+  private sealed trait KeyBound
+  /** The key is that column. */
+  private case object SameValue extends KeyBound
+  /** The key is a time window over that column, which ends at most a window 
after it. */
+  private case object WindowEnd extends KeyBound
+  /** The key is at or above that column, by an amount the walk does not know. 
*/
+  private case object AtOrAbove extends KeyBound
+  /** Some rows hold the key more than a microsecond below that column. */
+  private case object Below extends KeyBound
+
+  /**
+   * Whether `plan` shows that some row holds the join input's key below the 
bound of its column
+   * `eventTime`, which late filtering compares with the watermark: the column 
itself, or its end
+   * when `eventTimeIsWindow`. `bound` says how that key relates to the column 
`key` of `plan`.
+   * The walk follows both columns down by expression ID: through a projection 
or an expansion
+   * that passes them on, builds a time or session window from a single 
column, or shifts a
+   * timestamp by constant intervals; through any other node with one input 
that outputs both,
+   * as such a node keeps an expression ID only for an unchanged value; into 
the input of a join
+   * that outputs both; and into every input of a union, at the same 
positions. Where both reach
+   * the same column, a key below it, or equal to it while the late-filtered 
column is a window
+   * over it, can be below. A union input that does not watermark a column 
that the union, which
+   * takes its first input's metadata, watermarks builds it some other way. 
Everything else gives
+   * false, so such a key keeps the Spark 4.3 behaviour.
+   */
+  private def canBeBelow(
+      plan: LogicalPlan,
+      key: ExprId,
+      eventTime: ExprId,
+      bound: KeyBound,
+      eventTimeIsWindow: Boolean): Boolean = {
+    def outputsBoth(p: LogicalPlan): Boolean =
+      p.output.exists(_.exprId == key) && p.output.exists(_.exprId == 
eventTime)
+    if (key == eventTime) {
+      bound == Below || (eventTimeIsWindow && bound == SameValue)
+    } else {
+      plan match {
+        case p: Project =>
+          def entry(id: ExprId): Option[NamedExpression] = 
p.projectList.find(_.exprId == id)
+          (entry(key).flatMap(keyStep(_, bound)),
+            entry(eventTime).flatMap(eventTimeStep(_, eventTimeIsWindow))) 
match {
+            case (Some((childKey, childBound)), Some((childEventTime, 
isWindow))) =>
+              canBeBelow(p.child, childKey, childEventTime, childBound, 
isWindow)
+            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.
+          def entries(id: ExprId): Seq[Expression] =
+            e.output.indexWhere(_.exprId == id) match {
+              case -1 => Nil
+              case index => e.projections.map(_(index))
+            }
+          def passedOn(entries: Seq[Expression]): Option[ExprId] = entries.map 
{
+            case a: Attribute => Some(a.exprId)
+            case _ => None
+          }.distinct match {
+            case Seq(id) => id
+            case _ => None
+          }
+          def windowSource(id: ExprId, entries: Seq[Expression]): 
Option[ExprId] =
+            if (e.output.exists(a => a.exprId == id && 
a.metadata.contains(TimeWindow.marker))) {
+              entries.map(singleReference).distinct match {
+                case Seq(source) => source.map(_.exprId)
+                case _ => None
+              }
+            } else {
+              None
+            }
+          val (keyEntries, eventTimeEntries) = (entries(key), 
entries(eventTime))
+          val childKey = passedOn(keyEntries).map(_ -> bound).orElse {
+            windowSource(key, keyEntries).filter(_ => bound == 
SameValue).map(_ -> WindowEnd)
+          }
+          val childEventTime = passedOn(eventTimeEntries).map(_ -> 
eventTimeIsWindow).orElse {
+            windowSource(eventTime, eventTimeEntries).filter(_ => 
!eventTimeIsWindow).map(_ -> true)
+          }
+          (childKey, childEventTime) match {
+            case (Some((k, b)), Some((t, isWindow))) => canBeBelow(e.child, k, 
t, b, isWindow)
+            case _ => false
+          }
+        case u: Union =>
+          val keyIndex = u.output.indexWhere(_.exprId == key)
+          val eventTimeIndex = u.output.indexWhere(_.exprId == eventTime)
+          def unwatermarked(child: LogicalPlan, index: Int): Boolean =
+            u.output(index).metadata.contains(delayKey) &&
+              !child.output(index).metadata.contains(delayKey)
+          keyIndex >= 0 && eventTimeIndex >= 0 && u.children.exists { child =>
+            unwatermarked(child, keyIndex) || unwatermarked(child, 
eventTimeIndex) ||
+              canBeBelow(child, child.output(keyIndex).exprId,
+                child.output(eventTimeIndex).exprId, bound, eventTimeIsWindow)
+          }
+        case j: Join =>
+          j.children.find(outputsBoth).exists(canBeBelow(_, key, eventTime, 
bound,
+            eventTimeIsWindow))
+        case u: UnaryNode if outputsBoth(u.child) =>
+          canBeBelow(u.child, key, eventTime, bound, eventTimeIsWindow)
+        case _ => false
+      }
+    }
+  }
+
+  /** The only attribute that `e` references, if there is one. */
+  private def singleReference(e: Expression): Option[Attribute] = 
e.references.toSeq match {
+    case Seq(a) => Some(a)
+    case _ => None
+  }
+
+  /**
+   * The column of the projection's child that [[canBeBelow]] follows for the 
key's projection
+   * entry `entry`, and how the key relates to it.
    */
-  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 keyStep(entry: NamedExpression, bound: KeyBound): 
Option[(ExprId, KeyBound)] =
+    entry match {
+      case a: Attribute => Some(a.exprId -> bound)
+      case Alias(a: Attribute, _) => Some(a.exprId -> bound)
+      case Alias(child, _) => singleReference(child).flatMap { source =>
+        // A window is a struct, so a key above it is the window itself.
+        if (entry.metadata.contains(TimeWindow.marker)) {
+          Some(source.exprId -> WindowEnd).filter(_ => bound == SameValue)
+        } else if (entry.metadata.contains(SessionWindow.marker)) {
+          // A session ends its gap after the column, which can be longer than 
a shift below.
+          Some(source.exprId -> AtOrAbove).filter(_ => bound == SameValue)
+        } else {
+          isForwardShift(child, source).flatMap {
+            case true => Some(bound).collect {
+              case SameValue | WindowEnd | AtOrAbove => source.exprId -> 
AtOrAbove
+            }
+            case false => Some(bound).collect {
+              case SameValue | WindowEnd | Below => source.exprId -> Below
+            }
+          }
         }
+      }
+      case _ => None
+    }
+
+  /**
+   * The column of the projection's child that [[canBeBelow]] follows for the 
late-filtered
+   * column's projection entry `entry`, and whether the late-filtered column 
is a window over it.
+   */
+  private def eventTimeStep(
+      entry: NamedExpression,
+      eventTimeIsWindow: Boolean): Option[(ExprId, Boolean)] = entry match {
+    case a: Attribute => Some(a.exprId -> eventTimeIsWindow)
+    case Alias(a: Attribute, _) => Some(a.exprId -> eventTimeIsWindow)
+    case Alias(child, _) if !eventTimeIsWindow && 
(entry.metadata.contains(TimeWindow.marker) ||
+        entry.metadata.contains(SessionWindow.marker)) =>
+      singleReference(child).map(_.exprId -> true)
+    case _ => None
+  }
+
+  /**
+   * Whether the timestamp `expr` is `source` shifted by constant intervals 
that never move a
+   * time backward (true), or that move the epoch back by more than a 
microsecond (false), so
+   * some rows hold it below `source`. None for any other expression.
+   */
+  private def isForwardShift(expr: Expression, source: Attribute): 
Option[Boolean] = {
+    if (expr.dataType != TimestampType || source.dataType != TimestampType) {
+      None
+    } else {
+      intervalShift(expr, source).flatMap {
+        case (_, true) => Some(true)
+        case _ =>
+          val atEpoch = try {
+            Option(expr.transform {
+              case a: Attribute if a.exprId == source.exprId => Literal(0L, 
TimestampType)
+            }.eval())
+          } catch {
+            case NonFatal(_) => None
+          }
+          atEpoch.collect { case micros: Long if micros < -1L => false }
+      }
+    }
+  }
+
+  /**
+   * Get the cutoff for the opposite input's equality key at `ordinal`, given 
this input's
+   * watermark. `keys` and `inputAttributes` belong to this input, whose 
future rows have an event
+   * time above the watermark. When the key is that event time, the equal key 
of any state row
+   * they can still match is above the watermark too. When the key is the 
event time shifted by
+   * exact intervals, solving `stateKey >= rightTime + INTERVAL 10 SECONDS` 
shifts the cutoff by
+   * that interval, less 1 ms as for range conditions. When the shift has 
whole days, months or
+   * years but never moves a time backward, the cutoff is the watermark 
itself. Returns None for
+   * any other key, including a shift with whole days, months or years that 
can move a time
+   * backward.
+   */
+  def getStateKeyWatermark(
+      keys: Seq[Expression],
+      inputAttributes: Seq[Attribute],
+      ordinal: Int,
+      eventWatermark: Option[Long],
+      legacyKeys: Option[LegacyEventTimeKeys] = None): Option[Long] = {
+    if (getEventTimeKeyOrdinal(keys, inputAttributes, 
legacyKeys).contains(ordinal)) {
+      eventWatermark
+    } else {
+      shiftOfKey(keys(ordinal), inputAttributes).flatMap {
+        case KeyShift(eventTime, true, _) =>
+          val stateKey = AttributeReference("stateKey", TimestampType)()
+          getStateValueWatermark(AttributeSet(Seq(stateKey)), 
AttributeSet(Seq(eventTime)),
+            Some(GreaterThanOrEqual(stateKey, 
withIntervalLiterals(keys(ordinal)))),
+            eventWatermark)
+        // The solver cannot count this shift, but it keeps the key of every 
future row at or
+        // above that row's event time, which is above the watermark.
+        case KeyShift(_, false, true) => eventWatermark
+        case _ => None
+      }
+    }
+  }
+
+  /**
+   * Get a bound on this input's event time for state rows whose equality key 
at `ordinal` is
+   * above `keyWatermark`. When the key is the event time, the bound is the 
key watermark. When
+   * the key is the event time shifted by exact intervals, solving
+   * `leftTime + INTERVAL 10 SECONDS >= keyWatermark` subtracts that constant, 
less 1 ms.
+   * Returns None for any other key, including any shift with whole days, 
months or years.
+   */
+  def getEventTimeWatermarkFromKey(
+      keys: Seq[Expression],
+      inputAttributes: Seq[Attribute],
+      ordinal: Int,
+      keyWatermark: Long): Option[Long] = {
+    if (getEventTimeKeyOrdinal(keys, inputAttributes).contains(ordinal)) {
+      Some(keyWatermark)
+    } else {
+      shiftOfKey(keys(ordinal), inputAttributes).filter(_.exact).flatMap { 
shift =>
+        val keyWithWatermark = AttributeReference("stateKey", TimestampType,
+          metadata = new MetadataBuilder().putLong(delayKey, 0L).build())()
+        getStateValueWatermark(AttributeSet(Seq(shift.eventTime)),
+          AttributeSet(Seq(keyWithWatermark)),
+          Some(GreaterThanOrEqual(withIntervalLiterals(keys(ordinal)), 
keyWithWatermark)),
+          Some(keyWatermark))
+      }
+    }
+  }
+
+  /**
+   * Whether the key is this input's event time shifted by constant intervals 
that never move a
+   * time backward. [[getStateKeyWatermark]] bounds the opposite state by such 
a key at the
+   * watermark plus the shift for an exact interval, and at the watermark 
itself otherwise, so it
+   * is never below the watermark.
+   */
+  def isForwardShiftOfEventTime(key: Expression, inputAttributes: 
Seq[Attribute]): Boolean =
+    shiftOfKey(key, inputAttributes).exists(_.forward)
+
+  /**
+   * A timestamp key computed from the input's event time by constant 
intervals. `exact` means
+   * the solver counts the shift exactly; `forward` means the shift never 
moves a time backward.
+   */
+  private case class KeyShift(eventTime: Attribute, exact: Boolean, forward: 
Boolean)
+
+  /** How a timestamp key shifts the input's event time, if the solver or its 
sign bounds it. */
+  private def shiftOfKey(key: Expression, inputAttributes: Seq[Attribute]): 
Option[KeyShift] =
+    inputAttributes.find(_.metadata.contains(delayKey)).filter(_ => 
key.dataType == TimestampType)
+      .flatMap { eventTime =>
+        intervalShift(key, eventTime).collect {
+          case (exact, forward) if exact || forward => KeyShift(eventTime, 
exact, forward)
+        }
+      }
+
+  /**
+   * If the expression is the event time plus or minus constant intervals, 
whether the shift is
+   * exact and whether it never moves a time backward. Other functions and 
casts from other types
+   * are not accepted: a truncation such as CAST(CAST(rightTime AS BIGINT) AS 
TIMESTAMP) can map a
+   * later event time below the watermark.
+   */
+  private def intervalShift(expr: Expression, eventTime: Attribute): 
Option[(Boolean, Boolean)] = {
+    // Spark adds whole days in the session time zone, where a day can be 23 
or 25 hours across a
+    // daylight saving change, and months vary in length, but the solver 
counts a day as 24 hours.
+    // So only intervals without whole days or months are exact, in every time 
zone.
+    def interval(e: Expression, negate: Boolean): Option[(Boolean, Boolean)] = 
{
+      def forward(parts: Long*): Boolean =
+        if (negate) parts.forall(_ <= 0) else parts.forall(_ >= 0)
+      // An interval that fails to evaluate gives no bound; the query reports 
the error at run time.
+      def value: Option[Any] = try Option(e.eval()) catch { case NonFatal(_) 
=> None }
+      if (!e.foldable) {
+        None
+      } else {
+        e.dataType match {
+          case _: DayTimeIntervalType =>
+            value.map { v =>
+              val micros = v.asInstanceOf[Long]
+              (-MICROS_PER_DAY < micros && micros < MICROS_PER_DAY, 
forward(micros))
+            }
+          case _: YearMonthIntervalType =>
+            value.map { v =>
+              val months = v.asInstanceOf[Int]
+              (months == 0, forward(months))
+            }
+          case CalendarIntervalType =>
+            value.map { v =>
+              val i = v.asInstanceOf[CalendarInterval]
+              (i.months == 0 && i.days == 0, forward(i.months, i.days, 
i.microseconds))
+            }
+          case _ => None
+        }
+      }
+    }
+    def combine(
+        a: Option[(Boolean, Boolean)],
+        b: Option[(Boolean, Boolean)]): Option[(Boolean, Boolean)] =
+      for ((exactA, forwardA) <- a; (exactB, forwardB) <- b)
+        yield (exactA && exactB, forwardA && forwardB)

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 as you suggested. The shift classification now adds up the 
smallest and largest
   displacement of every term instead of classifying each term on its own. 
Sub-day parts count at
   their value, a whole day counts 12 to 36 hours, wider than any daylight 
saving change, and a
   month counts 28 to 31 such days, so the session time zone is still not read. 
A key never moves
   a time backward when its smallest displacement is not negative. Exactness is 
unchanged, so the
   solver, the output watermark and the left semi cutoffs see the same shifts 
as before.
   
   So `lt = rt + INTERVAL 1 DAY - INTERVAL 1 HOUR` and `rt + INTERVAL 1 MONTH - 
INTERVAL 1 DAY`
   bound the other input's state at the watermark again, while
   `rt - INTERVAL 1 DAY + INTERVAL 1 HOUR` and `rt + INTERVAL 1 DAY - INTERVAL 
13 HOURS` still give
   no bound, and `rt + (INTERVAL 1 DAY - INTERVAL 1 HOUR)` keeps its exact 
23-hour cutoff. A left
   outer join on the first key passes analysis, keeps its match and outputs the 
unmatched row once
   the watermark passes it, in both modes and on state formats 2 to 4. As you 
noted, restarts of
   older checkpoints of such keys are now accepted, which matches how older 
versions evicted them.
   The migration guide and the join docs describe the rule.
   
   <!-- sp2k-review9 reply 4579272779 -->
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala:
##########
@@ -167,6 +170,26 @@ class IncrementalExecution(
   private val allowMultipleStatefulOperators: Boolean =
     
sparkSession.sessionState.conf.getConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE)
 
+  // The analysis check computes the same keys from the plan it checks. Both 
read the operators
+  // of the query, which every batch's analyzed plan keeps; a batch only puts 
each source's data
+  // in place of the source. The walk needs no state from analysis, such as 
tags.
+  private lazy val legacyKeys: Option[LegacyEventTimeKeys] =
+    if (allowMultipleStatefulOperators) {
+      None
+    } else {
+      Some(StreamingJoinHelper.findLegacyEventTimeKeys(analyzed))

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. Execution no longer matches keys between the analyzed and the 
planned plan. It now
   computes the lags from the optimized plan that runs, whose expression IDs 
the planned join uses,
   so a key that the optimizer renamed is walked under its new ID. Analysis 
keeps reading the
   analyzed plan with the same rule. In your example, `ls` is the event time 
less 20 seconds, so it
   bounds the right state at the watermark less 20 seconds, and the inner and 
left outer joins keep
   the match. The projections that build such columns sit above the input's 
watermark node, which
   the optimizer keeps in every batch, including one without data, so the 
result does not change
   from batch to batch. I also fixed the comments that said both readers decide 
the same.
   
   <!-- sp2k-review9 reply 4579272757 -->
   



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