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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/MatchingScanWindow.scala:
##########
@@ -0,0 +1,261 @@
+/*
+ * 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.execution.streaming.operators.stateful.join
+
+import java.util.Locale
+
+import scala.util.control.NonFatal
+
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.util.DateTimeConstants._
+import org.apache.spark.sql.types._
+import org.apache.spark.unsafe.types.CalendarInterval
+
+/**
+ * The window of the column that the other input's V4 state is ordered by, 
which a row of this
+ * input can match. For each row, `rangeFor` returns the window, both ends 
inclusive, between the
+ * highest lower bound and the lowest upper bound that the join condition 
implies for that
+ * column, or None when it implies neither. A bound is evaluated on the row 
itself, so it may
+ * depend on any column of the row, as in `rightTime BETWEEN leftTime AND 
expiry`. The window is
+ * empty when the bounds cross.
+ *
+ * A bound must never exclude a row that the condition matches; the join still 
checks the full
+ * condition on every row in the window. A bound that cannot be computed 
exactly is left out:
+ * - Only deterministic conjuncts give bounds. Spark checks each of them on 
every joined row,
+ *   either before the row is stored or after the rows are joined.
+ * - A comparison gives a bound when one side reaches the column through steps 
the bound can be
+ *   inverted through exactly, and the other side reads only this input. A 
strict comparison
+ *   gives an inclusive bound.
+ * - A NULL bound, or one that fails to evaluate or overflows, leaves its end 
of the window open.
+ *   A NULL makes the comparison unknown, so the row matches nothing, but an 
open end is enough.
+ */
+private[sql] class MatchingScanWindow private (
+    lowerBounds: Seq[MatchingScanWindow.ColumnBound],
+    upperBounds: Seq[MatchingScanWindow.ColumnBound],
+    inputAttributes: Seq[Attribute]) {
+
+  private[this] val lower = lowerBounds.map(_.evaluator(inputAttributes))
+  private[this] val upper = upperBounds.map(_.evaluator(inputAttributes))
+
+  def rangeFor(row: InternalRow): Option[(Long, Long)] = {
+    var min = Long.MinValue
+    var max = Long.MaxValue
+    lower.foreach(_(row).foreach(bound => min = math.max(min, bound)))
+    upper.foreach(_(row).foreach(bound => max = math.min(max, bound)))
+    if (min == Long.MinValue && max == Long.MaxValue) None else Some((min, 
max))
+  }
+}
+
+private[sql] object MatchingScanWindow extends PredicateHelper {
+
+  /**
+   * A bound on the indexed column: `value` is evaluated on this input's row, 
and `toColumn`
+   * turns a non-NULL result into the bound in microseconds, or None if there 
is none.
+   */
+  case class ColumnBound(value: Expression, toColumn: Long => Option[Long]) {
+    def evaluator(inputAttributes: Seq[Attribute]): InternalRow => 
Option[Long] = {
+      val projection = UnsafeProjection.create(Seq(value), inputAttributes)
+      row =>
+        try {
+          val result = projection(row)
+          if (result.isNullAt(0)) None else toColumn(result.getLong(0))
+        } catch {
+          // The condition may still evaluate without error, for example when 
no state row is
+          // read, so the error must not fail the query here.
+          case NonFatal(_) => None
+        }
+    }
+  }
+
+  /**
+   * The window of `indexedColumn`, a TIMESTAMP column of the other input, 
implied by
+   * `condition` for rows of the input with `inputAttributes`. Returns None 
when the condition
+   * bounds the column in neither direction.
+   */
+  def apply(
+      condition: Option[Expression],
+      inputAttributes: Seq[Attribute],
+      indexedColumn: Attribute): Option[MatchingScanWindow] = {
+    if (indexedColumn.dataType != TimestampType) return None
+    val bounds = 
condition.toSeq.flatMap(splitConjunctivePredicates).filter(_.deterministic)
+      .flatMap(boundsOf(_, AttributeSet(inputAttributes), indexedColumn))
+    val (lower, upper) = bounds.partition(_._1)
+    if (bounds.isEmpty) {
+      None
+    } else {
+      Some(new MatchingScanWindow(lower.map(_._2), upper.map(_._2), 
inputAttributes))
+    }
+  }
+
+  /** Bounds of one conjunct, each with whether it is a lower bound. */
+  private def boundsOf(
+      conjunct: Expression,
+      input: AttributeSet,
+      column: Attribute): Seq[(Boolean, ColumnBound)] = {
+    // `side >= other` (or > ) bounds the column from below if it is in 
`side`, and from above if
+    // it is in `other`.
+    def atLeast(side: Expression, other: Expression): Seq[(Boolean, 
ColumnBound)] =
+      (solve(side, other, isLower = true, input, column) ++
+        solve(other, side, isLower = false, input, column)).toSeq
+    conjunct match {
+      case GreaterThanOrEqual(l, r) => atLeast(l, r)
+      case GreaterThan(l, r) => atLeast(l, r)
+      case LessThanOrEqual(l, r) => atLeast(r, l)
+      case LessThan(l, r) => atLeast(r, l)
+      case EqualTo(l, r) => atLeast(l, r) ++ atLeast(r, l)
+      case Between(value, lower, upper, _) =>
+        atLeast(value, lower) ++ atLeast(upper, value)
+      case _ => Nil
+    }
+  }
+
+  /**
+   * The bound on the column given `side >= value` (isLower) or `side <= 
value`, where `side`
+   * holds the column and `value` reads only this input.
+   */
+  private def solve(
+      side: Expression,
+      value: Expression,
+      isLower: Boolean,
+      input: AttributeSet,
+      column: Attribute): Option[(Boolean, ColumnBound)] = {
+    def readsOnlyInput(e: Expression): Boolean =
+      e.deterministic && e.references.subsetOf(input) && 
!SubqueryExpression.hasSubquery(e)
+    def holdsColumn(e: Expression): Boolean = e.references.contains(column)
+    // An integral sum is inverted by moving the other term to the bound. ANSI 
mode fails and
+    // TRY mode returns NULL on overflow, so a matching row always has the 
exact sum. The legacy
+    // mode wraps around, so the inversion holds only if no overflow can 
happen.
+    def exactSum(context: NumericEvalContext, x: Expression, y: Expression): 
Boolean =
+      context.evalMode != EvalMode.LEGACY || (for (a <- maxMagnitude(x); b <- 
maxMagnitude(y))
+        yield a + b <= BigInt(Long.MaxValue)).getOrElse(false)
+    // The rewritten bound fails on overflow; the evaluator then leaves the 
end open.
+    side match {
+      case _ if !readsOnlyInput(value) => None
+      case Add(x, y, context) if side.dataType == LongType && 
exactSum(context, x, y) =>
+        if (holdsColumn(x) && readsOnlyInput(y)) {
+          solve(x, Subtract(value, y, EvalMode.ANSI), isLower, input, column)
+        } else if (holdsColumn(y) && readsOnlyInput(x)) {
+          solve(y, Subtract(value, x, EvalMode.ANSI), isLower, input, column)
+        } else {
+          None
+        }
+      case Subtract(x, y, context) if side.dataType == LongType && 
exactSum(context, x, y) =>
+        if (holdsColumn(x) && readsOnlyInput(y)) {
+          solve(x, Add(value, y, EvalMode.ANSI), isLower, input, column)
+        } else if (holdsColumn(y) && readsOnlyInput(x)) {
+          // x - y >= v means y <= x - v.
+          solve(y, Subtract(x, value, EvalMode.ANSI), !isLower, input, column)
+        } else {
+          None
+        }
+      case _ =>
+        toColumnBound(side, isLower, column).map(f => (isLower, 
ColumnBound(value, f)))
+    }
+  }
+
+  /**
+   * The largest absolute value of an integral expression, if it is known: a 
timestamp cast to
+   * BIGINT holds whole seconds of a 64-bit microsecond count.
+   */
+  private def maxMagnitude(e: Expression): Option[BigInt] = e match {
+    case Cast(child, LongType, _, _) if child.dataType == TimestampType =>
+      Some(BigInt(Long.MaxValue / MICROS_PER_SECOND + 1))
+    case Literal(v: Long, LongType) => Some(BigInt(v).abs)
+    case Literal(v: Int, IntegerType) => Some(BigInt(v).abs)
+    case Cast(child, LongType, _, _) if child.dataType == IntegerType => 
maxMagnitude(child)
+    case Add(x, y, _) => for (a <- maxMagnitude(x); b <- maxMagnitude(y)) 
yield a + b
+    case Subtract(x, y, _) => for (a <- maxMagnitude(x); b <- maxMagnitude(y)) 
yield a + b
+    case _ => None
+  }
+
+  /**
+   * How a bound on `side` maps to a bound on the column itself, if `side` is 
the column, cast
+   * to TIMESTAMP or to BIGINT, or shifted by an interval with no days or 
months.
+   */
+  private def toColumnBound(
+      side: Expression,
+      isLower: Boolean,
+      column: Attribute): Option[Long => Option[Long]] = {
+    def shifted(start: Expression, shift: Option[Long]): Option[Long => 
Option[Long]] =
+      for (micros <- shift; inner <- toColumnBound(start, isLower, column))
+        yield (bound: Long) => subtract(bound, micros).flatMap(inner)
+    side match {
+      case a: Attribute if a.semanticEquals(column) => Some(Some(_))
+      case Cast(child, TimestampType, _, _) if child.dataType == TimestampType 
=>
+        toColumnBound(child, isLower, column)
+      // A cast to BIGINT floors to seconds: floor(t) >= s means t >= s 
seconds, and
+      // floor(t) <= s means t is below s + 1 seconds.
+      case Cast(child, LongType, _, _) if child.dataType == TimestampType =>
+        toColumnBound(child, isLower, column).map { inner => (seconds: Long) =>
+          multiply(seconds, MICROS_PER_SECOND)
+            .flatMap(micros => if (isLower) Some(micros) else add(micros, 
MICROS_PER_SECOND - 1))
+            .flatMap(inner)
+        }
+      case TimestampAddInterval(start, interval, _) => shifted(start, 
exactShift(interval))
+      case DatetimeSub(_, _, replacement) => toColumnBound(replacement, 
isLower, column)
+      case TimestampAdd(unit, quantity, start, _) =>
+        val micros = exactUnitMicros(unit).flatMap { unitMicros =>
+          foldableValue(quantity).collect { case n: Number => n.longValue() }
+            .flatMap(multiply(_, unitMicros))
+        }
+        shifted(start, micros)
+      case _ => None
+    }
+  }
+
+  /**
+   * The microseconds of a constant interval without days or months. Spark 
adds whole days and
+   * months in the session time zone, where a day can be 23 or 25 hours long, 
so they have no
+   * exact inverse.
+   */
+  private def exactShift(interval: Expression): Option[Long] =
+    (interval.dataType, foldableValue(interval)) match {
+      case (_: DayTimeIntervalType, Some(micros: Long))
+          if -MICROS_PER_DAY < micros && micros < MICROS_PER_DAY => 
Some(micros)

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, agreed. Fixed in 
[da03c49f74c](https://github.com/apache/spark/pull/60379/commits/da03c49f74c55ca2b5ab23f6f5a56734b308d1dd).
 A shift now inverts whole days when its own time zone has a
   fixed offset, such as UTC or +09:00, because there a day is always 24 hours. 
This covers day-time
   intervals of 24 hours or more, calendar intervals with days (months still 
give no bound), and
   timestampadd in DAY or WEEK. In a zone with daylight saving time nothing 
changes: such a shift still
   gives no bound on the stored side, and the 25-hour-day test still passes in 
every state format.
   New tests: `MatchingScanWindowSuite` "days in a fixed-offset time zone are 
inverted as 24 hours"
   (UTC and +09:00, both probe directions, and an overflow that leaves the end 
open), and
   `StreamingInnerJoinV4Suite` "matching scans invert whole days in a 
fixed-offset time zone".
   
   <!-- sp2k-review10 reply 4549328852 -->
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -717,61 +768,58 @@ case class StreamingSymmetricHashJoinExec(
         Predicate.create(Literal(false), Seq.empty).eval _  // false = do not 
remove if no predicate
     }
 
+    // A NULL in the column that the state watermark predicate tests makes the 
predicate unknown,
+    // so eviction never removes the row. The row cannot match either: that 
column is an equality
+    // key, or a comparison in the join condition bounds it. Handle the row 
like one that fails
+    // the pre-join filter.
+    // The check takes the generated key and the input row, so the key is 
computed only once.
+    private[this] val isEvictionColumnNull: (UnsafeRow, UnsafeRow) => Boolean =
+      stateWatermarkPredicate match {
+        case Some(JoinStateKeyWatermarkPredicate(expr, _, _)) =>
+          // Only a NULL key fails equality. A struct key with a NULL field 
can still be equal.
+          val ordinal = expr.collectFirst { case b: BoundReference => 
b.ordinal }.get
+          (key, _) => key.isNullAt(ordinal)
+        case Some(JoinStateValueWatermarkPredicate(LessThanOrEqual(column, _), 
_, _)) =>
+          // Test the compared column, not the predicate: the predicate holds 
the cutoff, which
+          // changes every batch and would generate and compile new code each 
time.
+          val isNull = Predicate.create(IsNull(column), inputAttributes)
+          (_, row) => isNull.eval(row)
+        case _ =>
+          (_, _) => false
+      }
+
+    // V1 to V3 eviction tests every stored row each batch, so it also removes 
a row whose
+    // eviction column is NULL. This version never stores such a row, but an 
older version did,
+    // and the row can never match. isEvictionColumnNull reads only the key 
for a key predicate
+    // and only the row for a value predicate.
+    private[this] val stateKeyEvictionFunc: UnsafeRow => Boolean =
+      key => stateKeyWatermarkPredicateFunc(key) || isEvictionColumnNull(key, 
null)
+    private[this] val stateValueEvictionFunc: UnsafeRow => Boolean =
+      row => stateValueWatermarkPredicateFunc(row) || 
isEvictionColumnNull(null, row)
+
     private[this] var updatedStateRowsCount = 0
     private[this] var numRemovedFromOtherSideDuringJoinCount = 0
     private[this] val allowMultipleStatefulOperators: Boolean =
       conf.getConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE)
 
-    // V4 range scan for time-interval joins (SPARK-55147). Extracts constant 
interval
-    // offsets from the join condition using 
getStateValueWatermark(eventWatermark=0).
-    // The -1 eviction adjustment widens range by ~1ms/side; postJoinFilter 
handles exact bounds.
-    private[this] val scanRangeOffsets: Option[(Long, Long)] = {
-      val isV4TimeIntervalJoin = stateFormatVersion >= 4 && 
(stateWatermarkPredicate match {
-        case Some(_: JoinStateValueWatermarkPredicate) => true
-        case _ => false
-      })
-
-      if (!isV4TimeIntervalJoin) {
-        None
+    // For the right side of a left semi join: whether a cutoff at the 
late-events watermark that
+    // is exact today shows that no left row passing late filtering can match 
a key and row.
+    private[this] lazy val noLeftRowCanMatch: (UnsafeRow, UnsafeRow) => 
Boolean =
+      if (joinType == LeftSemi && joinSide == RightSide) {
+        val (keyCutoff, valueCutoff) = 
getLeftSemiExactRightCutoffs(left.output, right.output,
+          leftKeys, rightKeys, condition.full, eventTimeWatermarkForLateEvents,
+          useFirstEventTimeColumn = !allowMultipleStatefulOperators)
+        val keyFunc = keyCutoff.map(Predicate.create(_, Seq.empty).eval _)
+        val valueFunc = valueCutoff.map(Predicate.create(_, 
inputAttributes).eval _)
+        (key, row) => keyFunc.exists(_(key)) || valueFunc.exists(_(row))
       } else {
-        val (thisSideAttrs, otherSideAttrs) = joinSide match {
-          case LeftSide => (left.output, right.output)
-          case RightSide => (right.output, left.output)
-        }
-
-        // Scan bounds must constrain the event-time columns used by the index 
and probe.
-        // Bounds on other columns cannot limit this scan. If either 
event-time bound is
-        // missing, scan all rows for the join key.
-        val thisEventTime = WatermarkSupport.findEventTimeColumn(
-          thisSideAttrs, !allowMultipleStatefulOperators).toSeq
-        val otherEventTime = WatermarkSupport.findEventTimeColumn(
-          otherSideAttrs, !allowMultipleStatefulOperators).toSeq
-        val lowerBoundMs = StreamingJoinHelper.getStateValueWatermark(
-          AttributeSet(otherEventTime), AttributeSet(thisEventTime), 
condition.full, Some(0L))
-        val upperBoundMs = StreamingJoinHelper.getStateValueWatermark(
-          AttributeSet(thisEventTime), AttributeSet(otherEventTime), 
condition.full, Some(0L))
-
-        (lowerBoundMs, upperBoundMs) match {
-          case (Some(lower), Some(upper)) =>
-            Some((lower * 1000L, -upper * 1000L)) // ms -> us
-          case _ => None
-        }
+        (_, _) => false
       }
-    }
 
-    private[this] val eventTimeIdxForRangeScan: Int = scanRangeOffsets.map { _ 
=>
-      WatermarkSupport.findEventTimeColumnIndex(
-        inputAttributes, !allowMultipleStatefulOperators).getOrElse(-1)
-    }.getOrElse(-1)
-
-    private def computeTimestampRange(thisRow: UnsafeRow): Option[(Long, 
Long)] = {
-      scanRangeOffsets match {
-        case Some((lowerOffset, upperOffset)) if eventTimeIdxForRangeScan >= 0 
=>
-          val eventTimeUs = thisRow.getLong(eventTimeIdxForRangeScan)
-          Some((eventTimeUs + lowerOffset, eventTimeUs + upperOffset))
-        case _ => None
-      }
-    }
+    private[this] val scanWindow = matchingScanWindow(joinSide)
+
+    private def computeTimestampRange(thisRow: UnsafeRow): Option[(Long, 
Long)] =

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 
[da03c49f74c](https://github.com/apache/spark/pull/60379/commits/da03c49f74c55ca2b5ab23f6f5a56734b308d1dd)
 as you suggested. `getJoinedRowsAndRemoveMatched` now takes the same
   optional `timestampRange` hint as `getJoinedRows`. The V4 state manager 
reads only that range;
   V1 to V3 ignore it. The right side of a left semi join passes its window, so 
a bid now reads only
   the auctions that can match it. Rows outside the window are neither returned 
nor removed. A new
   state manager test checks this and that eviction afterwards sees only the 
remaining rows. The
   existing left semi test on the q9 shape runs in every state format and still 
passes.
   
   <!-- sp2k-review10 reply 4549328862 -->
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/MatchingScanWindow.scala:
##########
@@ -0,0 +1,261 @@
+/*
+ * 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.execution.streaming.operators.stateful.join
+
+import java.util.Locale
+
+import scala.util.control.NonFatal
+
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.util.DateTimeConstants._
+import org.apache.spark.sql.types._
+import org.apache.spark.unsafe.types.CalendarInterval
+
+/**
+ * The window of the column that the other input's V4 state is ordered by, 
which a row of this
+ * input can match. For each row, `rangeFor` returns the window, both ends 
inclusive, between the
+ * highest lower bound and the lowest upper bound that the join condition 
implies for that
+ * column, or None when it implies neither. A bound is evaluated on the row 
itself, so it may
+ * depend on any column of the row, as in `rightTime BETWEEN leftTime AND 
expiry`. The window is
+ * empty when the bounds cross.
+ *
+ * A bound must never exclude a row that the condition matches; the join still 
checks the full
+ * condition on every row in the window. A bound that cannot be computed 
exactly is left out:
+ * - Only deterministic conjuncts give bounds. Spark checks each of them on 
every joined row,
+ *   either before the row is stored or after the rows are joined.
+ * - A comparison gives a bound when one side reaches the column through steps 
the bound can be
+ *   inverted through exactly, and the other side reads only this input. A 
strict comparison
+ *   gives an inclusive bound.
+ * - A NULL bound, or one that fails to evaluate or overflows, leaves its end 
of the window open.
+ *   A NULL makes the comparison unknown, so the row matches nothing, but an 
open end is enough.
+ */
+private[sql] class MatchingScanWindow private (
+    lowerBounds: Seq[MatchingScanWindow.ColumnBound],
+    upperBounds: Seq[MatchingScanWindow.ColumnBound],
+    inputAttributes: Seq[Attribute]) {
+
+  private[this] val lower = lowerBounds.map(_.evaluator(inputAttributes))
+  private[this] val upper = upperBounds.map(_.evaluator(inputAttributes))
+
+  def rangeFor(row: InternalRow): Option[(Long, Long)] = {
+    var min = Long.MinValue
+    var max = Long.MaxValue
+    lower.foreach(_(row).foreach(bound => min = math.max(min, bound)))
+    upper.foreach(_(row).foreach(bound => max = math.min(max, bound)))
+    if (min == Long.MinValue && max == Long.MaxValue) None else Some((min, 
max))
+  }
+}
+
+private[sql] object MatchingScanWindow extends PredicateHelper {
+
+  /**
+   * A bound on the indexed column: `value` is evaluated on this input's row, 
and `toColumn`
+   * turns a non-NULL result into the bound in microseconds, or None if there 
is none.
+   */
+  case class ColumnBound(value: Expression, toColumn: Long => Option[Long]) {
+    def evaluator(inputAttributes: Seq[Attribute]): InternalRow => 
Option[Long] = {
+      val projection = UnsafeProjection.create(Seq(value), inputAttributes)
+      row =>
+        try {
+          val result = projection(row)
+          if (result.isNullAt(0)) None else toColumn(result.getLong(0))
+        } catch {
+          // The condition may still evaluate without error, for example when 
no state row is
+          // read, so the error must not fail the query here.
+          case NonFatal(_) => None
+        }
+    }
+  }
+
+  /**
+   * The window of `indexedColumn`, a TIMESTAMP column of the other input, 
implied by
+   * `condition` for rows of the input with `inputAttributes`. Returns None 
when the condition
+   * bounds the column in neither direction.
+   */
+  def apply(
+      condition: Option[Expression],
+      inputAttributes: Seq[Attribute],
+      indexedColumn: Attribute): Option[MatchingScanWindow] = {
+    if (indexedColumn.dataType != TimestampType) return None
+    val bounds = 
condition.toSeq.flatMap(splitConjunctivePredicates).filter(_.deterministic)
+      .flatMap(boundsOf(_, AttributeSet(inputAttributes), indexedColumn))
+    val (lower, upper) = bounds.partition(_._1)
+    if (bounds.isEmpty) {
+      None
+    } else {
+      Some(new MatchingScanWindow(lower.map(_._2), upper.map(_._2), 
inputAttributes))
+    }
+  }
+
+  /** Bounds of one conjunct, each with whether it is a lower bound. */
+  private def boundsOf(
+      conjunct: Expression,
+      input: AttributeSet,
+      column: Attribute): Seq[(Boolean, ColumnBound)] = {
+    // `side >= other` (or > ) bounds the column from below if it is in 
`side`, and from above if
+    // it is in `other`.
+    def atLeast(side: Expression, other: Expression): Seq[(Boolean, 
ColumnBound)] =
+      (solve(side, other, isLower = true, input, column) ++
+        solve(other, side, isLower = false, input, column)).toSeq
+    conjunct match {
+      case GreaterThanOrEqual(l, r) => atLeast(l, r)
+      case GreaterThan(l, r) => atLeast(l, r)
+      case LessThanOrEqual(l, r) => atLeast(r, l)
+      case LessThan(l, r) => atLeast(r, l)
+      case EqualTo(l, r) => atLeast(l, r) ++ atLeast(r, l)
+      case Between(value, lower, upper, _) =>
+        atLeast(value, lower) ++ atLeast(upper, value)
+      case _ => Nil
+    }
+  }
+
+  /**
+   * The bound on the column given `side >= value` (isLower) or `side <= 
value`, where `side`
+   * holds the column and `value` reads only this input.
+   */
+  private def solve(
+      side: Expression,
+      value: Expression,
+      isLower: Boolean,
+      input: AttributeSet,
+      column: Attribute): Option[(Boolean, ColumnBound)] = {
+    def readsOnlyInput(e: Expression): Boolean =
+      e.deterministic && e.references.subsetOf(input) && 
!SubqueryExpression.hasSubquery(e)
+    def holdsColumn(e: Expression): Boolean = e.references.contains(column)
+    // An integral sum is inverted by moving the other term to the bound. ANSI 
mode fails and
+    // TRY mode returns NULL on overflow, so a matching row always has the 
exact sum. The legacy
+    // mode wraps around, so the inversion holds only if no overflow can 
happen.
+    def exactSum(context: NumericEvalContext, x: Expression, y: Expression): 
Boolean =
+      context.evalMode != EvalMode.LEGACY || (for (a <- maxMagnitude(x); b <- 
maxMagnitude(y))
+        yield a + b <= BigInt(Long.MaxValue)).getOrElse(false)
+    // The rewritten bound fails on overflow; the evaluator then leaves the 
end open.
+    side match {
+      case _ if !readsOnlyInput(value) => None
+      case Add(x, y, context) if side.dataType == LongType && 
exactSum(context, x, y) =>
+        if (holdsColumn(x) && readsOnlyInput(y)) {
+          solve(x, Subtract(value, y, EvalMode.ANSI), isLower, input, column)
+        } else if (holdsColumn(y) && readsOnlyInput(x)) {
+          solve(y, Subtract(value, x, EvalMode.ANSI), isLower, input, column)

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. We went the other way and removed this branch in 
[da03c49f74c](https://github.com/apache/spark/pull/60379/commits/da03c49f74c55ca2b5ab23f6f5a56734b308d1dd).
 Casting an event time to a
   number is a legacy way to compare times, and we do not want to optimize it. 
The window is now
   defined only for TIMESTAMP comparisons: a cast of the column to BIGINT, 
DOUBLE or DECIMAL, alone or
   in a sum, gives no bound, and the row reads every row for its key. 
`MatchingScanWindowSuite` now
   checks that these shapes, including one with the column as the second 
operand, give no window.
   
   <!-- sp2k-review10 reply 4549328869 -->
   



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelperSuite.scala:
##########
@@ -48,6 +91,279 @@ class StreamingJoinHelperSuite extends AnalysisTest {
     }
   }
 
+  test("state watermark extraction ignores columns outside both attribute 
sets") {
+    val leftTime = AttributeReference("leftTime", TimestampType)()
+    val leftOffset = AttributeReference("leftOffset", LongType)()
+    val metadata = new MetadataBuilder().putLong(EventTimeWatermark.delayKey, 
1000).build()
+    val rightTime = AttributeReference("rightTime", TimestampType, metadata = 
metadata)()
+    val rightDelay = AttributeReference("rightDelay", DayTimeIntervalType())()
+    val conditions = Seq(
+      leftTime > TimestampAddInterval(rightTime, rightDelay),
+      leftTime.cast(LongType) + leftOffset > rightTime.cast(LongType))
+    val logAppender = new LogAppender("state watermark extraction")
+    withLogAppender(logAppender, level = Some(Level.WARN)) {
+      conditions.foreach { condition =>
+        withClue(condition.sql) {
+          // The first condition reaches the references check through the V4 
range scan and the
+          // left semi exact cutoff, which pass only the opposite event time; 
eviction passes the
+          // whole opposite input, so its occurrence check already returns 
None. The second
+          // condition also reaches it through eviction, which passes only the 
constrained column
+          // because leftOffset is in neither attribute set.

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, updated in 
[da03c49f74c](https://github.com/apache/spark/pull/60379/commits/da03c49f74c55ca2b5ab23f6f5a56734b308d1dd).
 The comment no longer names the V4 range scan. It now says that
   both conditions reach the references check through eviction, and that the 
left semi exact cutoff
   drops them before solving because their shifts are not literal intervals.
   
   <!-- sp2k-review10 reply 4549328877 -->
   



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