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


##########
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:
   **Non-blocking (P2):** In a session time zone with a fixed offset, a day is 
exactly 24 hours, but this check, and `exactUnitMicros` for `timestampadd`, 
refuse to invert a whole day whatever the shift's zone. 
`DateTimeUtils.timestampAddDayTime` and `timestampAddInterval` add days with 
`atZone(zoneId).plusDays`, which is exact in UTC or `+09:00`, so the reason the 
doc comment above gives holds only in zones with daylight saving time.
   
   Reading the code for `spark.sql.session.timeZone=UTC` and `rightTime BETWEEN 
leftTime AND leftTime + INTERVAL 1 DAY` with both inputs watermarked: the base 
branch range-scanned `[rightTime - 1 day - 1 ms, rightTime + 1 ms]` of the left 
state for each right row. With this PR the right row's only bound is `leftTime 
<= rightTime`, so it reads every retained left row of the key back to the 
eviction cutoff. The symmetric `leftTime BETWEEN rightTime - INTERVAL 1 DAY AND 
rightTime + INTERVAL 1 DAY` gets no window at all on the left-row probe. 
Results stay correct; the cost is extra reads that grow with watermark delay 
and input skew.
   
   Checking whether the shift's own `timeZoneId` has fixed-offset rules, as 
`getLeftSemiExactRightCutoffs.addsDaysExactly` already does in this stack, and 
in that case inverting each whole day as 24 hours, would restore the window. 
The UTC assertions in `MatchingScanWindowSuite` for a calendar day and for 
`timestampadd(DAY)` would change with it.
   
   **Verification:**
   - **Behavior:** In UTC and in a fixed offset such as +09:00, a row whose 
condition bounds the other side's ordering column through INTERVAL 1 DAY, 
INTERVAL 48 HOURS, a calendar interval of days, or timestampadd in DAY or WEEK 
units gets the window that exactly inverts the shift in both probe directions, 
and a shift whose inverse overflows leaves that end open.
   - **Behavior:** A V4 interval join on a whole-day range in UTC returns the 
same matches as state format 2 with the window in place.
   - **Regression:** In America/Los_Angeles the same conditions still give no 
bound on the stored side, and the whole-day join across the 25-hour day still 
emits the match 24.5 hours after the left row in every state format.



##########
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:
   **Non-blocking (P2):** `computeTimestampRange` only reaches `getJoinedRows`. 
For the right side of a left semi join, line 904 calls 
`getJoinedRowsAndRemoveMatched` instead, which takes no range, and 
`SymmetricHashJoinStateManagerV4` serves it with 
`keyWithTsToValues.getValues(key)`, a scan of every left row for the key.
   
   So in V4, for `auctions LEFT SEMI JOIN bids ON id = auction AND bidTime 
BETWEEN dateTime AND expires`, an auction row reads only the bids in 
`[dateTime, expires]`. Each bid still reads every auction of its key, including 
expired auctions waiting for eviction, as on the base branch. The right joiner 
builds its window here and never evaluates it. The PR description says every 
such read now gets a window, and nothing in the code marks this path as 
deferred. Results are unaffected, and the window is safe to apply here too, 
because left rows outside it cannot match the probing right row.
   
   **Recommended change:** Give getJoinedRowsAndRemoveMatched the same optional 
timestampRange hint as getJoinedRows, defaulting to None, inclusive at both 
ends and free to ignore; serve it in SymmetricHashJoinStateManagerV4 with 
keyWithTsToValues.getValuesInRange in place of getValues, let the V1 to V3 
implementation ignore it, and pass computeTimestampRange(thisRow) from the left 
semi right-side branch of OneSideHashJoiner. Add state manager tests for a 
ranged remove-matched lookup and a V4 left semi join test on the q9 shape.
   
   **Why this works:** The right-row probe then reads only the left rows whose 
ordering column lies in the window the condition implies for that right row. 
Rows outside the window cannot match it, so the rows returned and removed are 
the same matched rows as before, and only rows that cannot match stop being 
scanned.
   
   **Scope:** Pass the V4 scan window to the right-row probe of left semi joins.
   
   **Compatibility:** Left semi output and state contents stay the same; only 
rows that cannot match the probing right row stop being read.
   
   **Risks:** Already-matched left rows outside a probe's window, which exist 
only after a join-type change across restarts, are no longer swept by that 
probe and stay until eviction, a case the trait leaves undefined. For the q9 
shape a bid's window is open at the top, so these probes also pay the point 
read at Long.MaxValue that the question about measuring that read raises.
   
   **Constraints:** The range stays a hint: state formats 1 to 3 keep reading 
every row, and results must not depend on whether a manager uses it. Removal 
keeps its per-timestamp-group rewrite; the range only selects which groups are 
read.
   
   **Success:** A V4 left semi right-row probe whose condition gives a window 
reads only the left rows of its key inside that window. Left semi results and 
the rows removed from left state are unchanged in every state format.
   
   **Verification:**
   - **Behavior:** A V4 state manager holding rows at several ordering 
timestamps for one key returns and removes only the matched rows inside the 
given range, keeps the rows outside it, and keeps its timestamp index in step 
with the rows that remain.
   - **Regression:** A V4 left semi join on the q9 shape, with bids arriving 
before, inside and after an auction's lifetime and expired auctions still in 
state, returns the same auctions as state format 2.
   - **Compatibility:** Left semi joins in state formats 1 to 3 return the same 
rows and leave the same state as before when the range is passed.



##########
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:
   **Nit (P3):** This comment no longer matches the callers. This PR removes 
the V4 range scan, so the first path it names is gone. 
`getLeftSemiExactRightCutoffs` drops this conjunct through `isExactShiftOf` 
before solving, because `rightDelay` is not a literal. Eviction 
(`getStateValueWatermarkForInput`) now passes only the opposite event time, so 
it reaches the references check whenever the constrained column has its own 
watermark; for a column without one, the inexact-arithmetic rule returns first. 
A possible rewrite:
   
   ```suggestion
             // Eviction passes only the constrained column and the opposite 
event time, so a term on
             // rightDelay or leftOffset, which are in neither attribute set, 
reaches the references
             // check when the constrained column has its own watermark; 
without one, the
             // inexact-arithmetic rule returns first. The left semi exact 
cutoff drops the first
             // condition before solving, because its interval is not a literal.
   ```
   
   See **Shared repair plan 1** in the review body.



##########
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:
   **Nit (P3):** Nothing fails if this branch regresses. 
`MatchingScanWindowSuite` covers `Subtract` with the indexed column in either 
position, but every `Add` case puts the column first. In 
`StreamingJoinArithmeticWatermarkSuite`'s V4 run of `CAST(leftTime AS LONG) + 
CAST(rightTime AS LONG) > 100`, this branch computes the window only for the 
left rows (1, 5) and (8, 21), whose keys have no right rows at that point. So 
if this line added instead of subtracting, or passed `!isLower`, every test 
would still pass, while a V4 left row arriving after its matching right row 
would get a window that skips that row. A `MatchingScanWindowSuite` case with 
the column as the second operand, checking both a lower and an upper 
comparison, would close the gap.
   
   **Verification:**
   - **Regression:** With the indexed column as the second operand of a BIGINT 
sum, the window for both a lower and an upper comparison equals the bound the 
condition implies, so adding instead of subtracting the other term, or flipping 
the bound direction in that branch, fails the test.



##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinNumericWatermarkSuite.scala:
##########
@@ -0,0 +1,431 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.streaming
+
+import org.apache.logging.log4j.Level
+
+import org.apache.spark.sql.{AnalysisException, 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
+
+class StreamingJoinNumericWatermarkSuite extends StreamTest {
+  import testImplicits._
+
+  private val timestampRule = "A time range condition must bound a TIMESTAMP 
column"
+
+  // Analysis rejects the plan before any state format is used. Each bound 
below is exact, with
+  // no truncating cast and no whole days, so only the TIMESTAMP-column rule 
rejects it.
+  test("left outer join cannot use a numeric state field for range eviction") {
+    val leftInput = MemoryStream[(Int, Long, Long)]
+    val rightInput = MemoryStream[(Int, Long)]
+    val left = leftInput.toDF().toDF("leftKey", "n", "time")
+      .select($"leftKey", $"n", timestamp_seconds($"time").as("lt"))
+      .withWatermark("lt", "1 second")
+    val right = rightInput.toDF().toDF("rightKey", "time")
+      .select($"rightKey", timestamp_seconds($"time").as("rt"))
+      .withWatermark("rt", "1 second")
+    val joined = left.join(right,
+      expr("leftKey = rightKey AND n > CAST(rt AS DOUBLE)"), "left_outer")
+      .select($"leftKey", $"n", $"lt")
+
+    val error = intercept[AnalysisException] {
+      testStream(joined)(
+        AddData(leftInput, (1, 20L, 20L)),
+        CheckNewAnswer())
+    }
+    assert(error.getMessage.contains("a watermark on the right input and a 
time constraint"))
+    assert(error.getMessage.contains(timestampRule))
+  }
+
+  // Earlier versions admitted this join, so disabling the finalization check 
runs it. The left
+  // state is never evicted, so the unmatched left row (2, 50) is never output 
with nulls, which
+  // evicting it by the cutoff solved for the numeric field would do.
+  test("left outer join on a numeric state field runs with the finalization 
check disabled") {
+    val leftInput = MemoryStream[(Int, Long, Long)]
+    val rightInput = MemoryStream[(Int, Long)]
+    val left = leftInput.toDF().toDF("leftKey", "n", "time")
+      .select($"leftKey", $"n", timestamp_seconds($"time").as("lt"))
+      .withWatermark("lt", "1 second")
+    val right = rightInput.toDF().toDF("rightKey", "time")
+      .select($"rightKey", timestamp_seconds($"time").as("rt"))
+      .withWatermark("rt", "1 second")
+    val joined = left.join(right,
+      expr("leftKey = rightKey AND n > CAST(rt AS DOUBLE)"), "left_outer")
+      .select($"leftKey", $"n", $"rt".cast("long"))
+
+    val appender = new LogAppender("finalization check disabled")
+    withLogAppender(appender, level = Some(Level.WARN)) {
+      withSQLConf(SQLConf.STREAMING_JOIN_CHECK_FINALIZATION_ENABLED.key -> 
"false") {
+        testStream(joined)(
+          StreamProgressLockedActions(Seq(
+            AddData(leftInput, (1, 20L, 20L)), AddData(rightInput, (1, 10L)))),
+          CheckNewAnswer(Row(1, 20L, 10L)),
+          AddData(rightInput, (2, 100L)),
+          CheckNewAnswer(),
+          // The left row (2, 50) does not match (2, 100). Its time is below 
the eviction
+          // watermark of 99 seconds in the next batch, yet the left state 
keeps the row.
+          AddData(leftInput, (2, 50L, 50L), (3, 200L, 200L)),
+          CheckNewAnswer(),
+          AddData(rightInput, (4, 120L)),
+          CheckNewAnswer())
+      }
+    }
+    assert(appender.loggingEvents.exists { event =>
+      val message = event.getMessage.getFormattedMessage
+      message.contains("allow unmatched state to be finalized") &&
+        message.contains("keeps that state without bound")
+    })
+  }
+
+  // Comparing with the TIMESTAMP event time casts these columns, but eviction 
compares the
+  // cutoff with the column itself.
+  for (columnType <- Seq("date", "timestamp_ntz")) {
+    test(s"left outer join cannot use a $columnType state field for range 
eviction") {
+      val leftInput = MemoryStream[(Int, Long)]
+      val rightInput = MemoryStream[(Int, Long)]
+      val left = leftInput.toDF().toDF("leftKey", "time")
+        .select($"leftKey", 
timestamp_seconds($"time").cast(columnType).as("orderDate"))
+      val right = rightInput.toDF().toDF("rightKey", "time")
+        .select($"rightKey", timestamp_seconds($"time").as("rt"))
+        .withWatermark("rt", "1 second")
+      val joined = left.join(right,
+        expr("leftKey = rightKey AND orderDate >= rt - INTERVAL 7 HOURS"), 
"left_outer")
+
+      val error = intercept[AnalysisException] {
+        testStream(joined)(
+          AddData(leftInput, (1, 20L)),
+          CheckNewAnswer())
+      }
+      assert(error.getMessage.contains(timestampRule))
+    }
+  }
+
+  private def withJoinConf(version: Int)(f: => Unit): Unit = {
+    withSQLConf(
+        SQLConf.STREAMING_JOIN_STATE_FORMAT_VERSION.key -> version.toString,
+        SQLConf.STATE_STORE_PROVIDER_CLASS.key -> 
classOf[RocksDBStateStoreProvider].getName,
+        SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> "false")(f)
+  }
+
+  // window() over a watermarked time column. The window is the input's only 
event-time column.
+  private def windowed(
+      input: MemoryStream[(Int, Long)],
+      key: String,
+      windowName: String,
+      duration: String,
+      slide: String): DataFrame = {
+    input.toDF().toDF(key, "time")
+      .select(col(key), timestamp_seconds($"time").as("t"))
+      .withWatermark("t", "0 seconds")
+      .select(col(key), window($"t", duration, slide).as(windowName))
+  }
+
+  // An evicted left window starts at least its own duration before the 
watermark, and a later
+  // right window starts less than its own duration before it, so with left 
windows at least as
+  // long a later right window orders above every evicted left window.
+  for {
+    version <- Seq(2, 3, 4)
+    leftDuration <- Seq("10 seconds", "20 seconds")
+  } {
+    test(s"left outer join finalizes $leftDuration windows by a whole-window 
bound, V$version") {
+      withJoinConf(version) {
+        val leftInput = MemoryStream[(Int, Long)]
+        val rightInput = MemoryStream[(Int, Long)]
+        val left = windowed(leftInput, "leftKey", "lw", leftDuration, 
leftDuration)
+        val right = windowed(rightInput, "rightKey", "rw", "10 seconds", "10 
seconds")
+        val joined = left.join(right, $"leftKey" === $"rightKey" && $"lw" > 
$"rw", "left_outer")
+          .select($"leftKey", $"lw.start".cast("long"), 
$"rw.start".cast("long"))
+        val matchedStart = if (leftDuration == "10 seconds") 10L else 0L
+
+        testStream(joined)(
+          StreamProgressLockedActions(Seq(
+            AddData(leftInput, (1, 5L), (5, 15L)), AddData(rightInput, (2, 
5L), (5, 5L)))),
+          CheckNewAnswer(Row(5, matchedStart, 0L)),
+          StreamProgressLockedActions(Seq(
+            AddData(leftInput, (3, 45L)), AddData(rightInput, (2, 45L)))),
+          CheckNewAnswer(),
+          // The eviction watermark is 45 seconds, past the end of key 1's 
left window.
+          AddData(rightInput, (2, 46L)),
+          CheckNewAnswer(Row(1, 0L, null)))
+      }
+    }
+  }
+
+  // The left input is watermarked on its event time lt, which the join 
condition does not use,
+  // and holds a window over the unwatermarked column ot. Eviction must try 
the window after lt
+  // finds no bound, or the left state is never finalized.
+  for (version <- Seq(2, 4)) {
+    test(s"left outer join finalizes a window over an unwatermarked column, 
V$version") {
+      withJoinConf(version) {
+        val leftInput = MemoryStream[(Int, Long)]
+        val rightInput = MemoryStream[(Int, Long)]
+        val left = leftInput.toDF().toDF("leftKey", "time")
+          .select($"leftKey", timestamp_seconds($"time").as("lt"),
+            timestamp_seconds($"time").as("ot"))
+          .withWatermark("lt", "0 seconds")
+          .select($"leftKey", $"lt", window($"ot", "10 seconds").as("lw"))
+        val right = windowed(rightInput, "rightKey", "rw", "10 seconds", "10 
seconds")
+        val joined = left.join(right, $"leftKey" === $"rightKey" && $"lw" > 
$"rw", "left_outer")
+          .select($"leftKey", $"lw.start".cast("long"), 
$"rw.start".cast("long"))
+
+        testStream(joined)(
+          StreamProgressLockedActions(Seq(
+            AddData(leftInput, (1, 5L), (5, 15L)), AddData(rightInput, (2, 
5L), (5, 5L)))),
+          CheckNewAnswer(Row(5, 10L, 0L)),
+          StreamProgressLockedActions(Seq(
+            AddData(leftInput, (3, 45L)), AddData(rightInput, (2, 45L)))),
+          CheckNewAnswer(),
+          // The eviction watermark is 45 seconds, past the end of key 1's 
left window.
+          AddData(rightInput, (2, 46L)),
+          CheckNewAnswer(Row(1, 0L, null)))
+      }
+    }
+  }
+
+  test("right outer and left semi joins finalize windows by a whole-window 
bound") {
+    Seq("right_outer", "left_semi").foreach { joinType =>
+      withClue(joinType) {
+        withJoinConf(2) {
+          val leftInput = MemoryStream[(Int, Long)]
+          val rightInput = MemoryStream[(Int, Long)]
+          val left = windowed(leftInput, "leftKey", "lw", "10 seconds", "10 
seconds")
+          val right = windowed(rightInput, "rightKey", "rw", "10 seconds", "10 
seconds")
+          val condition = $"leftKey" === $"rightKey" && $"lw" > $"rw"
+          // The right outer join finalizes the same left windows.
+          val (joined, unmatched) = if (joinType == "right_outer") {
+            (right.join(left, condition, joinType)
+              .select($"leftKey", $"lw.start".cast("long"), 
$"rw.start".cast("long")),
+              Seq(Row(1, 0L, null)))
+          } else {
+            (left.join(right, condition, joinType)
+              .select($"leftKey", $"lw.start".cast("long")), Seq.empty)
+          }
+          val matched = if (joinType == "right_outer") Row(5, 10L, 0L) else 
Row(5, 10L)
+
+          testStream(joined)(
+            StreamProgressLockedActions(Seq(
+              AddData(leftInput, (1, 5L), (5, 15L)), AddData(rightInput, (2, 
5L), (5, 5L)))),
+            CheckNewAnswer(matched),
+            StreamProgressLockedActions(Seq(
+              AddData(leftInput, (3, 25L)), AddData(rightInput, (2, 25L)))),
+            CheckNewAnswer(),
+            AddData(rightInput, (2, 26L)),
+            CheckNewAnswer(unmatched: _*))
+        }
+      }
+    }
+  }
+
+  // A 20-second right window that ends above the watermark can start before a 
10-second left
+  // window that ends at or below it, so these left windows cannot be 
finalized.
+  test("outer and semi joins cannot finalize windows shorter than the other 
input's") {
+    Seq("left_outer", "left_semi", "right_outer").foreach { joinType =>
+      withClue(joinType) {
+        val leftInput = MemoryStream[(Int, Long)]
+        val rightInput = MemoryStream[(Int, Long)]
+        val left = windowed(leftInput, "leftKey", "lw", "10 seconds", "10 
seconds")
+        val right = windowed(rightInput, "rightKey", "rw", "20 seconds", "1 
second")
+        val condition = $"leftKey" === $"rightKey" && $"lw" > $"rw"
+        val joined = if (joinType == "right_outer") {
+          right.join(left, condition, joinType)
+        } else {
+          left.join(right, condition, joinType)
+        }
+
+        val error = intercept[AnalysisException] {
+          testStream(joined)(
+            AddData(leftInput, (1, 5L)),
+            CheckNewAnswer())
+        }
+        assert(error.getMessage.contains(timestampRule))
+      }
+    }
+  }
+
+  for (version <- Seq(2, 3, 4)) {
+    test(s"inner join evicts windows by a whole-window bound, V$version") {
+      withJoinConf(version) {
+        val leftInput = MemoryStream[(Int, Long)]
+        val rightInput = MemoryStream[(Int, Long)]
+        val left = windowed(leftInput, "leftKey", "lw", "10 seconds", "10 
seconds")
+        val right = windowed(rightInput, "rightKey", "rw", "10 seconds", "10 
seconds")
+        val joined = left.join(right, $"leftKey" === $"rightKey" && $"lw" > 
$"rw")
+          .select($"leftKey", $"lw.start".cast("long"), 
$"rw.start".cast("long"))
+
+        testStream(joined)(
+          StreamProgressLockedActions(Seq(
+            AddData(leftInput, (1, 5L)), AddData(rightInput, (2, 5L)))),
+          CheckNewAnswer(),
+          StreamProgressLockedActions(Seq(
+            AddData(leftInput, (3, 25L)), AddData(rightInput, (4, 25L)))),
+          CheckNewAnswer(),
+          // Distinct keys: V4 groups rows with the same key and time into one 
entry.
+          AddData(rightInput, (6, 26L)),
+          CheckNewAnswer(),
+          Execute { query =>
+            // Left window [0, 10) is evicted. Left [20, 30) and the three 
right rows remain,
+            // because the bound gives right windows no cutoff.
+            val total = query.lastProgress.stateOperators.head.numRowsTotal
+            assert(total == 4, s"numRowsTotal = $total")
+          })
+      }
+    }
+  }
+
+  // Ordering windows compares their starts first. A 20-second right window 
that ends above the
+  // watermark can start before a 10-second left window that ends at or below 
it, so a bound that
+  // compares whole windows must not evict left windows.
+  for (version <- Seq(2, 3, 4)) {
+    test(s"inner join keeps windows that a longer opposite window can still 
match, V$version") {
+      withJoinConf(version) {
+        val leftInput = MemoryStream[(Int, Long)]
+        val rightInput = MemoryStream[(Int, Long)]
+        val left = windowed(leftInput, "leftKey", "lw", "10 seconds", "10 
seconds")
+        val right = windowed(rightInput, "rightKey", "rw", "20 seconds", "1 
second")
+        val joined = left.join(right, $"leftKey" === $"rightKey" && $"lw" > 
$"rw")
+          .select($"leftKey", $"lw.start".cast("long"), 
$"rw.start".cast("long"))
+
+        testStream(joined)(
+          StreamProgressLockedActions(Seq(
+            AddData(leftInput, (1, 5L)), AddData(rightInput, (9, 5L)))),
+          CheckNewAnswer(),
+          StreamProgressLockedActions(Seq(
+            AddData(leftInput, (8, 15L)), AddData(rightInput, (9, 15L)))),
+          CheckNewAnswer(),
+          // The watermark reaches 15 seconds, past the end of left window [0, 
10).
+          AddData(rightInput, (9, 16L)),
+          CheckNewAnswer(),
+          // Time 18 is in right window [-1, 19), which is not late and orders 
below [0, 10).
+          AddData(rightInput, (1, 18L)),
+          CheckNewAnswer(Row(1, 0L, -1L)))
+      }
+    }
+  }
+
+  // A union's column keeps its first child's metadata, so with children of 
different window
+  // lengths it records none, and a whole-window bound evicts neither union's 
windows nor the
+  // windows compared with them: a 20-second window can start before a 
10-second window that ends
+  // at or below the watermark.
+  test("outer joins cannot finalize windows compared with a union of window 
lengths") {
+    Seq("right", "left").foreach { unionSide =>
+      withClue(s"$unionSide union") {
+        val leftInput = MemoryStream[(Int, Long)]
+        val otherLeftInput = MemoryStream[(Int, Long)]
+        val rightInput = MemoryStream[(Int, Long)]
+        val otherRightInput = MemoryStream[(Int, Long)]
+        val (left, right) = if (unionSide == "right") {
+          (windowed(leftInput, "leftKey", "lw", "10 seconds", "10 seconds"),
+            windowed(rightInput, "rightKey", "rw", "10 seconds", "10 seconds")
+              .union(windowed(otherRightInput, "rightKey", "rw", "20 seconds", 
"1 second")))
+        } else {
+          (windowed(leftInput, "leftKey", "lw", "20 seconds", "20 seconds")
+              .union(windowed(otherLeftInput, "leftKey", "lw", "10 seconds", 
"10 seconds")),
+            windowed(rightInput, "rightKey", "rw", "20 seconds", "1 second"))
+        }
+        val joined = left.join(right, $"leftKey" === $"rightKey" && $"lw" > 
$"rw", "left_outer")
+
+        val error = intercept[AnalysisException] {
+          testStream(joined)(
+            AddData(leftInput, (1, 5L)),
+            CheckNewAnswer())
+        }
+        assert(error.getMessage.contains(timestampRule))
+      }
+    }
+  }
+
+  for (version <- Seq(2, 3, 4)) {
+    test(s"inner join keeps windows compared with a union of window lengths, 
V$version") {
+      withJoinConf(version) {
+        val leftInput = MemoryStream[(Int, Long)]
+        val tumblingInput = MemoryStream[(Int, Long)]
+        val slidingInput = MemoryStream[(Int, Long)]
+        val left = windowed(leftInput, "leftKey", "lw", "10 seconds", "10 
seconds")
+        val right = windowed(tumblingInput, "rightKey", "rw", "10 seconds", 
"10 seconds")
+          .union(windowed(slidingInput, "rightKey", "rw", "20 seconds", "1 
second"))
+        val joined = left.join(right, $"leftKey" === $"rightKey" && $"lw" > 
$"rw")
+          .select($"leftKey", $"lw.start".cast("long"), 
$"rw.start".cast("long"))
+
+        testStream(joined)(
+          StreamProgressLockedActions(Seq(AddData(leftInput, (1, 5L)),
+            AddData(tumblingInput, (9, 5L)), AddData(slidingInput, (9, 5L)))),
+          CheckNewAnswer(),
+          StreamProgressLockedActions(Seq(AddData(leftInput, (8, 15L)),
+            AddData(tumblingInput, (9, 15L)), AddData(slidingInput, (9, 
15L)))),
+          CheckNewAnswer(),
+          // The watermark reaches 15 seconds, past the end of left window [0, 
10).
+          AddData(tumblingInput, (9, 16L)),
+          CheckNewAnswer(),
+          // Time 18 is in sliding right window [-1, 19), which is not late 
and orders below
+          // [0, 10).
+          AddData(slidingInput, (1, 18L)),
+          CheckNewAnswer(Row(1, 0L, -1L)))
+      }
+    }
+  }
+
+  // Both directions give a cutoff, so V4 would compute range-scan offsets, 
which read the event
+  // time as a long. A time-window event time must not use them.

Review Comment:
   **Nit (P3):** This PR removes `scanRangeOffsets`, so the reason given here 
no longer exists. What now keeps a time-window ordering column from being 
range-scanned is `MatchingScanWindow.apply`, which returns no window when the 
indexed column is not `TIMESTAMP`, whether or not either direction gives a 
cutoff. A possible rewrite:
   
   ```suggestion
     // Both directions give a cutoff, so V4 orders each side's state by its 
time window. The scan
     // window bounds only a TIMESTAMP ordering column, so neither probe 
range-scans by window.
   ```
   
   See **Shared repair plan 1** in the review body.



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