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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -17,36 +17,659 @@
 
 package org.apache.spark.sql.catalyst.analysis
 
+import java.util.Locale
+
+import scala.util.Try
 import scala.util.control.NonFatal
 
 import org.apache.spark.internal.Logging
 import org.apache.spark.internal.LogKeys._
+import org.apache.spark.sql.catalyst.InternalRow
 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
 
+/**
+ * How far below a column that can filter its stream-stream join input's late 
rows one of the
+ * input's watermarked columns can be, for an equality key or a range 
condition on it: at most
+ * `micros` where the plan relates the two columns; by an amount that the plan 
does not bound when
+ * `unbounded`; and by an amount that it does not show when `unrelated`, 
because it does not relate
+ * the two. A window column is compared by its end, as eviction and late 
filtering compare it.
+ */
+case class EventTimeLag(micros: Long, unrelated: Boolean, unbounded: Boolean) {
+  def max(other: EventTimeLag): EventTimeLag = EventTimeLag(math.max(micros, 
other.micros),
+    unrelated || other.unrelated, unbounded || other.unbounded)
+
+  /**
+   * The cutoff for the other input's equality key when this input's watermark 
is `watermark`.
+   * A key that the plan does not relate keeps the Spark 4.3 cutoff.
+   */
+  def keyWatermark(watermark: Long): Option[Long] =
+    if (unbounded) None else Some(watermark - EventTimeLag.ceilMillis(micros))
+
+  /**
+   * The watermark to substitute for the column in a range condition. Spark 
4.3 substituted the
+   * watermark for every watermarked column; this does so only where the plan 
bounds the lag.
+   */
+  def rangeWatermark(watermark: Long): Option[Long] =
+    if (unbounded || unrelated) None else Some(watermark - 
EventTimeLag.ceilMillis(micros))
+}
+
+object EventTimeLag {
+  val zero: EventTimeLag = EventTimeLag(0L, unrelated = false, unbounded = 
false)
+  val unrelated: EventTimeLag = EventTimeLag(0L, unrelated = true, unbounded = 
false)
+  val unbounded: EventTimeLag = EventTimeLag(0L, unrelated = false, unbounded 
= true)
+
+  private def ceilMillis(micros: Long): Long =
+    micros / MICROS_PER_MILLIS + (if (micros % MICROS_PER_MILLIS == 0) 0 else 
1)
+}
+
+/**
+ * The [[EventTimeLag]] of the watermarked columns of stream-stream join 
inputs, by expression ID;
+ * see [[StreamingJoinHelper.findEventTimeLags]]. A column missing from `lags` 
has lag zero, so
+ * `EventTimeLags(Map.empty)` gives every watermarked column lag zero. That is 
right when multiple
+ * stateful operators are allowed: execution then fails at start for a planned 
input with two
+ * distinct watermarked columns, so the only one left filters late rows itself.
+ */
+case class EventTimeLags(lags: Map[ExprId, EventTimeLag]) {
+  /**
+   * The lag of `column` in a join input with output `inputAttributes`, if it 
carries a watermark.
+   * The input's first watermarked column filters its late rows itself.
+   */
+  def lagOf(column: NamedExpression, inputAttributes: Seq[Attribute]): 
Option[EventTimeLag] =
+    if (!column.metadata.contains(delayKey)) {
+      None
+    } else if (inputAttributes.find(_.metadata.contains(delayKey))
+        .exists(_.exprId == column.exprId)) {
+      Some(EventTimeLag.zero)
+    } else {
+      Some(lags.getOrElse(column.exprId, EventTimeLag.zero))
+    }
+}
+
+object EventTimeLags {
+  val none: EventTimeLags = EventTimeLags(Map.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. Without `lags`, only the input's 
first watermarked
+   * column counts as its event time; with them, every watermarked column that 
they bound does.
+   */
+  def getStateKeyWatermarkOrdinal(
+      keys: Seq[Expression],
+      inputAttributes: Seq[Attribute],
+      lags: Option[EventTimeLags] = None): Option[Int] = {
+    getEventTimeKeyOrdinal(keys, inputAttributes, lags).orElse {
+      keys.indices.find(getStateKeyWatermark(keys, inputAttributes, _, 
Some(0L), lags).isDefined)
+    }
+  }
+
+  /**
+   * Find the equality key that is this input's first watermarked column, or 
else, with `lags`,
+   * the watermarked key with the smallest lag that bounds it; see 
[[findEventTimeLags]].
+   */
+  def getEventTimeKeyOrdinal(
+      keys: Seq[Expression],
+      inputAttributes: Seq[Attribute],
+      lags: Option[EventTimeLags] = 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 =>
+      Some(keys.indexWhere(_.semanticEquals(eventTime))).filter(_ >= 0).orElse 
{
+        lags.flatMap { l =>
+          keys.indices.flatMap { i =>
+            keyLag(keys(i), inputAttributes, l).filterNot(_.unbounded).map(i 
-> _.micros)
+          }.sortBy(_._2).headOption.map(_._1)
+        }
+      }
+    }
+  }
+
+  /** The lag of a key that is a watermarked column of the input. */
+  private def keyLag(
+      key: Expression,
+      inputAttributes: Seq[Attribute],
+      lags: EventTimeLags): Option[EventTimeLag] = key match {
+    case n: NamedExpression => lags.lagOf(n, inputAttributes)
+    case _ => None
+  }
+
+  /**
+   * The lag of every watermarked column of each stream-stream join input in 
`plan`, combined
+   * over the inputs by [[EventTimeLag.max]]. This is for
+   * spark.sql.streaming.statefulOperator.allowMultiple=false, where an input 
can keep several
+   * watermarked columns, such as its event time and a copy of it or a time 
window over it, and
+   * filters late rows by the first of them. When `planned`, `plan` is the 
optimized plan that runs,
+   * so each input filters late rows by its first watermarked column, and a 
column's lag is taken
+   * against that one. Otherwise the optimizer can prune any watermarked 
column before a column, so
+   * its lag is the largest against all of them. Spark 4.3 bounded state by 
every watermarked
+   * column at the watermark. A lag lowers that cutoff; see [[EventTimeLag]].
+   */
+  def findEventTimeLags(plan: LogicalPlan, planned: Boolean): EventTimeLags = {
+    val lags = 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.map { i =>
+        val lateFiltered = if (planned) watermarked.take(1) else 
watermarked.take(i)
+        watermarked(i) -> lateFiltered.filter(_ != watermarked(i)).map { 
eventTime =>
+          lagBelow(input, watermarked(i), eventTime, Some(0L), Some(0L))
+        }.foldLeft(EventTimeLag.zero)(_ max _)
+      }
+    }
+    EventTimeLags(lags.groupMapReduce(_._1)(_._2)(_ max _))
+  }
+
+  /** How a column relates to the column of a node's child that [[lagBelow]] 
follows for it. */
+  private case class Step(column: ExprId, offset: Option[Long])
+
+  /**
+   * How far `key` of `plan` can be below its column `eventTime`, which late 
filtering compares
+   * with the watermark. Both are compared by their bounds: a time, or a 
window's end. `keyLow` is
+   * the smallest that the join input's key is above `key`, and 
`eventTimeHigh` the largest that the
+   * join input's late-filtered column is above `eventTime`; None means 
without bound. 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, for 
the key, 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. 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. Where both reach the same column, the lag is 
the difference of the
+   * two offsets. Everything else leaves the columns unrelated.
+   */
+  private def lagBelow(
+      plan: LogicalPlan,
+      key: ExprId,
+      eventTime: ExprId,
+      keyLow: Option[Long],
+      eventTimeHigh: Option[Long]): EventTimeLag = {
+    def outputsBoth(p: LogicalPlan): Boolean =
+      p.output.exists(_.exprId == key) && p.output.exists(_.exprId == 
eventTime)
+    def follow(child: LogicalPlan, keyStep: Option[Step], eventTimeStep: 
Option[Step]) =
+      (keyStep, eventTimeStep) match {
+        case (Some(k), Some(t)) => lagBelow(child, k.column, t.column,
+          addOffsets(keyLow, k.offset), addOffsets(eventTimeHigh, t.offset))
+        case _ => EventTimeLag.unrelated
+      }
+    if (key == eventTime) {
+      (keyLow, eventTimeHigh) match {
+        case (Some(low), Some(high)) => Try(Math.subtractExact(high, 
low)).toOption match {
+          case Some(lag) => EventTimeLag(math.max(0L, lag), unrelated = false, 
unbounded = false)
+          case None => EventTimeLag.unbounded
+        }
+        case _ => EventTimeLag.unbounded
+      }
+    } else {
+      plan match {
+        case p: Project =>
+          def entry(id: ExprId): Option[NamedExpression] = 
p.projectList.find(_.exprId == id)
+          follow(p.child, entry(key).flatMap(keyStep), 
entry(eventTime).flatMap(eventTimeStep))
+        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 step(id: ExprId, window: (Seq[Expression], Attribute) => 
Option[Long]) = {
+            val entries = e.output.indexWhere(_.exprId == id) match {
+              case -1 => Nil
+              case index => e.projections.map(_(index))
+            }
+            entries.map {
+              case a: Attribute => Some(a.exprId)
+              case _ => None
+            }.distinct match {
+              case Seq(Some(passedOn)) => Some(Step(passedOn, Some(0L)))
+              case _ if e.output.exists(a => a.exprId == id &&
+                  a.metadata.contains(TimeWindow.marker)) =>
+                entries.map(timeWindowSource).distinct match {
+                  case Seq(Some(source)) => Some(Step(source.exprId, 
window(entries, source)))
+                  case _ => None
+                }
+              case _ => None
+            }
+          }
+          // A window ends after its time column, and at most its length after 
it.
+          follow(e.child, step(key, (_, _) => Some(0L)), step(eventTime, 
(entries, source) =>
+            entries.map(timeWindowLength(_, source)).reduceOption((a, b) =>
+              for (x <- a; y <- b) yield math.max(x, y)).flatten))
+        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)
+          if (keyIndex < 0 || eventTimeIndex < 0) {
+            EventTimeLag.unrelated
+          } else {
+            u.children.map { child =>
+              if (unwatermarked(child, keyIndex) || unwatermarked(child, 
eventTimeIndex)) {
+                EventTimeLag.unbounded
+              } else {
+                lagBelow(child, child.output(keyIndex).exprId,
+                  child.output(eventTimeIndex).exprId, keyLow, eventTimeHigh)
+              }
+            }.reduce(_ max _)
+          }
+        case j: Join =>
+          j.children.find(outputsBoth).map(lagBelow(_, key, eventTime, keyLow, 
eventTimeHigh))
+            .getOrElse(EventTimeLag.unrelated)

Review Comment:
   Thanks, the equality case keeps its bound again. The range-tied case is 
still a regression, so I don't think it can wait for a follow-up. In legacy 
mode, take AB = A.join(B, ak = bk AND bt BETWEEN at AND at + INTERVAL 10 
MINUTES) followed by AB.join(C, ak = ck AND ct BETWEEN bt AND bt + INTERVAL 1 
HOUR, "right_outer"). Every AB row that passes late filtering on at has bt >= 
at, so Spark 4.3's bound on C, which substitutes the watermark for bt, is 
exact, and the query runs correctly there. With bt left unrelated, the same 
query fails analysis after an upgrade, and its inner form keeps every C row for 
the life of the query. The walk can read a range conjunct of the earlier join 
that bounds one column from below by the other: bt >= at - INTERVAL 1 HOUR 
would give bt a lag of one hour, and the condition above gives it lag zero.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4587582096","thread_id":"inline:4587582096","verdict_sha256":"ed2f650739e69e1eecefff6e87901ea7159cff0fde92bd3a90563887642cc71c"}
 -->



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -17,36 +17,720 @@
 
 package org.apache.spark.sql.catalyst.analysis
 
+import java.util.Locale
+
+import scala.util.Try
 import scala.util.control.NonFatal
 
 import org.apache.spark.internal.Logging
 import org.apache.spark.internal.LogKeys._
+import org.apache.spark.sql.catalyst.InternalRow
 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.{InnerLike, LeftOuter, RightOuter}
+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
 
+/**
+ * How far below a column that can filter its stream-stream join input's late 
rows one of the
+ * input's watermarked columns can be, for an equality key or a range 
condition on it: at most
+ * `micros` where the plan relates the two columns; by an amount that the plan 
does not bound when
+ * `unbounded`; and by an amount that it does not show when `unrelated`, 
because it does not relate
+ * the two. A window column is compared by its end, as eviction and late 
filtering compare it.
+ */
+case class EventTimeLag(micros: Long, unrelated: Boolean, unbounded: Boolean) {
+  def max(other: EventTimeLag): EventTimeLag = EventTimeLag(math.max(micros, 
other.micros),
+    unrelated || other.unrelated, unbounded || other.unbounded)
+
+  /**
+   * The cutoff for the other input's equality key when this input's watermark 
is `watermark`.
+   * A key that the plan does not relate keeps the Spark 4.3 cutoff.
+   */
+  def keyWatermark(watermark: Long): Option[Long] =
+    if (unbounded) None else Some(watermark - EventTimeLag.ceilMillis(micros))
+
+  /**
+   * The watermark to substitute for the column in a range condition. Spark 
4.3 substituted the
+   * watermark for every watermarked column; this does so only where the plan 
bounds the lag.
+   */
+  def rangeWatermark(watermark: Long): Option[Long] =
+    if (unbounded || unrelated) None else Some(watermark - 
EventTimeLag.ceilMillis(micros))
+}
+
+object EventTimeLag {
+  val zero: EventTimeLag = EventTimeLag(0L, unrelated = false, unbounded = 
false)
+  val unrelated: EventTimeLag = EventTimeLag(0L, unrelated = true, unbounded = 
false)
+  val unbounded: EventTimeLag = EventTimeLag(0L, unrelated = false, unbounded 
= true)
+
+  private def ceilMillis(micros: Long): Long =
+    micros / MICROS_PER_MILLIS + (if (micros % MICROS_PER_MILLIS == 0) 0 else 
1)
+}
+
+/**
+ * The [[EventTimeLag]] of the watermarked columns of stream-stream join 
inputs, by expression ID;
+ * see [[StreamingJoinHelper.findEventTimeLags]]. A column missing from `lags` 
has lag zero, so
+ * `EventTimeLags(Map.empty)` gives every watermarked column lag zero. That is 
right when multiple
+ * stateful operators are allowed: execution then fails at start for a planned 
input with two
+ * distinct watermarked columns, so the only one left filters late rows itself.
+ */
+case class EventTimeLags(lags: Map[ExprId, EventTimeLag]) {
+  /**
+   * The lag of `column` in a join input with output `inputAttributes`, if it 
carries a watermark.
+   * The input's first watermarked column filters its late rows itself.
+   */
+  def lagOf(column: NamedExpression, inputAttributes: Seq[Attribute]): 
Option[EventTimeLag] =
+    if (!column.metadata.contains(delayKey)) {
+      None
+    } else if (inputAttributes.find(_.metadata.contains(delayKey))
+        .exists(_.exprId == column.exprId)) {
+      Some(EventTimeLag.zero)
+    } else {
+      Some(lags.getOrElse(column.exprId, EventTimeLag.zero))
+    }
+}
+
+object EventTimeLags {
+  val none: EventTimeLags = EventTimeLags(Map.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. Without `lags`, only the input's 
first watermarked
+   * column counts as its event time; with them, every watermarked column that 
they bound does.
    */
-  def isWatermarkInJoinKeys(plan: LogicalPlan): Boolean = {
-    plan match {
-      case ExtractEquiJoinKeys(_, leftKeys, rightKeys, _, _, _, _, _) =>
-        (leftKeys ++ rightKeys).exists {
-          case a: AttributeReference => 
a.metadata.contains(EventTimeWatermark.delayKey)
-          case _ => false
+  def getStateKeyWatermarkOrdinal(
+      keys: Seq[Expression],
+      inputAttributes: Seq[Attribute],
+      lags: Option[EventTimeLags] = None): Option[Int] = {
+    getEventTimeKeyOrdinal(keys, inputAttributes, lags).orElse {
+      keys.indices.find(getStateKeyWatermark(keys, inputAttributes, _, 
Some(0L), lags).isDefined)
+    }
+  }
+
+  /**
+   * Find the equality key that is this input's first watermarked column, or 
else, with `lags`,
+   * the watermarked key with the smallest lag that bounds it; see 
[[findEventTimeLags]].
+   */
+  def getEventTimeKeyOrdinal(
+      keys: Seq[Expression],
+      inputAttributes: Seq[Attribute],
+      lags: Option[EventTimeLags] = 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 =>
+      Some(keys.indexWhere(_.semanticEquals(eventTime))).filter(_ >= 0).orElse 
{
+        lags.flatMap { l =>
+          keys.indices.flatMap { i =>
+            keyLag(keys(i), inputAttributes, l).filterNot(_.unbounded).map(i 
-> _.micros)
+          }.sortBy(_._2).headOption.map(_._1)
         }
+      }
+    }
+  }
+
+  /** The lag of a key that is a watermarked column of the input. */
+  private def keyLag(
+      key: Expression,
+      inputAttributes: Seq[Attribute],
+      lags: EventTimeLags): Option[EventTimeLag] = key match {
+    case n: NamedExpression => lags.lagOf(n, inputAttributes)
+    case _ => None
+  }
+
+  /**
+   * The lag of every watermarked column of each stream-stream join input in 
`plan`, combined
+   * over the inputs by [[EventTimeLag.max]]. This is for
+   * spark.sql.streaming.statefulOperator.allowMultiple=false, where an input 
can keep several
+   * watermarked columns, such as its event time and a copy of it or a time 
window over it, and
+   * filters late rows by the first of them. When `planned`, `plan` is the 
optimized plan that runs,
+   * so each input filters late rows by its first watermarked column, and a 
column's lag is taken
+   * against that one. Otherwise the optimizer can prune any watermarked 
column before a column, so
+   * its lag is the largest against all of them. Spark 4.3 bounded state by 
every watermarked
+   * column at the watermark. A lag lowers that cutoff; see [[EventTimeLag]].
+   */
+  def findEventTimeLags(plan: LogicalPlan, planned: Boolean): EventTimeLags = {
+    val lags = 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.map { i =>
+        val lateFiltered = if (planned) watermarked.take(1) else 
watermarked.take(i)
+        watermarked(i) -> lateFiltered.filter(_ != watermarked(i)).map { 
eventTime =>
+          lagBelow(input, watermarked(i), eventTime, Some(0L), Some(0L))
+        }.foldLeft(EventTimeLag.zero)(_ max _)
+      }
+    }
+    EventTimeLags(lags.groupMapReduce(_._1)(_._2)(_ max _))
+  }
+
+  /** How a column relates to the column of a node's child that [[lagBelow]] 
follows for it. */
+  private case class Step(column: ExprId, offset: Option[Long])
+
+  /**
+   * How far `key` of `plan` can be below its column `eventTime`, which late 
filtering compares
+   * with the watermark. Both are compared by their bounds: a time, or a 
window's end. `keyLow` is
+   * the smallest that the join input's key is above `key`, and 
`eventTimeHigh` the largest that the
+   * join input's late-filtered column is above `eventTime`; None means 
without bound. 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, for 
the key, 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, or into both inputs of one that outputs each from a 
different input and equates
+   * them through its condition (see [[lagThroughJoinCondition]]); and into 
every input of a union,
+   * at the same positions. 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, so 
the lag is
+   * unbounded. Where both reach the same column, the lag is the difference of 
the two offsets.
+   * Everything else leaves the columns unrelated.
+   */
+  private def lagBelow(
+      plan: LogicalPlan,
+      key: ExprId,
+      eventTime: ExprId,
+      keyLow: Option[Long],
+      eventTimeHigh: Option[Long]): EventTimeLag = {
+    def outputsBoth(p: LogicalPlan): Boolean =
+      p.output.exists(_.exprId == key) && p.output.exists(_.exprId == 
eventTime)
+    def follow(child: LogicalPlan, keyStep: Option[Step], eventTimeStep: 
Option[Step]) =
+      (keyStep, eventTimeStep) match {
+        case (Some(k), Some(t)) => lagBelow(child, k.column, t.column,
+          addOffsets(keyLow, k.offset), addOffsets(eventTimeHigh, t.offset))
+        case _ => EventTimeLag.unrelated
+      }
+    if (key == eventTime) {
+      (keyLow, eventTimeHigh) match {
+        case (Some(low), Some(high)) => Try(Math.subtractExact(high, 
low)).toOption match {
+          case Some(lag) => EventTimeLag(math.max(0L, lag), unrelated = false, 
unbounded = false)
+          case None => EventTimeLag.unbounded
+        }
+        case _ => EventTimeLag.unbounded
+      }
+    } else {
+      plan match {
+        case p: Project =>
+          def entry(id: ExprId): Option[NamedExpression] = 
p.projectList.find(_.exprId == id)
+          follow(p.child, entry(key).flatMap(keyStep), 
entry(eventTime).flatMap(eventTimeStep))
+        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 step(id: ExprId, window: (Seq[Expression], Attribute) => 
Option[Long]) = {
+            val entries = e.output.indexWhere(_.exprId == id) match {
+              case -1 => Nil
+              case index => e.projections.map(_(index))
+            }
+            entries.map {
+              case a: Attribute => Some(a.exprId)
+              case _ => None
+            }.distinct match {
+              case Seq(Some(passedOn)) => Some(Step(passedOn, Some(0L)))
+              case _ if e.output.exists(a => a.exprId == id &&
+                  a.metadata.contains(TimeWindow.marker)) =>
+                entries.map(timeWindowSource).distinct match {
+                  case Seq(Some(source)) => Some(Step(source.exprId, 
window(entries, source)))
+                  case _ => None
+                }
+              case _ => None
+            }
+          }
+          // A window ends after its time column, and at most its length after 
it.
+          follow(e.child, step(key, (_, _) => Some(0L)), step(eventTime, 
(entries, source) =>
+            entries.map(timeWindowLength(_, source)).reduceOption((a, b) =>
+              for (x <- a; y <- b) yield math.max(x, y)).flatten))
+        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)
+          if (keyIndex < 0 || eventTimeIndex < 0) {
+            EventTimeLag.unrelated
+          } else {
+            u.children.map { child =>
+              if (unwatermarked(child, keyIndex) || unwatermarked(child, 
eventTimeIndex)) {
+                EventTimeLag.unbounded
+              } else {
+                lagBelow(child, child.output(keyIndex).exprId,
+                  child.output(eventTimeIndex).exprId, keyLow, eventTimeHigh)
+              }
+            }.reduce(_ max _)
+          }
+        case j: Join =>
+          j.children.find(outputsBoth).map(lagBelow(_, key, eventTime, keyLow, 
eventTimeHigh))
+            .getOrElse(lagThroughJoinCondition(j, key, eventTime, keyLow, 
eventTimeHigh))
+        case u: UnaryNode if outputsBoth(u.child) =>
+          lagBelow(u.child, key, eventTime, keyLow, eventTimeHigh)
+        case _ => EventTimeLag.unrelated
+      }
+    }
+  }
+
+  /**
+   * The lag of `key` below `eventTime` of [[lagBelow]] where `join` outputs 
them from different
+   * inputs, through an equality `x = y` in its condition between a 
watermarked column x of the
+   * key's input and a watermarked column y of the event time's input: the key 
is at most its lag
+   * below x, which equals y, which is at most its lag below the event time, 
so the lags add up.
+   * That holds on every row that the join outputs with a non-NULL key: all 
rows of an inner join
+   * satisfy its condition, and so do those of a left or right outer join that 
pads the key's
+   * input, whose other rows carry a NULL key that no condition matches. The 
smallest bounded lag
+   * over such equalities wins. Other conjuncts, such as a range or a shifted 
equality, and other
+   * join types leave the columns unrelated.
+   */
+  private def lagThroughJoinCondition(
+      join: Join,
+      key: ExprId,
+      eventTime: ExprId,
+      keyLow: Option[Long],
+      eventTimeHigh: Option[Long]): EventTimeLag = {
+    def watermarked(p: LogicalPlan): Set[ExprId] =
+      p.output.filter(_.metadata.contains(delayKey)).map(_.exprId).toSet
+    def outputs(p: LogicalPlan, id: ExprId): Boolean = 
p.output.exists(_.exprId == id)
+    val inputs = if (outputs(join.left, key) && outputs(join.right, 
eventTime)) {
+      Some((join.left, join.right))
+    } else if (outputs(join.right, key) && outputs(join.left, eventTime)) {
+      Some((join.right, join.left))
+    } else {
+      None
+    }
+    val lags = inputs.filter { case (keyInput, _) =>
+      join.joinType match {
+        case _: InnerLike => true
+        case LeftOuter => keyInput eq join.right
+        case RightOuter => keyInput eq join.left
+        case _ => false
+      }
+    }.toSeq.flatMap { case (keyInput, eventTimeInput) =>
+      val keyColumns = watermarked(keyInput)
+      val eventTimeColumns = watermarked(eventTimeInput)
+      join.condition.toSeq.flatMap(splitConjunctivePredicates).flatMap {
+        case EqualTo(a: Attribute, b: Attribute) => Seq(a.exprId -> b.exprId, 
b.exprId -> a.exprId)
+        case _ => Nil
+      }.filter { case (x, y) => keyColumns.contains(x) && 
eventTimeColumns.contains(y) }
+        .map { case (x, y) =>
+          val below = lagBelow(keyInput, key, x, keyLow, Some(0L))
+          val above = lagBelow(eventTimeInput, y, eventTime, Some(0L), 
eventTimeHigh)
+          if (below.unrelated || above.unrelated) {
+            EventTimeLag.unrelated
+          } else {
+            Try(Math.addExact(below.micros, above.micros)).toOption
+              .filter(_ => !below.unbounded && !above.unbounded)
+              .map(EventTimeLag(_, unrelated = false, unbounded = false))
+              .getOrElse(EventTimeLag.unbounded)
+          }
+        }
+    }
+    lags.filter(lag => !lag.unrelated && 
!lag.unbounded).sortBy(_.micros).headOption
+      .getOrElse(EventTimeLag.unrelated)

Review Comment:
   **Non-blocking (P2):** When every watermarked equality in the earlier join's 
condition gives an unbounded lag, this falls back to `EventTimeLag.unrelated`, 
and `keyWatermark` gives an unrelated key the full watermark, while a column of 
the join input with the same unbounded lag gets no cutoff.
   
   Reading the code, with `B = B1.union(B2)`, where `B2` builds `bc` 
independently of `bt` and watermarks neither column, take `AB = A.join(B, ak = 
bk AND at = bc)` and then `AB.join(C, bt = ct)`. The Union case gives `bt` an 
unbounded lag relative to `bc`, so this returns unrelated, and `C`'s state is 
evicted at `ct <= watermark`. AB rows from `B2` have `at = bc` above the 
watermark but a `bt` that can be below it, so they miss their matches: the 
failure that the PR removes when the unbounded column belongs to the join input 
itself.
   
   **Recommended change:** Make the join step of the legacy-mode lag walk read 
every conjunct of the earlier join's condition that compares a watermarked 
column x of the key's input with a watermarked column y of the event time's 
input, range comparisons as well as equalities, and take from each the lower 
bound it gives x in terms of y (x >= y - d gives d, an equality gives 0), using 
the range solver's arithmetic for constant interval shifts. Add that bound to 
the lag of the key below x and the lag of y below the late-filtered column, as 
the equality case does now. Keep the smallest bounded lag over all ties, return 
unbounded when the conjuncts tie the columns but no tie gives a bounded lag, 
and return unrelated only when no conjunct ties a watermarked column of each 
input. Add chained-join tests for both shapes, change the lag test that expects 
the range conjunct at <= bt to leave the columns unrelated, which then gives 
lag zero, and update the scaladoc of lagThroughJoinCondition an
 d the legacy-mode note of the migration guide, which name only equalities.
   
   **Why this works:** Every row that an inner join outputs, and every row with 
a non-NULL key that an outer join padding the key's input outputs, satisfies 
the conjunct, so x >= y - d holds on it; with the key at most its lag below x 
and y at most its lag below the late-filtered column, the key is at most the 
sum below that column, which is the amount keyWatermark and rangeWatermark 
subtract. Returning unbounded for ties without a bound gives such a key no 
cutoff, as the walk already does for the join input's own unbounded columns.
   
   **Scope:** Extend the legacy-mode lag walk's join step to range ties and 
keep its unbounded results, with chained-join tests.
   
   **Compatibility:** Equality ties with a bounded lag and columns that come 
from the same input of the earlier join keep their current lags.
   
   **Risks:** Legacy-mode chained joins whose only ties give no bounded lag, an 
equality with an unbounded lag or range conjuncts that bound the tied column 
only from above, lose the Spark 4.3 key cutoff: their outer forms fail analysis 
by default and still run with 
spark.sql.streaming.join.checkFinalization.enabled=false, since earlier 
versions admitted them through a watermarked key, and their inner forms keep 
that state; this is the cost of keeping their matches. Range-tied chained joins 
regain eviction, so a mistake in the lower-bound arithmetic would drop matches; 
the tests cover forward and backward ties.
   
   **Constraints:** Keep the join-type filter, so only inner joins and outer 
joins that pad the key's input relate the columns. Do not read the session time 
zone; whole-day and month terms keep the PR's counting rule. Read a BETWEEN 
conjunct, which the analyzed plan keeps and the optimized plan rewrites into 
two comparisons, as those two comparisons, so admission and execution find the 
same ties.
   
   **Exclusions:**
   - Key-only and full outer earlier joins, which still leave the columns 
unrelated.
   
   **Success:** In legacy mode, AB = A.join(B, ak = bk AND bt BETWEEN at AND at 
+ INTERVAL 10 MINUTES) followed by AB.join(C, ak = ck AND ct BETWEEN bt AND bt 
+ INTERVAL 1 HOUR, "right_outer") passes analysis, evicts C's state below the 
watermark and outputs C's unmatched rows once the watermark passes them. With 
the earlier tie bt >= at - INTERVAL 1 HOUR, C's state is bounded at the 
watermark less one hour and no match is dropped. A chained join whose only tie 
has an unbounded lag gives the dependent state no key cutoff, so its inner form 
keeps every match.
   
   **Verification:**
   - **Regression:** A legacy-mode right outer chained join whose earlier join 
ties bt to at only by bt BETWEEN at AND at + INTERVAL 10 MINUTES passes 
analysis, evicts C's state and outputs C's unmatched row once the watermark 
passes it, on every supported state format.
   - **Regression:** A legacy-mode chained inner join whose earlier join ties 
the columns by bt >= at - INTERVAL 1 HOUR keeps the match of a C row with an AB 
row whose bt is up to one hour below at, and evicts C's state below the 
watermark less one hour.
   - **Regression:** A legacy-mode chained inner join whose only equality tie 
runs through a union input that does not watermark the tied column keeps the 
match of a C row with an AB row whose key is below the watermark while its 
late-filtered column is above it.
   - **Compatibility:** Chained joins after a key-only or a full outer earlier 
join, and chained joins tied by an equality of two watermarked columns, keep 
their current analysis outcome and eviction.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -17,36 +17,720 @@
 
 package org.apache.spark.sql.catalyst.analysis
 
+import java.util.Locale
+
+import scala.util.Try
 import scala.util.control.NonFatal
 
 import org.apache.spark.internal.Logging
 import org.apache.spark.internal.LogKeys._
+import org.apache.spark.sql.catalyst.InternalRow
 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.{InnerLike, LeftOuter, RightOuter}
+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
 
+/**
+ * How far below a column that can filter its stream-stream join input's late 
rows one of the
+ * input's watermarked columns can be, for an equality key or a range 
condition on it: at most
+ * `micros` where the plan relates the two columns; by an amount that the plan 
does not bound when
+ * `unbounded`; and by an amount that it does not show when `unrelated`, 
because it does not relate
+ * the two. A window column is compared by its end, as eviction and late 
filtering compare it.
+ */
+case class EventTimeLag(micros: Long, unrelated: Boolean, unbounded: Boolean) {
+  def max(other: EventTimeLag): EventTimeLag = EventTimeLag(math.max(micros, 
other.micros),
+    unrelated || other.unrelated, unbounded || other.unbounded)
+
+  /**
+   * The cutoff for the other input's equality key when this input's watermark 
is `watermark`.
+   * A key that the plan does not relate keeps the Spark 4.3 cutoff.
+   */
+  def keyWatermark(watermark: Long): Option[Long] =
+    if (unbounded) None else Some(watermark - EventTimeLag.ceilMillis(micros))
+
+  /**
+   * The watermark to substitute for the column in a range condition. Spark 
4.3 substituted the
+   * watermark for every watermarked column; this does so only where the plan 
bounds the lag.
+   */
+  def rangeWatermark(watermark: Long): Option[Long] =
+    if (unbounded || unrelated) None else Some(watermark - 
EventTimeLag.ceilMillis(micros))
+}
+
+object EventTimeLag {
+  val zero: EventTimeLag = EventTimeLag(0L, unrelated = false, unbounded = 
false)
+  val unrelated: EventTimeLag = EventTimeLag(0L, unrelated = true, unbounded = 
false)
+  val unbounded: EventTimeLag = EventTimeLag(0L, unrelated = false, unbounded 
= true)
+
+  private def ceilMillis(micros: Long): Long =
+    micros / MICROS_PER_MILLIS + (if (micros % MICROS_PER_MILLIS == 0) 0 else 
1)
+}
+
+/**
+ * The [[EventTimeLag]] of the watermarked columns of stream-stream join 
inputs, by expression ID;
+ * see [[StreamingJoinHelper.findEventTimeLags]]. A column missing from `lags` 
has lag zero, so
+ * `EventTimeLags(Map.empty)` gives every watermarked column lag zero. That is 
right when multiple
+ * stateful operators are allowed: execution then fails at start for a planned 
input with two
+ * distinct watermarked columns, so the only one left filters late rows itself.
+ */
+case class EventTimeLags(lags: Map[ExprId, EventTimeLag]) {
+  /**
+   * The lag of `column` in a join input with output `inputAttributes`, if it 
carries a watermark.
+   * The input's first watermarked column filters its late rows itself.
+   */
+  def lagOf(column: NamedExpression, inputAttributes: Seq[Attribute]): 
Option[EventTimeLag] =
+    if (!column.metadata.contains(delayKey)) {
+      None
+    } else if (inputAttributes.find(_.metadata.contains(delayKey))
+        .exists(_.exprId == column.exprId)) {
+      Some(EventTimeLag.zero)
+    } else {
+      Some(lags.getOrElse(column.exprId, EventTimeLag.zero))
+    }
+}
+
+object EventTimeLags {
+  val none: EventTimeLags = EventTimeLags(Map.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. Without `lags`, only the input's 
first watermarked
+   * column counts as its event time; with them, every watermarked column that 
they bound does.
    */
-  def isWatermarkInJoinKeys(plan: LogicalPlan): Boolean = {
-    plan match {
-      case ExtractEquiJoinKeys(_, leftKeys, rightKeys, _, _, _, _, _) =>
-        (leftKeys ++ rightKeys).exists {
-          case a: AttributeReference => 
a.metadata.contains(EventTimeWatermark.delayKey)
-          case _ => false
+  def getStateKeyWatermarkOrdinal(
+      keys: Seq[Expression],
+      inputAttributes: Seq[Attribute],
+      lags: Option[EventTimeLags] = None): Option[Int] = {
+    getEventTimeKeyOrdinal(keys, inputAttributes, lags).orElse {
+      keys.indices.find(getStateKeyWatermark(keys, inputAttributes, _, 
Some(0L), lags).isDefined)
+    }
+  }
+
+  /**
+   * Find the equality key that is this input's first watermarked column, or 
else, with `lags`,
+   * the watermarked key with the smallest lag that bounds it; see 
[[findEventTimeLags]].
+   */
+  def getEventTimeKeyOrdinal(
+      keys: Seq[Expression],
+      inputAttributes: Seq[Attribute],
+      lags: Option[EventTimeLags] = 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 =>
+      Some(keys.indexWhere(_.semanticEquals(eventTime))).filter(_ >= 0).orElse 
{
+        lags.flatMap { l =>
+          keys.indices.flatMap { i =>
+            keyLag(keys(i), inputAttributes, l).filterNot(_.unbounded).map(i 
-> _.micros)

Review Comment:
   **Blocking (P1):** In legacy mode, this ranking keeps keys whose lag is 
unrelated and sorts them by `micros`, which is 0 for `EventTimeLag.unrelated`, 
so an unrelated key always beats a key with a known positive lag, and 
`keyWatermark` then gives it the full watermark.
   
   Reading the code, take `R = A.join(B, ak = bk)`, where `A` carries `ax = at 
- INTERVAL 20 SECONDS` with `at`'s watermark metadata, joined with `L` on `lk = 
ak AND lx = ax AND lu = bt` while the query keeps `at`. The key-only join 
leaves `bt` unrelated to `at`, and `ax` gets a 20-second lag, so the ranking 
picks `bt` and evicts `L`'s state at `lu <= watermark`. A new A row with `at` 
above the watermark can still join an old B row whose `bt` is below it, and 
that R row finds its left match already evicted: an inner join drops the match, 
and a left outer join has already emitted the left row padded with nulls. The 
base branch evicted by the first watermarked key, `ax`, at the watermark and 
lost matches only within its 20-second shift; ranked first, `ax` would get the 
exact cutoff, the watermark less 20 seconds.
   
   **Verification:**
   - **Regression:** In legacy mode, an inner and a left outer join on lk = ak 
AND lx = ax AND lu = bt, whose right input is a key-only join of A and B that 
keeps at, where ax is at shifted back 20 seconds and bt is B's event time, keep 
the match of a right row whose bt is at or below the watermark while its at is 
above it.
   - **Behavior:** For join keys with one bounded and one unrelated lag, the 
chosen key ordinal is the bounded key's, whatever the order of the keys.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -705,33 +715,150 @@ 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,
+      eventTimeLags: EventTimeLags): 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 = {
+      // Any watermarked column of the other input can bound state: each 
planned input keeps one
+      // distinct watermarked column when multiple stateful operators are 
allowed, or execution
+      // fails at start, and in legacy mode its lag lowers the cutoff.
+      StreamingJoinHelper.getStateKeyWatermarkOrdinal(
+        otherKeys, otherInput.output, Some(eventTimeLags)).isDefined ||
+        
StreamingJoinHelper.getStateValueWatermarkForLags(stateInput.outputSet, 
otherInput.output,
+          join.condition, Some(1000000), Some(eventTimeLags)).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)

Review Comment:
   **Nit (P3):** Every left outer and left semi test that disables the 
finalization check has a watermarked equality key, which admits the join before 
this arm runs, and the tests that reach a range arm cover only full outer and 
right outer joins. Swapping this arm's inputs or returning false from it leaves 
every suite green, while a legacy-mode left outer join bounded only by a range 
condition on a right column with an unbounded lag, which earlier versions 
admitted, would then fail with the conf set to false, although the conf 
promises to run it with a warning.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60280#discussion_r4537719935).
   
   **Verification:**
   - **Regression:** A legacy-mode left outer join and a left semi join bounded 
only by lt >= rc on a right column with an unbounded lag fail analysis by 
default with an error that names the conf, and pass analysis with the warning 
when the finalization check is disabled.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala:
##########
@@ -167,6 +171,29 @@ class IncrementalExecution(
   private val allowMultipleStatefulOperators: Boolean =
     
sparkSession.sessionState.conf.getConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE)
 
+  // The lags of the planned join inputs, against the columns that they filter 
late rows by. They
+  // read the optimized plan, whose expression IDs the planned joins use. The 
analysis check reads
+  // the analyzed plan with the same rule, against every column that pruning 
can leave first, so
+  // it bounds a column here whenever it bounds one there. The projections 
that build the later
+  // watermarked columns stay in every batch's optimized plan: they sit above 
the input's
+  // watermark node, which the optimizer keeps even for a batch without data.
+  private lazy val eventTimeLags: Option[EventTimeLags] =
+    if (allowMultipleStatefulOperators) {
+      None
+    } else {
+      Some(StreamingJoinHelper.findEventTimeLags(optimizedPlan, planned = 
true))

Review Comment:
   **Non-blocking (P2):** These lags are recomputed from each batch's optimized 
plan, and that plan changes when a union input without a watermark node has no 
data: `MicroBatchExecution` replaces its source with an empty `LocalRelation`, 
and `PropagateEmptyRelation` removes the input from the union, so the Union 
case that gives the column an unbounded lag no longer runs.
   
   Reading the code, with `R = R1.union(R2)`, where `R2` does not watermark the 
copy `c` of `t`, and `L` inner-joined with `R` on `lk = rk AND lc = rc`, the 
left state has no key cutoff in a batch where `R2`'s source has data and is 
evicted at `lc <= watermark` in a batch where it has none. A later `R2` row 
with `t` above the watermark and `c` below it then finds its match evicted, and 
the inner join drops it: the failure that the union rule prevents in batches 
where every input has data.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60280#discussion_r4579272757).
   
   **Recommended change:** Record, from each batch's analyzed plan, which still 
has every union input, the expression IDs at each union position that some 
input leaves unwatermarked while the union's output is watermarked, meaning the 
union's output attribute and every input's attribute there, and have the walk 
over the optimized plan return unbounded for a column that reaches one of them, 
so removing that input does not shorten the lag. Commits 470c0cc6b63 and 
e03f9977b87 had execution read the analyzed plan, and 634eb849aa4 replaced that 
with the optimized plan so that keys the optimizer renames keep their bound; 
the repair keeps the walk on the optimized plan and takes only these union 
positions from the analyzed plan. Correct the comment on eventTimeLags that 
says the result does not change between batches, and add a legacy-mode join 
test over such a union.
   
   **Why this works:** The record holds every expression ID that a removed 
union input can leave behind. When a later input has no data, 
PropagateEmptyRelation returns the remaining inputs under the union's own 
output IDs, which are the first input's; when the first input is removed, it 
re-aliases another input to those IDs, and RemoveRedundantAliases can drop that 
alias so that the walk reaches that input's own attribute. The record holds all 
of these IDs, so the column's lag stays unbounded in every batch, as in a batch 
in which the input has data.
   
   **Scope:** Keep the Union case's unbounded result in batches in which an 
unwatermarked union input has no data.
   
   **Compatibility:** Lags of columns that no unwatermarked union input feeds 
keep their optimized-plan values.
   
   **Risks:** A column that the record marks gets no key cutoff in any batch, 
so a legacy-mode inner join over such a union keeps that state; its outer form 
already fails analysis, which sees the same unbounded lag. An input attribute 
at a marked position that also reaches another join by a different path is 
marked there too, which only withholds a cutoff.
   
   **Constraints:** Keep the optimized plan's expression IDs for every other 
lag, so keys that the optimizer renames keep their bound. Leave the analysis 
check unchanged; it already sees every union input.
   
   **Success:** In legacy mode, an inner join keyed on a column that one union 
input does not watermark keeps the match of a later row from that input after a 
batch in which that input had no data. The lags that execution computes for 
such a query are the same in batches with and without data for the 
unwatermarked input.
   
   **Verification:**
   - **Regression:** A legacy-mode inner join on a key built by a union whose 
second input has no watermark keeps the match of a row from that input with an 
earlier row of the other side after a batch in which that input had no data.
   - **Behavior:** The execution lags of a legacy-mode query over such a union 
are equal in a batch in which every union input has data and in one in which 
the unwatermarked input has none.
   - **Compatibility:** A key that the optimizer renames behind a repartition 
keeps its bound at the watermark less its lag.



##########
common/utils/src/main/resources/error/error-conditions.json:
##########
@@ -8165,6 +8165,41 @@
     ],
     "sqlState" : "55019"
   },
+  "STREAMING_JOIN_CHECKPOINT_INCOMPATIBLE" : {
+    "message" : [
+      "Cannot reuse the checkpoint for the stream-stream join with condition 
<joinCondition>. Watermarked columns: left [<leftWatermarkColumns>], right 
[<rightWatermarkColumns>].",
+      "This Spark version changes how watermarks determine which rows can 
still match. Spark cannot verify that rows saved by the previous version can be 
reused safely for this join. Start the query with a new checkpoint and replay 
the required input, accounting for previously written results to avoid 
duplicates and correct any missing or incorrect output."
+    ],
+    "sqlState" : "0A000"
+  },
+  "STREAMING_JOIN_UNBOUNDED_DOWNSTREAM_EVENT_TIME" : {
+    "message" : [
+      "The append-mode aggregation after a stream-stream join uses the event 
time <eventTime> of the join's <side> input, but the join has no bound on that 
event time for the state of that input, so it holds back its output watermark 
and the aggregation would never emit results."
+    ],
+    "subClass" : {
+      "TIME_CONSTRAINT" : {
+        "message" : [
+          "Add a time constraint that limits how late a matching <otherSide> 
row can arrive, aggregate the event time of an input whose state the join can 
bound. A bound on the event time comes from an equality key that shifts the 
other input's event time by an exact interval (under one day, or timestampadd 
in hours, minutes or seconds), or from a range condition used in place of a 
shifted equality. To run the query anyway, set <config> to false."

Review Comment:
   **Nit (P3):** Without the update-mode remedy, this sentence joins its two 
remaining remedies with a comma alone, so every query with a stream-stream 
outer join that gets this error reads a run-on instruction instead of two 
alternatives.
   
   ```suggestion
             "Add a time constraint that limits how late a matching <otherSide> 
row can arrive, or aggregate the event time of an input whose state the join 
can bound. A bound on the event time comes from an equality key that shifts the 
other input's event time by an exact interval (under one day, or timestampadd 
in hours, minutes or seconds), or from a range condition used in place of a 
shifted equality. To run the query anyway, set <config> to false."
   ```
   
   The `WATERMARK_AND_TIME_CONSTRAINT` message needs the same "or".
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60280#discussion_r4587582060).
   
   **Verification:**
   - **Inspection:** The two sub-conditions without the update output mode join 
their two remedies with "or", and the two sub-conditions that offer the update 
output mode are unchanged.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -17,36 +17,720 @@
 
 package org.apache.spark.sql.catalyst.analysis
 
+import java.util.Locale
+
+import scala.util.Try
 import scala.util.control.NonFatal
 
 import org.apache.spark.internal.Logging
 import org.apache.spark.internal.LogKeys._
+import org.apache.spark.sql.catalyst.InternalRow
 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.{InnerLike, LeftOuter, RightOuter}
+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
 
+/**
+ * How far below a column that can filter its stream-stream join input's late 
rows one of the
+ * input's watermarked columns can be, for an equality key or a range 
condition on it: at most
+ * `micros` where the plan relates the two columns; by an amount that the plan 
does not bound when
+ * `unbounded`; and by an amount that it does not show when `unrelated`, 
because it does not relate
+ * the two. A window column is compared by its end, as eviction and late 
filtering compare it.
+ */
+case class EventTimeLag(micros: Long, unrelated: Boolean, unbounded: Boolean) {
+  def max(other: EventTimeLag): EventTimeLag = EventTimeLag(math.max(micros, 
other.micros),
+    unrelated || other.unrelated, unbounded || other.unbounded)
+
+  /**
+   * The cutoff for the other input's equality key when this input's watermark 
is `watermark`.
+   * A key that the plan does not relate keeps the Spark 4.3 cutoff.
+   */
+  def keyWatermark(watermark: Long): Option[Long] =
+    if (unbounded) None else Some(watermark - EventTimeLag.ceilMillis(micros))
+
+  /**
+   * The watermark to substitute for the column in a range condition. Spark 
4.3 substituted the
+   * watermark for every watermarked column; this does so only where the plan 
bounds the lag.
+   */
+  def rangeWatermark(watermark: Long): Option[Long] =
+    if (unbounded || unrelated) None else Some(watermark - 
EventTimeLag.ceilMillis(micros))
+}
+
+object EventTimeLag {
+  val zero: EventTimeLag = EventTimeLag(0L, unrelated = false, unbounded = 
false)
+  val unrelated: EventTimeLag = EventTimeLag(0L, unrelated = true, unbounded = 
false)
+  val unbounded: EventTimeLag = EventTimeLag(0L, unrelated = false, unbounded 
= true)
+
+  private def ceilMillis(micros: Long): Long =
+    micros / MICROS_PER_MILLIS + (if (micros % MICROS_PER_MILLIS == 0) 0 else 
1)

Review Comment:
   **Nit (P3):** Every lag the suites build is a whole number of seconds, so 
the rounding branch of `ceilMillis` never runs in a test. Replacing it with 
plain division keeps every suite green, while a legacy-mode key on a copy of 
the event time shifted back by 500 microseconds would then get the watermark 
itself as its cutoff and evict a state row that a later row just above the 
watermark still matches.
   
   **Verification:**
   - **Regression:** At a watermark of 10,000 ms, keyWatermark and 
rangeWatermark give 9,999 ms for a lag of 500 microseconds, 9,998 ms for 1,500 
microseconds and 9,999 ms for exactly 1,000 microseconds.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala:
##########
@@ -721,14 +945,74 @@ 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

Review Comment:
   No, I don't know one, and a query with one could not run: an event-time 
timeout needs a watermarked column in the operator's input both at analysis and 
when the operator runs. The analysis check rejects flatMapGroupsWithState and 
applyInPandasWithState with an event-time timeout when the child has no 
watermarked column, and the physical operators' shared base requires the 
watermark expressions for that timeout, which it builds from the planned 
child's output. So every query that runs keeps such a column in the planned 
input, the general rule already counts these operators, and the two cases are 
redundant. Your new restart test covers the behavior, and removing the two 
cases or keeping them as documentation would both be fine.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4587582160","thread_id":"inline:4587582160","verdict_sha256":"ed2f650739e69e1eecefff6e87901ea7159cff0fde92bd3a90563887642cc71c"}
 -->



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