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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -17,36 +17,722 @@
 
 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 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

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 
[ab59957f358](https://github.com/apache/spark/pull/60280/commits/ab59957f3582d270164fd563b24f31603ff5e54c)
 on #60280. The legacy-mode lag walk now relates two columns through any 
conjunct
   of the earlier join that bounds one of them from below by the other plus 
constant intervals, not
   only through an equality. In your example `ct BETWEEN it AND it + INTERVAL 1 
HOUR` gives `ct` lag
   zero against `it`, so `vt >= ct` bounds `v` at the watermark, and `vt <= it 
+ INTERVAL 1 HOUR`
   bounds the left input as before. The right outer form passes analysis again 
and emits unmatched
   conversions, and the inner form evicts `v`. A constant whose whole days, 
months or years can move
   a time backward gives no bound, as for keys. Tests: chained right outer and 
inner joins whose
   earlier inner or left outer join ties the columns only by a BETWEEN, on 
state formats 2 and 3,
   plus lag tests for each comparison form.
   
   <!-- sp2k-review11 reply 4599498343 -->
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -17,36 +17,722 @@
 
 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 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:
   > [!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 
[ab59957f358](https://github.com/apache/spark/pull/60280/commits/ab59957f3582d270164fd563b24f31603ff5e54c)
 on #60280. An earlier-join tie whose lag has no bound now gives the key no 
bound,
   instead of leaving it unrelated, so the other input's state is not evicted 
at the watermark. Your
   shape, a day-shifted copy of `bt` keyed after `at = bt`, reaches the same 
step as the day-shifted
   tie that the new chained-join test covers; that test keeps the match of a C 
row a day below the
   watermark, and its right outer form now fails analysis.
   
   <!-- sp2k-review11 reply 4599498353 -->
   



##########
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:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM: Claude Sonnet 5.5 
(`claude-sonnet-5-5`, 1M context), running as an SP2K agent on behalf of 
@HeartSaVioR.
   
   Fixed in 
[ab59957f358](https://github.com/apache/spark/pull/60280/commits/ab59957f3582d270164fd563b24f31603ff5e54c)
 on #60280. The `TIME_CONSTRAINT` and `WATERMARK_AND_TIME_CONSTRAINT` messages 
now join their two remedies with "or", so they read as alternatives, as the 
`_OR_UPDATE_MODE` variants do.
   
   <!-- sp2k-review11 reply 4599498385 -->
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -17,36 +17,722 @@
 
 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:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM: Claude Sonnet 5.5 
(`claude-sonnet-5-5`, 1M context), running as an SP2K agent on behalf of 
@HeartSaVioR.
   
   Added in 
[ab59957f358](https://github.com/apache/spark/pull/60280/commits/ab59957f3582d270164fd563b24f31603ff5e54c)
 on #60280. `StreamingJoinHelperSuite` checks `keyWatermark` and 
`rangeWatermark` for lags with a sub-millisecond part: 500 microseconds lowers 
the cutoff by 1 ms, 1,500 microseconds by 2 ms, and a whole millisecond by 
exactly that. Replacing `ceilMillis` with `micros / 1000` makes it fail, which 
I checked.
   
   <!-- sp2k-review11 reply 4599498465 -->
   



##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinPlanRobustBoundSuite.scala:
##########
@@ -0,0 +1,438 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.streaming
+
+import java.sql.Timestamp
+
+import org.apache.spark.sql.{AnalysisException, Column, DataFrame, Row}
+import org.apache.spark.sql.execution.streaming.runtime.MemoryStream
+import org.apache.spark.sql.execution.streaming.state.RocksDBStateStoreProvider
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Stream-stream joins whose bound must hold whatever column pruning leaves in 
the planned
+ * inputs: keys and range conditions on a watermarked column that follows the 
input's event time,
+ * and keys that shift the event time by several intervals.
+ */
+class StreamingJoinPlanRobustBoundSuite extends StreamTest {
+  import testImplicits._
+
+  private val legacyMode = SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key -> 
"false"
+  private val defaultMode = SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key -> 
"true"
+
+  /** An input of (key, seconds) with the event time `<side>t` and a watermark 
delay of 1 s. */
+  private def eventTimeInput(memory: MemoryStream[(Int, Int)], side: String): 
DataFrame =
+    memory.toDF().toDF(s"${side}k", "time")
+      .select(col(s"${side}k"), timestamp_seconds($"time").as(s"${side}t"))
+      .withWatermark(s"${side}t", "1 second")
+
+  /** Adds `<side>w`, a 10-second window over the event time. */
+  private def windowed(memory: MemoryStream[(Int, Int)], side: String): 
DataFrame =
+    eventTimeInput(memory, side).withColumn(s"${side}w", 
window(col(s"${side}t"), "10 seconds"))
+
+  /** Adds a watermarked column `<side>s` that holds the event time shifted by 
`shift`. */
+  private def withShifted(df: DataFrame, side: String, shift: String): 
DataFrame = {
+    val time = s"${side}t"
+    df.select(col("*"), (col(time) + expr(shift)).as(s"${side}s", 
df.schema(time).metadata))
+  }
+
+  private def testJoin(conf: (String, String)*)(result: DataFrame)(
+      actions: StreamAction*): Unit = {
+    withSQLConf(Seq(
+        SQLConf.STATE_STORE_PROVIDER_CLASS.key -> 
classOf[RocksDBStateStoreProvider].getName,
+        SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> "false") ++ 
conf: _*) {
+      testStream(result)(StartStream() +: actions: _*)
+    }
+  }
+
+  private def restartActions(restart: Boolean): Seq[StreamAction] =
+    if (restart) Seq(StopStream, StartStream()) else Nil
+
+  private def assertStateRows(rows: Long): StreamAction = Execute { query =>
+    assert(query.lastProgress.stateOperators.head.numRowsTotal === rows)
+  }
+
+  /** Checks the state rows of a join that keeps every row until eviction, as 
all but semi do. */
+  private def assertStateRows(joinType: String, rows: Long): Seq[StreamAction] 
=
+    if (joinType == "left_semi") Nil else Seq(assertStateRows(rows))

Review Comment:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM: Claude Sonnet 5.5 
(`claude-sonnet-5-5`, 1M context), running as an SP2K agent on behalf of 
@HeartSaVioR.
   
   Added in 
[ab59957f358](https://github.com/apache/spark/pull/60280/commits/ab59957f3582d270164fd563b24f31603ff5e54c)
 on #60280. The left_semi variants of the plan-robust bound tests now assert 
their state rows. A left semi join does not store a left row that a right row 
matches in its batch, so its counts differ from the other join types, and each 
test passes its own count. The legacy event-time-pruned left_semi variant is 
named for what it does, evicting at the watermark, with a comment on why: its 
right input is pruned to `rk` and `rc`, so `rc` filters late rows itself. 
Dropping the key cutoff of the join state makes these variants fail, which I 
checked.
   
   <!-- sp2k-review11 reply 4599498498 -->
   



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