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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -261,28 +261,37 @@ object StreamingSymmetricHashJoinHelper extends Logging {
             eventTimeWatermarkForEviction.get,
             prevStateKeyWatermark)
         }
-      } else if (isWatermarkDefinedOnInput) { // case 2 in the 
StreamingSymmetricHashJoinExec docs
-        val stateValueWatermark = StreamingJoinHelper.getStateValueWatermark(
-          attributesToFindStateWatermarkFor = 
AttributeSet(oneSideInputAttributes),
-          attributesWithEventWatermark = 
AttributeSet(otherSideInputAttributes),
-          condition,
-          eventTimeWatermarkForEviction)
-        // A row can pass late-input filtering but already be eligible for 
eviction in this batch.
-        // When the previous join-derived state cutoff is ahead of the 
late-input watermark, a new
-        // row can fall at or below that cutoff. V4 must scan from the 
beginning to find such rows.
-        val prevStateValueWatermark = eventTimeWatermarkForLateEvents.flatMap 
{ lateWatermark =>
-          StreamingJoinHelper.getStateValueWatermark(
-            attributesToFindStateWatermarkFor = 
AttributeSet(oneSideInputAttributes),
-            attributesWithEventWatermark = 
AttributeSet(otherSideInputAttributes),
-            condition,
-            eventTimeWatermarkForLateEvents).filter(_ <= lateWatermark)
-        }
-        val inputAttributeWithWatermark = 
oneSideInputAttributes.find(_.metadata.contains(delayKey))
-        val expr = watermarkExpression(inputAttributeWithWatermark, 
stateValueWatermark)
-        expr.map { e =>
-          // watermarkExpression only provides the expression when 
eventTimeWatermarkForEviction
-          // is defined
-          JoinStateValueWatermarkPredicate(e, stateValueWatermark.get, 
prevStateValueWatermark)
+      } else if (isWatermarkDefinedOnInput || !useFirstEventTimeColumn) {

Review Comment:
   **Non-blocking (P2):** With this condition, an input without its own 
watermark gets `leftTime <= cutoff` in the default mode, which lets eviction 
reach the rows a 4.3 checkpoint stored on state format versions 1 to 3, except 
those whose `leftTime` is NULL: the predicate is never true for them, and 
`isEvictionColumnNull` (StreamingSymmetricHashJoinExec.scala:747-755) screens 
only arriving rows. Because such an input has no late filtering and 4.3 never 
evicts it, a 4.3 checkpoint of a left outer join with a watermark only on 
`rightTime` and `leftTime BETWEEN rightTime - INTERVAL 5 SECONDS AND rightTime 
+ INTERVAL 5 SECONDS` holds every left row with a NULL `leftTime` that the 
query ever received. Reading the code, after the upgrade left (2, 5 s) is 
evicted and (2, null) is emitted as intended, but left (1, NULL) stays in state 
and (1, null) is never emitted, although the same row arriving after the 
upgrade is emitted at once. Switching a state format 1 to 3 checkpoint from 
allowMult
 iple=false to the default does the same. Inner and left semi joins are 
unaffected, because the optimizer filters such rows out below the join. The 
per-row removal of NULL-column rows suggested for the watermarked case would 
cover this input too.
   
   See **Shared repair plan 1** in the review body.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -261,28 +261,37 @@ object StreamingSymmetricHashJoinHelper extends Logging {
             eventTimeWatermarkForEviction.get,
             prevStateKeyWatermark)
         }
-      } else if (isWatermarkDefinedOnInput) { // case 2 in the 
StreamingSymmetricHashJoinExec docs
-        val stateValueWatermark = StreamingJoinHelper.getStateValueWatermark(
-          attributesToFindStateWatermarkFor = 
AttributeSet(oneSideInputAttributes),
-          attributesWithEventWatermark = 
AttributeSet(otherSideInputAttributes),
-          condition,
-          eventTimeWatermarkForEviction)
-        // A row can pass late-input filtering but already be eligible for 
eviction in this batch.
-        // When the previous join-derived state cutoff is ahead of the 
late-input watermark, a new
-        // row can fall at or below that cutoff. V4 must scan from the 
beginning to find such rows.
-        val prevStateValueWatermark = eventTimeWatermarkForLateEvents.flatMap 
{ lateWatermark =>
-          StreamingJoinHelper.getStateValueWatermark(
-            attributesToFindStateWatermarkFor = 
AttributeSet(oneSideInputAttributes),
-            attributesWithEventWatermark = 
AttributeSet(otherSideInputAttributes),
-            condition,
-            eventTimeWatermarkForLateEvents).filter(_ <= lateWatermark)
-        }
-        val inputAttributeWithWatermark = 
oneSideInputAttributes.find(_.metadata.contains(delayKey))
-        val expr = watermarkExpression(inputAttributeWithWatermark, 
stateValueWatermark)
-        expr.map { e =>
-          // watermarkExpression only provides the expression when 
eventTimeWatermarkForEviction
-          // is defined
-          JoinStateValueWatermarkPredicate(e, stateValueWatermark.get, 
prevStateValueWatermark)
+      } else if (isWatermarkDefinedOnInput || !useFirstEventTimeColumn) {
+        // case 2 in the StreamingSymmetricHashJoinExec docs. The opposite 
watermark bounds the
+        // future matches, so this input needs no watermark of its own, except 
in the legacy mode.
+        val eventTime = 
oneSideInputAttributes.find(_.metadata.contains(delayKey))
+        // The legacy mode with a single global watermark keeps applying a 
cutoff on any column of
+        // this input to the event time.
+        def solve(watermark: Option[Long]): Option[(Attribute, Long)] =
+          if (useFirstEventTimeColumn) {
+            StreamingJoinHelper.getStateValueWatermark(
+              attributesToFindStateWatermarkFor = 
AttributeSet(oneSideInputAttributes),
+              attributesWithEventWatermark = 
AttributeSet(otherSideInputAttributes),
+              condition,
+              watermark).map(eventTime.get -> _)
+          } else {
+            
StreamingJoinHelper.getStateValueWatermarkColumn(oneSideInputAttributes,

Review Comment:
   **Blocking (P1):** Evicting this input by the column the condition bounds 
keeps rows whose event time is already below the state watermark that 
`produceOutputWatermark` publishes: `getStateWatermark` 
(StreamingSymmetricHashJoinHelper.scala:182-199) still solves the condition 
over all of the input's columns, so for `rightTime BETWEEN leftTime AND expiry` 
it reports the expiry-derived cutoff as if the input were evicted by 
`leftTime`. A downstream Append-mode stateful operator uses that output 
watermark as its late-event watermark, so it drops the matched and unmatched 
rows the join emits from buffered rows older than it. Reading the code with 
60-second watermarks and the data of the new 'range eviction uses the bounded 
column' test, a left outer join followed by `groupBy(window(leftTime, '1 
minute')).count()` in Append mode would count 2 for the window holding both 
left rows on the base branch, which emits both as unmatched while the 
downstream late watermark is about 39.999 s, and
  0 with this change, which emits them after the join has published about 
339.999 s. For inner and left semi joins, the dropped rows are matches the base 
branch lost at the join, so their chained results are no worse, but the matches 
this change restores still never reach the downstream operator. The same holds 
for an inner join whose watermarked input is bounded only through a 
non-TIMESTAMP column: that input is now never evicted while its state watermark 
keeps advancing.
   
   **Recommended change:** Treat a stream-stream join, in the default mode, as 
a stateful operation that can emit rows older than the watermark when an input 
with its own watermark would be evicted by a column other than its event time, 
or by no column although a bound on a non-TIMESTAMP column still yields a 
cutoff for it, so that the existing global watermark correctness check rejects 
a stateful operator placed after such a join. Add the limit to the 
bounded-column entry of the Structured Streaming migration guide, and add 
unsupported-operation and multi-stateful-operator join tests.
   
   **Why this works:** ifCannotBeFollowedByStatefulOperation gains a 
stream-stream join case that runs, for each input with its own watermark, the 
same decision execution uses: StreamingJoinHelper.getStateValueWatermarkColumn 
against the other input, as hasValidRange in UnsupportedOperationChecker.scala 
lines 713-720 already does. When that decision picks a column other than the 
event time, or picks none while the whole-input cutoff that getStateWatermark 
reports is defined, the join is flagged, so 
checkStreamingQueryGlobalWatermarkLimit raises its existing 'possible 
correctness issue due to global watermark' error before any batch runs and no 
downstream operator consumes the unsound output watermark.
   
   **Compatibility:** Chained queries whose join bounds each watermarked 
input's event time keep passing analysis and keep the base branch's output 
watermark.
   
   **Risks:** A query that chains a stateful operator after such a join runs on 
the base branch, where that input is evicted early by its event time, and fails 
analysis after this repair; setting 
spark.sql.streaming.statefulOperator.checkCorrectness.enabled to false turns 
the error into a warning and runs the query with the late-row drops the check 
warns about, and legacy mode is no way back because it allows only one stateful 
operator. For outer joins that preserve such an input the rejection closes a 
regression, but inner and left semi chains, whose downstream results this 
change alone leaves no worse than on the base branch, also fail analysis, 
trading a silently incomplete result for an explicit error.
   
   **Constraints:** The new case must make the same column choice as execution, 
with the event time preferred, so joins whose condition bounds each watermarked 
input's event time stay chainable. It applies only when multiple stateful 
operators are allowed, and joins with a watermark in their equality keys, which 
are evicted by that key, stay outside it.
   
   **Exclusions:**
   - One-sided joins whose watermarked input gets no cutoff because the other 
input has no watermark keep their base-branch behavior, since their output 
watermark already ignores that input's never-evicted state and changing it is 
outside this change.
   
   **Verification:**
   - **Behavior:** Analysis rejects with the global-watermark correctness 
error, and only warns when the correctness check is disabled, an Append-mode 
window aggregation on leftTime placed after a left outer, inner, or left semi 
join on `leftKey = rightKey AND rightTime BETWEEN leftTime AND expiry` with 
watermarks on leftTime and rightTime, and after an inner join whose watermarked 
left input is bounded only through `CAST(leftDate AS TIMESTAMP) > rightTime - 
INTERVAL 1 DAY`.
   - **Compatibility:** A time-interval left outer join on `leftTime BETWEEN 
rightTime - INTERVAL 1 HOUR AND rightTime + INTERVAL 1 HOUR` followed by an 
Append-mode window aggregation on leftTime still passes analysis and produces 
the same counts as on the base branch.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -261,28 +261,37 @@ object StreamingSymmetricHashJoinHelper extends Logging {
             eventTimeWatermarkForEviction.get,
             prevStateKeyWatermark)
         }
-      } else if (isWatermarkDefinedOnInput) { // case 2 in the 
StreamingSymmetricHashJoinExec docs
-        val stateValueWatermark = StreamingJoinHelper.getStateValueWatermark(
-          attributesToFindStateWatermarkFor = 
AttributeSet(oneSideInputAttributes),
-          attributesWithEventWatermark = 
AttributeSet(otherSideInputAttributes),
-          condition,
-          eventTimeWatermarkForEviction)
-        // A row can pass late-input filtering but already be eligible for 
eviction in this batch.
-        // When the previous join-derived state cutoff is ahead of the 
late-input watermark, a new
-        // row can fall at or below that cutoff. V4 must scan from the 
beginning to find such rows.
-        val prevStateValueWatermark = eventTimeWatermarkForLateEvents.flatMap 
{ lateWatermark =>
-          StreamingJoinHelper.getStateValueWatermark(
-            attributesToFindStateWatermarkFor = 
AttributeSet(oneSideInputAttributes),
-            attributesWithEventWatermark = 
AttributeSet(otherSideInputAttributes),
-            condition,
-            eventTimeWatermarkForLateEvents).filter(_ <= lateWatermark)
-        }
-        val inputAttributeWithWatermark = 
oneSideInputAttributes.find(_.metadata.contains(delayKey))
-        val expr = watermarkExpression(inputAttributeWithWatermark, 
stateValueWatermark)
-        expr.map { e =>
-          // watermarkExpression only provides the expression when 
eventTimeWatermarkForEviction
-          // is defined
-          JoinStateValueWatermarkPredicate(e, stateValueWatermark.get, 
prevStateValueWatermark)
+      } else if (isWatermarkDefinedOnInput || !useFirstEventTimeColumn) {
+        // case 2 in the StreamingSymmetricHashJoinExec docs. The opposite 
watermark bounds the
+        // future matches, so this input needs no watermark of its own, except 
in the legacy mode.
+        val eventTime = 
oneSideInputAttributes.find(_.metadata.contains(delayKey))
+        // The legacy mode with a single global watermark keeps applying a 
cutoff on any column of
+        // this input to the event time.
+        def solve(watermark: Option[Long]): Option[(Attribute, Long)] =
+          if (useFirstEventTimeColumn) {
+            StreamingJoinHelper.getStateValueWatermark(
+              attributesToFindStateWatermarkFor = 
AttributeSet(oneSideInputAttributes),
+              attributesWithEventWatermark = 
AttributeSet(otherSideInputAttributes),
+              condition,
+              watermark).map(eventTime.get -> _)
+          } else {
+            
StreamingJoinHelper.getStateValueWatermarkColumn(oneSideInputAttributes,
+              AttributeSet(otherSideInputAttributes), condition, watermark)
+          }
+        solve(eventTimeWatermarkForEviction).flatMap { case (column, 
stateValueWatermark) =>
+          // A row can pass late-input filtering but already be eligible for 
eviction in this
+          // batch. When the previous join-derived state cutoff is ahead of 
the late-input
+          // watermark, a new row can fall at or below that cutoff. V4 must 
scan from the
+          // beginning to find such rows. Late-input filtering bounds only the 
event time, so a
+          // cutoff on another column always scans from the beginning.
+          val prevStateValueWatermark = 
eventTimeWatermarkForLateEvents.flatMap { lateWatermark =>
+            solve(Some(lateWatermark)).collect {
+              case (c, w) if eventTime.exists(_.semanticEquals(c)) && w <= 
lateWatermark => w
+            }
+          }
+          watermarkExpression(Some(column), Some(stateValueWatermark)).map { e 
=>

Review Comment:
   **Blocking (P1):** After an upgrade, the predicate built here for a 
watermarked input bounded only through another TIMESTAMP column tests that 
column, for example `expiry <= cutoff`, and per-row eviction on state format 
versions 1 to 3 (StreamingSymmetricHashJoinExec.scala:735-740, 
SymmetricHashJoinStateManager.scala:1465-1477) never removes a stored row whose 
`expiry` is NULL. `isEvictionColumnNull` 
(StreamingSymmetricHashJoinExec.scala:747-755) screens only arriving rows, but 
4.3, whose join code matches the base branch, does store such rows: for a left 
outer join on `leftKey = rightKey AND rightTime BETWEEN leftTime AND expiry`, 
left (1, leftTime 100 s, expiry NULL) passes admission and is evicted by 
`leftTime <= cutoff`, emitting (1, null) once the watermark passes 100 s. After 
that checkpoint restarts on this version in the default mode, the row would 
stay in state forever and (1, null) would never be emitted; rows written on 
state formats 1 to 3 with allowMultiple=false are 
 stranded the same way once the default mode is restored. Only the inputs that 
outer joins preserve are affected, because the optimizer infers an IS NOT NULL 
filter on that column for every other input. Since a NULL in the tested column 
can never satisfy the condition, removing such stored rows in the same per-row 
eviction would emit them as unmatched, as 4.3 does.
   
   See **Shared repair plan 1** in the review body.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -362,6 +364,24 @@ case class StreamingSymmetricHashJoinExec(
   }
 
   protected override def doExecute(): RDD[InternalRow] = {
+    // Older versions order the V4 state of an input by its event time, so 
their checkpoints
+    // cannot evict that state by another column.
+    if (stateFormatVersion == 4 &&
+        conf.getConf(SQLConf.STREAMING_JOIN_STATE_V4_INDEX_VERSION) == 0) {
+      Seq((LeftSide, stateWatermarkPredicates.left, left.output),
+          (RightSide, stateWatermarkPredicates.right, right.output)).foreach {
+        case (side, predicate, attributes) =>
+          val eventTime = WatermarkSupport.findEventTimeColumnIndex(
+            attributes, allowMultipleEventTimeColumns = false)
+          stateValueWatermarkColumnOrdinal(predicate, attributes)
+            .filterNot(eventTime.contains).foreach { column =>

Review Comment:
   **Non-blocking (P2):** Because an input without its own watermark has no 
event time, this check now fails every state format 4 checkpoint of 4.3 in 
which such an input is range-bounded, including inner and left semi joins, 
where continuing is safe: their eviction emits no rows, so the old randomly 
bucketed rows would only stay in state as on 4.3, and lookups still find them 
through key prefix scans, since `scanRangeOffsets` 
(StreamingSymmetricHashJoinExec.scala:760-792) needs event times on both sides. 
For example, an inner join with a watermark only on `leftTime` and `leftKey = 
rightKey AND leftTime BETWEEN rightTime - INTERVAL 5 SECONDS AND rightTime + 
INTERVAL 5 SECONDS`, which returns correct matches on 4.3, would fail its first 
batch after the upgrade with STREAMING_JOIN_STATE_V4_CHECKPOINT_INCOMPATIBLE 
for the right side. The description and the migration guide state the failure 
but not why letting such sides continue is rejected. Failing only when the 
input is a preserved s
 ide of an outer join, where continuing would leave old unmatched rows 
unemitted, keeps the protection that matters, and a TODO there could name the 
state rewrite that would let the continuing joins evict their old rows.
   
   **Verification:**
   - **Regression:** An inner join with a watermark only on leftTime and 
`leftKey = rightKey AND leftTime BETWEEN rightTime - INTERVAL 5 SECONDS AND 
rightTime + INTERVAL 5 SECONDS`, and a left semi join with a watermark only on 
the right input, restart on state format 4 from a checkpoint whose index 
version was removed and still match rows buffered before the restart.
   - **Compatibility:** The left outer restart case for an input without its 
own watermark and the bounded-other-column case still fail with 
STREAMING_JOIN_STATE_V4_CHECKPOINT_INCOMPATIBLE naming the same side and column.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -261,28 +261,37 @@ object StreamingSymmetricHashJoinHelper extends Logging {
             eventTimeWatermarkForEviction.get,
             prevStateKeyWatermark)
         }
-      } else if (isWatermarkDefinedOnInput) { // case 2 in the 
StreamingSymmetricHashJoinExec docs
-        val stateValueWatermark = StreamingJoinHelper.getStateValueWatermark(
-          attributesToFindStateWatermarkFor = 
AttributeSet(oneSideInputAttributes),
-          attributesWithEventWatermark = 
AttributeSet(otherSideInputAttributes),
-          condition,
-          eventTimeWatermarkForEviction)
-        // A row can pass late-input filtering but already be eligible for 
eviction in this batch.
-        // When the previous join-derived state cutoff is ahead of the 
late-input watermark, a new
-        // row can fall at or below that cutoff. V4 must scan from the 
beginning to find such rows.
-        val prevStateValueWatermark = eventTimeWatermarkForLateEvents.flatMap 
{ lateWatermark =>
-          StreamingJoinHelper.getStateValueWatermark(
-            attributesToFindStateWatermarkFor = 
AttributeSet(oneSideInputAttributes),
-            attributesWithEventWatermark = 
AttributeSet(otherSideInputAttributes),
-            condition,
-            eventTimeWatermarkForLateEvents).filter(_ <= lateWatermark)
-        }
-        val inputAttributeWithWatermark = 
oneSideInputAttributes.find(_.metadata.contains(delayKey))
-        val expr = watermarkExpression(inputAttributeWithWatermark, 
stateValueWatermark)
-        expr.map { e =>
-          // watermarkExpression only provides the expression when 
eventTimeWatermarkForEviction
-          // is defined
-          JoinStateValueWatermarkPredicate(e, stateValueWatermark.get, 
prevStateValueWatermark)
+      } else if (isWatermarkDefinedOnInput || !useFirstEventTimeColumn) {
+        // case 2 in the StreamingSymmetricHashJoinExec docs. The opposite 
watermark bounds the
+        // future matches, so this input needs no watermark of its own, except 
in the legacy mode.
+        val eventTime = 
oneSideInputAttributes.find(_.metadata.contains(delayKey))
+        // The legacy mode with a single global watermark keeps applying a 
cutoff on any column of
+        // this input to the event time.
+        def solve(watermark: Option[Long]): Option[(Attribute, Long)] =
+          if (useFirstEventTimeColumn) {
+            StreamingJoinHelper.getStateValueWatermark(
+              attributesToFindStateWatermarkFor = 
AttributeSet(oneSideInputAttributes),
+              attributesWithEventWatermark = 
AttributeSet(otherSideInputAttributes),
+              condition,
+              watermark).map(eventTime.get -> _)
+          } else {
+            
StreamingJoinHelper.getStateValueWatermarkColumn(oneSideInputAttributes,
+              AttributeSet(otherSideInputAttributes), condition, watermark)
+          }
+        solve(eventTimeWatermarkForEviction).flatMap { case (column, 
stateValueWatermark) =>
+          // A row can pass late-input filtering but already be eligible for 
eviction in this
+          // batch. When the previous join-derived state cutoff is ahead of 
the late-input
+          // watermark, a new row can fall at or below that cutoff. V4 must 
scan from the
+          // beginning to find such rows. Late-input filtering bounds only the 
event time, so a
+          // cutoff on another column always scans from the beginning.
+          val prevStateValueWatermark = 
eventTimeWatermarkForLateEvents.flatMap { lateWatermark =>
+            solve(Some(lateWatermark)).collect {

Review Comment:
   **Non-blocking (P2):** This lower bound is valid only when the previous 
batch evicted with the same formula: `evictByTimestamp` requires every entry at 
or below it to be already evicted 
(SymmetricHashJoinStateManager.scala:191-196), and IncrementalExecution 
supplies the late watermark on the first batch after a restart too 
(IncrementalExecution.scala:606-611). For a state format 4 left outer join on 
`leftKey = rightKey AND leftTime > rightTime - INTERVAL 10 MINUTES AND expiry > 
rightTime - INTERVAL 1 HOUR`, 4.3 evicts left rows only at the watermark minus 
1 hour, while this formula evicts at minus 10 minutes, and the index-version 
check passes because the column is still `leftTime`. On the first batch after 
the upgrade the scan would start at the previous watermark minus 10 minutes, so 
left rows that 4.3 kept between minus 1 hour and minus 10 minutes, which can no 
longer match, would never be evicted and their (key, null) rows never emitted. 
Switching a state format 4 checkpoint f
 rom allowMultiple=false to the default does the same, and with an extra 
`CAST(lt AS LONG) > 10` conjunct the rows that 4.3 kept because of the constant 
stay stuck instead of being fixed.
   
   **Recommended change:** On the first batch of each query run, pass no 
previous late-event watermark to the join's predicate derivation, so that the 
first state format 4 eviction after a restart scans the secondary index from 
its start, while later batches of the run keep the bound; add join restart 
tests.
   
   **Why this works:** Adding IncrementalExecution's isFirstBatch flag to the 
condition that gates prevBatchLateEventsWm at IncrementalExecution.scala lines 
606-611 makes the lower bound empty for that batch, so evictByTimestamp scans 
once from the start and removes every row that the earlier run retained below 
the new cutoff; the bounds of the later batches tile again because the formula 
no longer changes within the run.
   
   **Risks:** Every state format 4 join with a watermark-based predicate, 
including joins the finding does not affect, scans its secondary index from the 
start once per query restart; the cost is bounded by the state size, matches 
what the first batch of a new query already does, and ends after that batch.
   
   **Constraints:** Later batches of the same run must keep the lower bound, so 
steady-state eviction keeps its range scan.
   
   **Exclusions:**
   - State format versions 1 to 3, whose eviction always visits every stored 
value.
   
   **Verification:**
   - **Regression:** A state format 4 left outer join on `leftKey = rightKey 
AND leftTime > rightTime - INTERVAL 10 MINUTES AND expiry > rightTime - 
INTERVAL 1 HOUR`, run with 
spark.sql.streaming.statefulOperator.allowMultiple=false until it buffers an 
unmatched left row whose leftTime lies between the legacy and the default 
cutoff and then restarted with the default, emits that row with nulls and 
removes it from state once the watermark passes it.
   - **Compatibility:** A state format 4 time-interval join stopped and 
restarted in the default mode produces the same output and state row counts as 
an uninterrupted run.



##########
docs/streaming/ss-migration-guide.md:
##########
@@ -25,6 +25,32 @@ Please refer [Migration Guide: SQL, Datasets and 
DataFrame](../sql-migration-gui
 
 ## Upgrading from Structured Streaming 4.3 to 4.4
 
+- Since Spark 4.4, a stream-stream join whose condition bounds an input with 
its own watermark
+  only through another TIMESTAMP column, for example `rightTime BETWEEN 
leftTime AND expiry`,
+  evicts the state of that input by the bounded column instead of its event 
time. Earlier versions
+  could emit outer join rows too early and lose matches. An outer or left semi 
join whose only such
+  bound is on a column that is not TIMESTAMP, such as a DATE column cast to 
TIMESTAMP, now fails
+  analysis. Such a join with state format version 4 cannot restart from a 
checkpoint of an earlier
+  version; start it with a new checkpoint. Rows that an earlier version 
evicted are not restored.
+  With `spark.sql.streaming.statefulOperator.allowMultiple` set to false, 
joins keep the earlier
+  behavior.
+
+- Since Spark 4.4, a range condition of a stream-stream join bounds the state 
of one input only
+  if the other input's watermarked column appears in it with a positive sign, 
for example

Review Comment:
   **Nit (P3):** Read literally, this rule contradicts the example on line 41: 
in `CAST(leftTime AS LONG) + CAST(rightTime AS LONG) > 100` the watermarked 
column appears with a plus sign, yet the condition no longer evicts state, 
because the code checks the sign after rewriting the conjunct into `watermark + 
c < leftTime` (StreamingJoinHelper.scala:210-217). Conversely, `CAST(leftTime 
AS LONG) - CAST(rightTime AS LONG) > -5` writes `rightTime` with a minus sign 
but still yields the cutoff `leftTime > watermark - 5 s`. Wording such as 'only 
if, solved for that input's column, the condition bounds it from below by an 
expression that rises with the other input's watermark' would match the code.
   
   **Verification:**
   - **Inspection:** Read against StreamingJoinHelper.scala lines 210-217, the 
reworded entry classifies `CAST(leftTime AS LONG) + CAST(rightTime AS LONG) > 
100` and `CAST(leftTime AS LONG) > 10` as not bounding state and `CAST(leftTime 
AS LONG) - CAST(rightTime AS LONG) > -5` as bounding it.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -722,6 +744,16 @@ case class StreamingSymmetricHashJoinExec(
     private[this] val allowMultipleStatefulOperators: Boolean =
       conf.getConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE)
 
+    // The join condition bounds the column that the value predicate tests, so 
a row with a NULL
+    // in it can never match, and the predicate never evicts it. The legacy 
mode tests the event
+    // time even when the condition bounds another column.
+    private[this] val isEvictionColumnNull: UnsafeRow => Boolean = 
stateWatermarkPredicate match {
+      case Some(JoinStateValueWatermarkPredicate(LessThanOrEqual(column, _), 
_, _))
+          if allowMultipleStatefulOperators =>

Review Comment:
   **Nit (P3):** This guard keeps the legacy behavior for rows with a NULL 
event time, but no new end-to-end suite sets 
`spark.sql.streaming.statefulOperator.allowMultiple=false`, and the only 
legacy-mode join test (StreamingJoinV4Suite, SPARK-56402) has no NULLs. Without 
the guard, a legacy-mode left row with a NULL `leftTime` under `leftKey = 
rightKey AND rightTime <= expiry` would be emitted on arrival or dropped, and 
its later match lost, although the base branch stores and matches it. A 
legacy-mode left outer join test with such a row would give the guard a failure 
signal.
   
   **Verification:**
   - **Compatibility:** In legacy mode a left outer join on `leftKey = rightKey 
AND rightTime <= expiry` keeps a left row whose leftTime is NULL, emits its 
match with a later right row whose rightTime is before expiry, and emits no 
early unmatched row for it, as on the base branch.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/SymmetricHashJoinStateManager.scala:
##########
@@ -268,12 +274,12 @@ class SymmetricHashJoinStateManagerV4(
   //   is unused if eviction is not possible (e.g., only one side defines a 
watermark in a time
   //   interval join). That would require propagating the predicate 
information here.
   private val hasEventTime: Boolean =
-    eventTimeColIdxOpt.isDefined || joinKeyOrdinalForWatermark.isDefined
+    timestampColIdxOpt.isDefined || joinKeyOrdinalForWatermark.isDefined

Review Comment:
   **Nit (P3):** With this PR an input without an event-time column can have an 
ordering column, the TIMESTAMP column its predicate tests, so this guard is now 
true for it and its rows go to the secondary index, but the comment above 
(lines 269-271) still says the index 'will never be used for eviction' without 
an event time column, and the comment in `extractEventTimeFn` (line 294) still 
ties random bucketing to a missing event time column. That invites a later 
optimization that skips the index for such inputs and silently stops their 
eviction. Rewording both comments around the ordering column and renaming 
`hasEventTime` would match the code.
   
   **Verification:**
   - **Inspection:** No comment or identifier in 
SymmetricHashJoinStateManagerV4 still says that the secondary index is skipped, 
or random bucketing used, merely because the input has no event-time column.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -117,6 +117,27 @@ object StreamingJoinHelper extends PredicateHelper with 
Logging {
     allStateWatermarks.reduceOption((x, y) => Math.min(x, y))
   }
 
+  /**
+   * Get the column that evicts the state of an input, with its state value 
watermark. That is the
+   * event time if the input has one and the condition bounds it, and 
otherwise the first other
+   * TIMESTAMP column in input order that the condition bounds. Each column is 
solved on its own,
+   * so the cutoff applies to the column that the condition bounds.
+   */
+  def getStateValueWatermarkColumn(
+      inputAttributes: Seq[Attribute],
+      attributesWithEventWatermark: AttributeSet,
+      joinCondition: Option[Expression],
+      eventWatermark: Option[Long]): Option[(Attribute, Long)] = {
+    val eventTime = inputAttributes.find(_.metadata.contains(delayKey))
+    val candidates = eventTime.toSeq ++ inputAttributes.filter { a =>

Review Comment:
   **Nit (P3):** The event-time-first order here decides the state format 4 
ordering column, which must agree with the event-time ranges that 
`scanRangeOffsets` (StreamingSymmetricHashJoinExec.scala:760-792) probes, and 
whether a 4.3 checkpoint passes the restart check, but no test exercises it: 
each new case bounds only one column of a watermarked input, and every test 
input lists `leftTime` before `expiry`, so plain input order would pick the 
same column. Without the preference, an input listing `expiry` first under 
`rightTime BETWEEN leftTime AND leftTime + INTERVAL 10 MINUTES AND rightTime <= 
expiry` would be ordered by `expiry` and lose matches in the range scan, and no 
test would fail. A helper-suite case with that input order, plus an end-to-end 
state format 4 join on that condition, would pin the preference.
   
   **Verification:**
   - **Behavior:** For an input listing expiry before leftTime and the 
condition `rightTime BETWEEN leftTime AND leftTime + INTERVAL 10 MINUTES AND 
rightTime <= expiry`, the chosen eviction column is leftTime, and a state 
format 4 left outer join on it finds every match within the 10-minute range 
across several batches.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -362,6 +364,24 @@ case class StreamingSymmetricHashJoinExec(
   }
 
   protected override def doExecute(): RDD[InternalRow] = {
+    // Older versions order the V4 state of an input by its event time, so 
their checkpoints
+    // cannot evict that state by another column.
+    if (stateFormatVersion == 4 &&
+        conf.getConf(SQLConf.STREAMING_JOIN_STATE_V4_INDEX_VERSION) == 0) {

Review Comment:
   **Non-blocking (P2):** This check trusts the recorded index version to 
describe the layout, but a state format 4 checkpoint started with 
`spark.sql.streaming.statefulOperator.allowMultiple=false` records version 1 
while its predicates, and so its ordering, follow the legacy rule: an input 
without its own watermark gets no predicate and random buckets, and a 
watermarked input bounded through `expiry` is ordered by `leftTime` 
(StreamingSymmetricHashJoinHelper.scala:264-276, 
SymmetricHashJoinStateManager.scala:257-277). allowMultiple is not in the 
offset log (OffsetSeq.scala:199-215), so a later restart with the default 
passes this check: the unindexed rows of a left outer join with a watermark 
only on `rightTime` would never be evicted or emitted, and `leftTime`-ordered 
rows would be evicted by the expiry cutoff, the 4.3 behavior for which a 4.3 
checkpoint of the same join is rejected. The conf's doc 
(SQLConf.scala:4406-4410) also says version 1 orders by the bounded column and 
vers
 ion 0 by the event time, which does not hold in legacy mode, and setting 0 for 
a new query selects no ordering; it only enables this check.
   
   **Recommended change:** Record index version 0 in the offset log for every 
batch that runs with spark.sql.streaming.statefulOperator.allowMultiple set to 
false, so that a checkpoint written in legacy mode is treated like a 4.3 
checkpoint by the restart check once the default mode is restored, and rewrite 
the doc of spark.sql.streaming.join.stateFormatV4.indexVersion to say that 0 
marks a checkpoint that may hold state ordered by the event time or not 
indexed, that 1 means ordering by the column the default mode evicts by, and 
that setting it does not select an ordering.
   
   **Why this works:** When OffsetSeqMetadata builds the confs for a batch, it 
writes 0 for the index version if allowMultiple is false and otherwise keeps 
the restored value, so the recorded version can only move from 1 to 0; on a 
later restart in the default mode, the pinned 0 makes the existing check reject 
the sides whose layout this version cannot evict correctly, exactly as for 4.3 
checkpoints.
   
   **Risks:** A state format 4 checkpoint that ever ran in legacy mode can no 
longer restart in the default mode for joins whose watermarked input is evicted 
by another column or whose preserved outer side has no watermark; such users 
must start a new checkpoint or stay in legacy mode, as with 4.3 checkpoints, 
and the recorded 0 cannot be undone.
   
   **Constraints:** The recorded version must never return from 0 to 1 
automatically. It must stay consistent with limiting the restart check, for 
inputs without their own watermark, to preserved outer sides, so that inner and 
left semi checkpoints written in legacy mode still restart.
   
   **Exclusions:**
   - Validating the ordering column across changes of the join condition, which 
the recovery semantics guide declares ill-defined.
   
   **Verification:**
   - **Regression:** A state format 4 left outer join with a watermark only on 
rightTime and `leftTime BETWEEN rightTime - INTERVAL 5 SECONDS AND rightTime + 
INTERVAL 5 SECONDS`, and one on `rightTime BETWEEN leftTime AND expiry`, 
started with spark.sql.streaming.statefulOperator.allowMultiple=false and 
restarted with the default, fail the restart with 
STREAMING_JOIN_STATE_V4_CHECKPOINT_INCOMPATIBLE instead of silently keeping the 
legacy eviction.
   - **Compatibility:** A query started and restarted in the default mode keeps 
recording index version 1 and restarts normally, and a query restarted in 
legacy mode from a version 1 checkpoint keeps running.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -708,20 +708,23 @@ object UnsupportedOperationChecker extends Logging {
   private def checkForStreamStreamJoinWatermark(join: Join): Unit = {
     val watermarkInJoinKeys = StreamingJoinHelper.isWatermarkInJoinKeys(join)
 
+    // Execution evicts the state of an input with its own watermark only by 
the column that

Review Comment:
   **Nit (P3):** The `else` branch of `hasValidRange` still accepts an input 
without its own watermark through a bound on any column, while execution evicts 
such an input only through a TIMESTAMP column that 
`getStateValueWatermarkColumn` picks (StreamingJoinHelper.scala:131-134). A 
left outer join with a watermark only on `rightTime` and `CAST(leftDate AS 
TIMESTAMP) BETWEEN rightTime - INTERVAL 1 DAY AND rightTime` therefore passes 
analysis, as the new UnsupportedOperationsSuite case pins, but its left rows 
are never evicted and its unmatched rows never emitted, as on the base branch. 
The PR description defers analysis rules for such inputs, but code readers 
cannot see that; a TODO at that branch naming the deferred TIMESTAMP-only rule 
would show it. This comment also covers only inputs with their own watermark, 
and 'such as not by a DATE column cast to TIMESTAMP' does not parse; 'not, for 
example, by a DATE column cast to TIMESTAMP' reads correctly.
   
   See **Shared repair plan 2** in the review body.



##########
docs/streaming/ss-migration-guide.md:
##########
@@ -25,6 +25,32 @@ Please refer [Migration Guide: SQL, Datasets and 
DataFrame](../sql-migration-gui
 
 ## Upgrading from Structured Streaming 4.3 to 4.4
 
+- Since Spark 4.4, a stream-stream join whose condition bounds an input with 
its own watermark
+  only through another TIMESTAMP column, for example `rightTime BETWEEN 
leftTime AND expiry`,
+  evicts the state of that input by the bounded column instead of its event 
time. Earlier versions
+  could emit outer join rows too early and lose matches. An outer or left semi 
join whose only such
+  bound is on a column that is not TIMESTAMP, such as a DATE column cast to 
TIMESTAMP, now fails
+  analysis. Such a join with state format version 4 cannot restart from a 
checkpoint of an earlier
+  version; start it with a new checkpoint. Rows that an earlier version 
evicted are not restored.
+  With `spark.sql.streaming.statefulOperator.allowMultiple` set to false, 
joins keep the earlier

Review Comment:
   **Nit (P3):** With `spark.sql.streaming.statefulOperator.allowMultiple` set 
to false, execution keeps the earlier eviction, but the analysis rule this 
entry lists does not: `hasValidRange` 
(UnsupportedOperationChecker.scala:713-720) never reads that setting. A 
legacy-mode left outer join whose watermarked left input is bounded only by 
`CAST(leftDate AS TIMESTAMP) > rightTime - INTERVAL 1 DAY` passes analysis on 
the base branch but fails with this change, with 'must bound its event time or 
another TIMESTAMP column', contrary to this sentence. Because such cutoffs can 
evict rows that later rows still match, keeping the error and narrowing this 
sentence to the eviction, for example 'joins keep the earlier eviction, but the 
analysis failure above still applies', resolves the contradiction without 
allowing a wrong result. The comment above `hasValidRange` 
(UnsupportedOperationChecker.scala:711-712) has the same gap: in legacy mode a 
cutoff from any column is still applied to the event 
 time.
   
   See **Shared repair plan 2** in the review body.



##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinOneSidedWatermarkSuite.scala:
##########
@@ -0,0 +1,84 @@
+/*
+ * 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.spark.sql.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
+import org.apache.spark.tags.SlowSQLTest
+
+@SlowSQLTest
+class StreamingJoinOneSidedWatermarkSuite extends StreamTest {
+  import testImplicits._
+
+  for {
+    version <- Seq(2, 3, 4)
+    joinType <- Seq("left_outer", "right_outer")

Review Comment:
   **Nit (P3):** Only outer joins run here, and this PR narrowed the 
SPARK-56406 inner join in StreamingJoinV4Suite so that its unwatermarked side 
gets no cutoff, so nothing end to end checks inner and left semi joins, whose 
state the PR also bounds: no assertion that their matches survive eviction or 
that the unwatermarked input's state shrinks, and no coverage of the inner-join 
branch that skips storing an unwatermarked right row already at or below its 
cutoff (StreamingSymmetricHashJoinExec.scala:932-955). Adding inner joins with 
a watermark on either input alone, and left semi joins with a watermark only on 
the right input (a watermark only on the left fails analysis), with state-row 
assertions across a restart, would cover them.
   
   **Verification:**
   - **Behavior:** For inner joins with a watermark on either input alone and 
left semi joins with a watermark only on the right input, with `leftTime 
BETWEEN rightTime - INTERVAL 5 SECONDS AND rightTime + INTERVAL 5 SECONDS`, 
every match within the range is emitted, including for rows that arrive below 
the cutoff, and the state of the input without a watermark shrinks once the 
other input's watermark passes its rows, on state formats 2 to 4 and after a 
restart.



##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinRangeEvictionSuite.scala:
##########
@@ -0,0 +1,311 @@
+/*
+ * 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.io.File
+import java.nio.charset.StandardCharsets.UTF_8
+import java.nio.file.Files
+
+import org.apache.hadoop.fs.Path
+import org.apache.logging.log4j.Level
+
+import org.apache.spark.sql.{AnalysisException, DataFrame, Row}
+import org.apache.spark.sql.catalyst.analysis.StreamingJoinHelper
+import org.apache.spark.sql.execution.streaming.checkpointing.{OffsetMap, 
OffsetSeq, OffsetSeqLog}
+import 
org.apache.spark.sql.execution.streaming.operators.stateful.join.StreamingSymmetricHashJoinExec
+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
+import org.apache.spark.tags.SlowSQLTest
+import org.apache.spark.util.Utils
+
+@SlowSQLTest
+class StreamingJoinRangeEvictionSuite extends StateStoreMetricsTest {
+  import testImplicits._
+
+  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)
+  }
+
+  // The left input has the event time leftTime and another TIMESTAMP column 
expiry. A negative
+  // end gives a NULL expiry.
+  private def joinWithExpiry(range: String, joinType: String)
+      : (MemoryStream[(Int, Long, Long)], MemoryStream[(Int, Long)], 
DataFrame) = {
+    val leftInput = MemoryStream[(Int, Long, Long)]
+    val rightInput = MemoryStream[(Int, Long)]
+    val left = leftInput.toDF().toDF("leftKey", "start", "end")
+      .select($"leftKey", timestamp_seconds($"start").as("leftTime"),
+        when($"end" >= 0, timestamp_seconds($"end")).as("expiry"))
+      .withWatermark("leftTime", "60 seconds")
+    val right = rightInput.toDF().toDF("rightKey", "time")
+      .select($"rightKey", timestamp_seconds($"time").as("rightTime"))
+      .withWatermark("rightTime", "60 seconds")
+    val condition = expr(s"leftKey = rightKey AND $range")
+    val joined = if (joinType == "right_outer") {
+      right.join(left, condition, joinType)
+    } else {
+      left.join(right, condition, joinType)
+    }
+    val result = joined.select($"leftKey", 
$"rightTime".cast("long").as("matchTime"),
+      $"leftTime".cast("long"))
+    (leftInput, rightInput, result)
+  }
+
+  // State format 3 shares the eviction code of format 2.
+  for {
+    version <- Seq(2, 4)
+    joinType <- Seq("inner", "left_outer", "right_outer")
+    shape <- Seq("between", "conjunction", "upper", "interval")
+  } {
+    test(s"range eviction uses the bounded column, V$version $joinType 
$shape") {
+      withJoinConf(version) {
+        val range = shape match {
+          case "between" => "rightTime BETWEEN leftTime AND expiry"
+          case "conjunction" => "rightTime >= leftTime AND rightTime <= expiry"
+          case "interval" => "rightTime BETWEEN leftTime AND leftTime + 
INTERVAL 10 MINUTES"
+          case _ => "rightTime <= expiry"
+        }
+        val (leftInput, rightInput, result) = joinWithExpiry(range, joinType)
+        testStream(result)(
+          StreamProgressLockedActions(Seq(
+            AddData(leftInput, (1, 100L, 700L), (2, 100L, 700L)), 
AddData(rightInput, (9, 100L)))),
+          CheckNewAnswer(),
+          StreamProgressLockedActions(Seq(
+            AddData(leftInput, (8, 400L, 1000L)), AddData(rightInput, (9, 
400L)))),
+          CheckNewAnswer(),
+          AddData(rightInput, (9, 400L)),
+          // The watermark has passed the start time, but the range has not 
expired.
+          CheckNewAnswer(),
+          Execute { query =>
+            val join = query.lastExecution.executedPlan.collectFirst {
+              case j: StreamingSymmetricHashJoinExec => j
+            }.get
+            assert(join.eventTimeWatermarkForEviction.contains(340000L))
+          },
+          AddData(rightInput, (1, 460L)),
+          CheckNewAnswer(Row(1, 460L, 100L)),
+          StreamProgressLockedActions(Seq(
+            AddData(leftInput, (8, 1000L, 1600L)), AddData(rightInput, (9, 
1000L)))),
+          CheckNewAnswer(),
+          AddData(rightInput, (9, 1100L)),
+          CheckNewAnswer((if (joinType != "inner") Seq(Row(2, null, 100L)) 
else Nil): _*)
+        )
+      }
+    }
+  }
+
+  for {
+    version <- Seq(2, 3, 4)
+    joinType <- Seq("left_outer", "right_outer")
+  } {
+    test(s"range eviction includes newly admitted expired values, V$version 
$joinType") {
+      withJoinConf(version) {
+        val (leftInput, rightInput, result) = joinWithExpiry("rightTime <= 
expiry", joinType)
+        testStream(result)(
+          StreamProgressLockedActions(Seq(
+            AddData(leftInput, (8, 100L, 700L)), AddData(rightInput, (9, 
100L)))),
+          CheckNewAnswer(),
+          StreamProgressLockedActions(Seq(
+            AddData(leftInput, (8, 400L, 1000L)), AddData(rightInput, (9, 
400L)))),
+          CheckNewAnswer(),
+          AddData(rightInput, (9, 400L)), CheckNewAnswer(),
+          // The start passes late filtering, but expiry is below the previous 
eviction cutoff.
+          AddData(leftInput, (3, 460L, 200L)), CheckNewAnswer(Row(3, null, 
460L)),
+          AddData(rightInput, (9, 500L)), CheckNewAnswer())
+      }
+    }
+  }
+
+  for {
+    version <- Seq(2, 4)
+    joinType <- Seq("left_outer", "right_outer")
+  } {
+    test(s"a row whose range-eviction column is NULL is emitted on arrival, 
V$version $joinType") {
+      withJoinConf(version) {
+        val (leftInput, rightInput, result) =
+          joinWithExpiry("rightTime BETWEEN leftTime AND expiry", joinType)
+        testStream(result)(
+          // The row can never match, and the eviction predicate on expiry 
never removes it.
+          StreamProgressLockedActions(Seq(
+            AddData(leftInput, (1, 100L, -1L), (2, 100L, 700L)), 
AddData(rightInput, (2, 150L)))),
+          CheckNewAnswer(Row(1, null, 100L), Row(2, 150L, 100L)),
+          assertNumStateRows(total = 2, updated = 2))
+      }
+    }
+  }
+
+  // In state format 4, the extra conjunct gives the right side a value 
predicate on rightTime, so
+  // that the range scan of the right joiner solves the bound that shifts by a 
column.
+  for {
+    bound <- Seq("leftTime > rightTime + rightDelay",
+      "CAST(leftTime AS BIGINT) + leftOffset > CAST(rightTime AS BIGINT)")
+    version <- Seq(2, 4)
+  } {
+    test(s"range eviction does not log solver errors for other columns: 
$bound, V$version") {
+      val logAppender = new LogAppender("stream-stream join state constraints")
+      withLogAppender(logAppender,
+          loggerNames = 
Seq(StreamingJoinHelper.getClass.getName.stripSuffix("$")),
+          level = Some(Level.WARN)) {
+        withJoinConf(version) {
+          val leftInput = MemoryStream[(Int, Long, Long)]
+          val rightInput = MemoryStream[(Int, Long, Int)]
+          val left = leftInput.toDF().toDF("leftKey", "time", "leftOffset")
+            .select($"leftKey", timestamp_seconds($"time").as("leftTime"), 
$"leftOffset")
+            .withWatermark("leftTime", "0 seconds")
+          val right = rightInput.toDF().toDF("rightKey", "time", "delay")
+            .select($"rightKey", timestamp_seconds($"time").as("rightTime"),
+              ($"delay" * expr("INTERVAL 1 SECOND")).as("rightDelay"))
+            .withWatermark("rightTime", "0 seconds")
+          val extra = if (version == 4) " AND leftTime < rightTime + INTERVAL 
1 HOUR" else ""
+          val joined = left.join(right, expr(s"leftKey = rightKey AND 
$bound$extra"))
+            .select($"leftKey", $"leftTime".cast("long"), 
$"rightTime".cast("long"))
+          testStream(joined)(
+            StreamProgressLockedActions(Seq(
+              AddData(leftInput, (1, 20L, 0L)), AddData(rightInput, (1, 10L, 
5)))),
+            CheckNewAnswer(Row(1, 20L, 10L)),
+            AddData(rightInput, (2, 30L, 1)),
+            CheckNewAnswer())
+        }
+      }
+      // A per-row column leaves the bound unknown, which is not an error.
+      assert(!logAppender.loggingEvents.exists(
+        _.getMessage.getFormattedMessage.contains("Error trying to extract 
state constraint")))
+    }
+  }
+
+  private val indexVersionKey = 
SQLConf.STREAMING_JOIN_STATE_V4_INDEX_VERSION.key
+
+  private def indexVersion(checkpoint: File): Option[String] = {
+    new OffsetSeqLog(spark, new File(checkpoint, 
"offsets").getCanonicalPath).getLatest().get._2
+      .metadataOpt.get.conf.get(indexVersionKey)
+  }
+
+  // Removes the V4 index version from the latest offset log entry, as older 
versions wrote it.
+  private def removeIndexVersion(checkpoint: File): Unit = {
+    val offsetsPath = new File(checkpoint, "offsets").getCanonicalPath
+    val log = new OffsetSeqLog(spark, offsetsPath)
+    val (batchId, offsets) = log.getLatest().get
+    val updated = offsets match {
+      case o: OffsetSeq =>
+        o.copy(metadataOpt = o.metadataOpt.map(m => m.copy(conf = m.conf - 
indexVersionKey)))
+      case o: OffsetMap =>
+        o.copy(metadata = o.metadata.copy(conf = o.metadata.conf - 
indexVersionKey))
+    }
+    val path = new Path(offsetsPath, batchId.toString)
+    assert(path.getFileSystem(spark.sessionState.newHadoopConf()).delete(path, 
false))
+    assert(log.add(batchId, updated))
+  }
+
+  // Copies a bundled checkpoint and points the copied operator metadata at 
the state schema files
+  // of the copy. The bundled metadata names them under the placeholder 
directory /checkpoint.
+  private def copyCheckpointFixture(name: String, checkpoint: File): Unit = {
+    Utils.copyDirectory(
+      new File(getClass.getResource(s"/structured-streaming/$name/").toURI), 
checkpoint)
+    val metadataDir = new File(checkpoint, "state/0/_metadata/v2")
+    metadataDir.listFiles().filter(f => f.isFile && 
!f.getName.startsWith(".")).foreach { file =>
+      val metadata = new String(Files.readAllBytes(file.toPath), UTF_8)
+      val updated = metadata.replace("file:/checkpoint/", new 
Path(checkpoint.toURI).toString + "/")
+      assert(updated != metadata, s"No state schema file is named in $file")
+      Files.write(file.toPath, updated.getBytes(UTF_8))
+    }
+  }
+
+  test("V4 restart from an older checkpoint keeps evicting by the event time") 
{
+    withJoinConf(4) {
+      withTempDir { checkpoint =>
+        val (leftInput, rightInput, result) = joinWithExpiry(
+          "rightTime BETWEEN leftTime AND leftTime + INTERVAL 10 MINUTES", 
"left_outer")
+        testStream(result)(
+          StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+          StreamProgressLockedActions(Seq(
+            AddData(leftInput, (1, 100L, 700L)), AddData(rightInput, (9, 
100L)))),
+          CheckNewAnswer(),
+          StopStream)
+        assert(indexVersion(checkpoint) === Some("1"))
+        removeIndexVersion(checkpoint)
+        testStream(result)(
+          StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+          AddData(rightInput, (1, 160L)),
+          CheckNewAnswer(Row(1, 160L, 100L)),

Review Comment:
   **Nit (P3):** After the restart this test only checks that right (1, 160) 
matches; the watermark never passes `leftTime + 10 minutes` for an unmatched 
row, so a change that dropped the predicate or stopped evicting on an 
index-version-0 restart would still pass despite the test's name. Both 
failing-restart tests also put the offending input on the left, which leaves 
the right-side element of the check in `doExecute` 
(StreamingSymmetricHashJoinExec.scala:371-372) without a failure signal. 
Advancing the watermark past an unmatched row after the restart, and adding a 
right outer join whose preserved right input has no watermark, would cover both.
   
   **Verification:**
   - **Behavior:** After restarting the left outer join on `rightTime BETWEEN 
leftTime AND leftTime + INTERVAL 10 MINUTES` from a checkpoint without the 
index version, an unmatched left row is emitted with nulls once the watermark 
passes leftTime + 10 minutes, and a right outer join whose right input has no 
watermark fails the same kind of restart with 
STREAMING_JOIN_STATE_V4_CHECKPOINT_INCOMPATIBLE naming the right side.



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