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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -262,27 +262,34 @@ object StreamingSymmetricHashJoinHelper extends Logging {
             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)
+        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):** Choosing expiry here keeps a left row buffered until 
expiry passes. But produceOutputWatermark 
(StreamingSymmetricHashJoinExec.scala:1160-1176) is unchanged and still takes 
the left state watermark from getStateWatermark's whole-input solve, which for 
`rightTime BETWEEN leftTime AND expiry` is the input watermark minus 1 ms. So 
the join tells downstream operators that no older row will follow, and then 
emits rows with old leftTime values. Take the PR's own test batches followed by 
`groupBy(window(leftTime, '1 minute')).count()` in Append mode. Before this 
change both outer rows for leftTime 100 s were emitted at watermark 340 s and 
counted in window [60 s, 120 s). With this change, by the review's reading of 
the code, the match at 460 s and the later outer row reach the aggregation 
after its late-events watermark has reached 339.999 s. Both are dropped as 
late, and that window is never emitted. The same applies to an input bounded 
only through a non-TIMESTAMP co
 lumn, which is now never evicted.
   
   **Recommended change:** In UnsupportedOperationChecker, treat a 
stream-stream join as an operator that can emit late rows when, in the default 
mode, an input with its own watermark whose rows the join emits (both inputs, 
or the left input of a left semi join) has a bound under the whole-input solve, 
but the eviction column the default mode picks for it is not its event time, 
either another TIMESTAMP column or none for a bound only through a 
non-TIMESTAMP column. checkStreamingQueryGlobalWatermarkLimit then rejects a 
stateful operator after such a join, or warns when 
spark.sql.streaming.statefulOperator.checkCorrectness.enabled is false. Take 
the eviction column from the mode-aware helper in StreamingJoinHelper that the 
analysis range check and the V4 restart check also use. Add a sentence to the 
4.3-to-4.4 Structured Streaming migration notes, plus analysis-checker and 
multi-operator streaming join tests.
   
   **Why this works:** The join's output watermark stays as it is, but a query 
whose downstream stateful operator would silently drop the rows such a join 
emits late no longer starts without an explicit choice: it fails with the 
existing correctness error, or runs with a warning when the user disables the 
check, the contract other operators that can emit late rows already follow.
   
   **Compatibility:** The join's own eviction by the bounded column and its 
output watermark stay as the PR makes them; only whether a stateful operator 
may follow such a join changes.
   
   **Risks:** Queries that chain a stateful operator after a join whose 
watermarked input is bounded only through another column, and that ran on the 
base branch with wrong join results, now fail at start unless 
spark.sql.streaming.statefulOperator.checkCorrectness.enabled is set to false, 
which runs them with a warning and the late-row drops; the migration note must 
say so. Like the existing check for other operators that can emit late rows, 
the new case flags any stateful operator after such a join, including one keyed 
on the other input's event time, whose rows are not late; disabling the check 
runs those queries with a warning.
   
   **Constraints:** The new case applies only in the default mode and only to 
inputs whose eviction the PR moved off the event time, so time-interval joins 
bounded through their event times, inputs without their own watermark, join-key 
watermarks, and the legacy mode pass the check as on the base branch.
   
   **Exclusions:**
   - Holding back the join's output watermark itself, which needs run-time 
tracking of the oldest buffered event time.
   
   **Verification:**
   - **Regression:** A left outer join on `rightTime BETWEEN leftTime AND 
expiry` with watermarks on both inputs, followed by an Append-mode window 
aggregation on leftTime, fails analysis with the existing correctness error, 
and with the correctness check disabled it starts and logs the warning.
   - **Regression:** An inner join whose watermarked input is bounded only 
through a DATE column cast to TIMESTAMP is flagged the same way when a stateful 
operator follows it.
   - **Compatibility:** A time-interval join bounded through both event times 
followed by a window aggregation, and a join on a watermarked join key followed 
by an aggregation, still pass the check, and the new case does not fire for the 
expiry-bounded join when spark.sql.streaming.statefulOperator.allowMultiple is 
false.



##########
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
+    // getStateValueWatermarkColumn picks, such as not by a DATE column cast 
to TIMESTAMP.
+    def hasValidRange(input: LogicalPlan, other: LogicalPlan): Boolean =
+      if 
(input.output.exists(_.metadata.contains(EventTimeWatermark.delayKey))) {
+        StreamingJoinHelper.getStateValueWatermarkColumn(

Review Comment:
   **Non-blocking (P2):** This check never reads 
`spark.sql.streaming.statefulOperator.allowMultiple`. With it set to false, 
getStateWatermarkPredicates still takes the `useFirstEventTimeColumn` branch: 
it solves over all of the input's columns and evicts by the event time exactly 
as before. A left outer join whose only bound is `CAST(leftDate AS TIMESTAMP) > 
rightTime` would therefore run unchanged, yet it now fails analysis, on start 
and on restart, with the extended `_LEGACY_ERROR_TEMP_3102` message. That 
contradicts the migration note's 'With 
`spark.sql.streaming.statefulOperator.allowMultiple` set to false, joins keep 
the earlier behavior.' The comments at 
UnsupportedOperationChecker.scala:711-712 and 
UnsupportedOperationsSuite.scala:562-563 also describe only the default mode, 
and the new checker cases run only in that mode.
   
   **Verification:**
   - **Regression:** Left outer, right outer, full outer, and left semi joins 
bounded only through a DATE column cast to TIMESTAMP of a watermarked input 
pass analysis with spark.sql.streaming.statefulOperator.allowMultiple set to 
false.
   - **Compatibility:** With the default setting the same joins still fail with 
the message that the range condition must bound the event time or another 
TIMESTAMP column, and joins bounded through another TIMESTAMP column still pass.



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

Review Comment:
   **Blocking (P1):** This screen runs only over rows that arrive in the batch. 
A state format 1-3 checkpoint from an earlier version can already hold 
preserved-side rows with a NULL in the column the predicate now tests, because 
that version evicted by the event time and stored every row that passed the 
pre-join filter. Take `rightTime BETWEEN leftTime AND expiry`, with a left row 
(1, 100 s, expiry NULL) stored on 4.3 and the query restarted on this version. 
Once the watermark reaches 340 s the row is tested with `expiry <= 339999 ms`, 
which is NULL, so evictAndReturnByValueCondition never returns it. The row 
stays in state for good and `(1, null, 100 s)` is never emitted, where 4.3 
evicted the row by leftTime and emitted it. Rows stored while 
`spark.sql.streaming.statefulOperator.allowMultiple` was false hit the same gap 
when the setting is switched back.
   
   **Recommended change:** In OneSideHashJoiner, when the default mode builds a 
`column <= cutoff` value predicate, evict a buffered row on state formats 1-3 
when that column is NULL as well as when it is at or below the cutoff, reusing 
the column isEvictionColumnNull already extracts, and add join tests that 
restart a state format 2 outer join from a checkpoint holding a row whose 
bounded column is NULL.
   
   **Why this works:** Restored rows that can never match then leave state at 
the first eviction pass, and on an outer join's preserved input they are 
emitted as unmatched rows, as the PR's NULL rule already does for arriving rows.
   
   **Risks:** An upgraded state format 1-3 outer join whose checkpoint holds 
rows with a NULL event time under an event-time predicate, which the base 
branch kept forever without output, now evicts them in the first eviction pass 
and emits their outer rows, consistent with the NULL rule for arriving rows.
   
   **Constraints:** The legacy mode keeps the base branch's eviction, so the 
NULL eviction applies only in the default mode.
   
   **Verification:**
   - **Regression:** A state format 2 left outer join on `rightTime BETWEEN 
leftTime AND expiry` that stores a left row with a NULL expiry while 
spark.sql.streaming.statefulOperator.allowMultiple is false, then restarts in 
the default mode, emits that row's outer row in the first batch after the 
restart and keeps no state row for it.
   - **Compatibility:** With allowMultiple set to false a row with a NULL 
eviction column stays in state as on the base branch, and in the default mode 
rows whose eviction column is not NULL are evicted at the same watermark as 
before the change.



##########
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 own watermark, 
with its state value
+   * watermark. That is the event time if 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:
   **Non-blocking (P2):** The candidate order here is load-bearing. In state 
format 4 the range probe applies event-time offsets to the other input's index, 
which is now ordered by that input's eviction column, and the index-version-0 
restart check passes only while that column is the event time. Every test, new 
and existing (including the StreamingJoinSuite 'matching scan on event time' 
cases), bounds exactly one column of each watermarked input, so swapping the 
order would still pass. For example, with `rightTime BETWEEN leftTime AND 
leftTime + INTERVAL 10 MINUTES AND rightTime <= expiry` on V4, the left index 
would be keyed by expiry while the right side probes it with leftTime offsets, 
missing most matches. A solver case and a V4 join case that bound both leftTime 
and expiry would pin the order.
   
   **Verification:**
   - **Behavior:** For a condition that bounds both leftTime and expiry of a 
watermarked input, the eviction column is leftTime with the event-time cutoff, 
and a state format 4 inner and left outer join over it return every match the 
condition admits, including matches whose expiry is well after the right event 
time.



##########
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 runs only for index version 0. But a new 
V4 query records version 1 even when 
`spark.sql.streaming.statefulOperator.allowMultiple=false` orders its index by 
the event time, and that setting is not in OffsetSeqMetadata.relevantSQLConfs. 
Take a left outer join on `rightTime BETWEEN leftTime AND expiry` started in 
the legacy mode and restarted with the default. The predicate becomes `expiry 
<= cutoff`, this check is skipped, and evictByTimestamp scans carried-over 
entries that are keyed by leftTime. A row with leftTime 10:00 and expiry 12:00 
is evicted at a right watermark of 10:30, so a right row at 11:00 never matches 
it and the null row is emitted early. The conf doc at SQLConf.scala:4406-4410 
also misstates both versions. It says version 1 orders by the column the 
condition bounds, which is false in the legacy mode. It says version 0 fails 
whenever the condition bounds another column, but it fails only when the 
condition does not bound the event 
 time.
   
   **Recommended change:** When a query starts without an offset log and 
spark.sql.streaming.statefulOperator.allowMultiple is false, record 
spark.sql.streaming.join.stateFormatV4.indexVersion as 0, the event-time 
ordering the legacy mode uses, in MicroBatchExecution's start path; a restart 
keeps the recorded value as today. Extend the restart check in 
StreamingSymmetricHashJoinExec.doExecute so that version 0 requires the 
predicate column to be the event time, as now, and version 1 requires it to be 
the column the default mode picks, taken from the mode-aware helper in 
StreamingJoinHelper that the analysis checks also use, failing with 
STREAMING_JOIN_STATE_V4_CHECKPOINT_INCOMPATIBLE otherwise. Reword that error so 
it also covers a change of spark.sql.streaming.statefulOperator.allowMultiple, 
correct the conf's doc for both versions, and add restart tests for both mode 
switches.
   
   **Why this works:** The record then states the ordering the state actually 
has, and the check compares it with the ordering the current run would append 
and evict by in either mode, so a mode switch that would evict rows by a column 
they are not indexed by fails with the request for a new checkpoint instead of 
silently evicting them early.
   
   **Compatibility:** Default-mode V4 queries and checkpoints written before 
this change restart exactly as with the current patch.
   
   **Risks:** A V4 query started with allowMultiple=false and later run in the 
default mode, or the reverse, now fails at its first batch with the request to 
start a new checkpoint when the two modes order its state by different columns, 
where today it runs and evicts rows early; queries whose modes agree on the 
column keep running.
   
   **Constraints:** Queries started in the default mode keep recording version 
1, and checkpoints without the entry keep reading version 0, so existing 
restarts behave as today.
   
   **Exclusions:**
   - Migrating existing V4 state to another ordering, which would rewrite 
persisted state.
   
   **Verification:**
   - **Regression:** A V4 left outer join on `rightTime BETWEEN leftTime AND 
expiry` started with spark.sql.streaming.statefulOperator.allowMultiple set to 
false and restarted with the default fails with the incompatible-checkpoint 
error for the left side and `expiry`.
   - **Regression:** The same join started in the default mode and restarted 
with allowMultiple set to false fails with the same error.
   - **Compatibility:** A V4 time-interval join bounded through both event 
times restarts normally across both mode switches, a new default-mode query 
still records version 1, and a checkpoint without the entry still restarts as 
version 0.



##########
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 =>
+        Predicate.create(IsNull(column), inputAttributes).eval _

Review Comment:
   **Nit (P3):** This screen also applies when the predicate tests the event 
time, as in `rightTime BETWEEN leftTime AND leftTime + INTERVAL 10 MINUTES`. A 
left outer join now emits a row with a NULL leftTime on arrival, where state 
formats 1-3 kept it in state for good. The only NULL case in 
StreamingJoinRangeEvictionSuite uses expiry, so limiting the screen to 
non-event-time columns would pass every test. One interval-join case with a 
NULL event time on state formats 2 and 4 would pin it.
   
   **Verification:**
   - **Behavior:** On state formats 2 and 4, a left outer join on an interval 
condition emits a left row whose event time is NULL as an outer row in the 
batch it arrives in and keeps no state row for it.



##########
docs/streaming/ss-migration-guide.md:
##########
@@ -25,6 +25,16 @@ 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

Review Comment:
   **Nit (P3):** 'Such a join' follows the sentence about the outer or left 
semi join that 'now fails analysis', so it reads as that rejected join, for 
which a restart is moot. The restart failure in 
StreamingSymmetricHashJoinExec.doExecute is for the join of the first sentence, 
bounded through another TIMESTAMP column. 'Rows that an earlier version evicted 
are not restored' applies to such joins on state formats 2 and 3. Naming the 
join each sentence applies to would let users with state format 4 queries see 
that they need a new checkpoint.
   
   **Verification:**
   - **Inspection:** The 4.3-to-4.4 note in 
docs/streaming/ss-migration-guide.md names the join each consequence applies 
to: the analysis failure for outer and left semi joins bounded only through a 
non-TIMESTAMP column, the restart failure for state format 4 joins bounded 
through another TIMESTAMP column, and the evicted-rows sentence for such joins 
on state formats 2 and 3.



##########
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
+    // getStateValueWatermarkColumn picks, such as not by a DATE column cast 
to TIMESTAMP.

Review Comment:
   **Nit (P3):** 'such as not by a DATE column cast to TIMESTAMP' does not 
parse, because 'such as' introduces an example of what is included. 'and so not 
by' states the intended exclusion:
   
   ```suggestion
       // getStateValueWatermarkColumn picks, and so not by a DATE column cast 
to TIMESTAMP.
   ```
   
   **Verification:**
   - **Inspection:** The comment at UnsupportedOperationChecker.scala:711-712 
no longer contains 'such as not by' and states that a DATE column cast to 
TIMESTAMP is not an eviction column.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -262,27 +262,34 @@ object StreamingSymmetricHashJoinHelper extends Logging {
             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)
+        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):** After a restart, IncrementalExecution supplies the 
late-events watermark as soon as the previous batch's offset metadata exists. 
This lower bound is therefore recomputed with the new event-time-only rule, 
while the checkpoint was evicted with the old rule's lower minimum over all 
bounded columns. Take a V4 left outer join on `leftTime >= rightTime - INTERVAL 
10 MINUTES AND leftExpiry >= rightTime - INTERVAL 1 HOUR` restarted from a 4.3 
checkpoint. 4.3 evicted left rows up to W - 1 h - 1 ms. The restart check 
passes because the eviction column is still leftTime, and the first scan starts 
at W_prev - 10 min - 1 ms. Left rows with leftTime in (W_prev - 1 h, W_prev - 
10 min] are never scanned again, which breaks the startTimestamp contract of 
evictByTimestamp (SymmetricHashJoinStateManager.scala:191-194). The same 
happens when a V4 query run with 
`spark.sql.streaming.statefulOperator.allowMultiple=false` is restarted with 
the default.
   
   **Recommended change:** In IncrementalExecution's stream-stream join rule, 
also require that the previous batch ran in this execution (isFirstBatch is 
false) before passing the late-events watermark as the scan lower bound, so the 
first batch after any restart scans the V4 index from its start, and add V4 
restart tests that cover the band between the earlier and the new cutoff.
   
   **Why this works:** The first batch of a run then evicts every entry at or 
below its own cutoff, whatever cutoff the run that wrote the checkpoint used, 
which restores the guarantee evictByTimestamp requires for the lower bound of 
every later batch.
   
   **Risks:** Every restart of a V4 join with a value or join-key eviction 
bound scans its index from the start once, in its first batch, through any 
delete markers left since the last compaction, before the lower bound resumes; 
the cost is bounded per restart and results do not change.
   
   **Constraints:** Batches after the first in a run keep the lower bound, so 
steady-state eviction cost is unchanged.
   
   **Verification:**
   - **Regression:** A V4 left outer join on `leftTime >= rightTime - INTERVAL 
10 MINUTES AND expiry >= rightTime - INTERVAL 1 HOUR`, run with 
spark.sql.streaming.statefulOperator.allowMultiple set to false and restarted 
with the default, emits the outer rows of unmatched left rows whose leftTime 
lies between the one-hour and the ten-minute cutoffs, and keeps none of them in 
state.
   - **Compatibility:** A new case shows that the scan lower bound is absent in 
the first batch after a restart and present again in the batch after it, so 
steady-state batches keep scanning from the previous cutoff.



##########
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):** The `if allowMultipleStatefulOperators` guard here is one of 
three legacy-mode branches. The other two are the `useFirstEventTimeColumn` 
solve in getStateWatermarkPredicates and the V4 index column that follows the 
event-time predicate. Only StreamingSymmetricHashJoinHelperSuite checks the 
legacy mode, by asserting the predicate's column. The SPARK-56402 case in 
StreamingJoinV4Suite runs a join with allowMultiple=false, but its condition 
bounds only the event times and has no NULL event time, so it cannot tell the 
legacy branches from the default ones. Dropping this guard, or letting the 
legacy V4 index follow the bounded column, would pass every test. A legacy-mode 
run of the between shape on state formats 2 and 4, with a NULL event-time row, 
would pin all three.
   
   **Verification:**
   - **Compatibility:** With spark.sql.streaming.statefulOperator.allowMultiple 
set to false, the between-shape join on state formats 2 and 4 produces the base 
branch's output for the PR's test batches, including the early outer row, and a 
row with a NULL event time is added to the state when it arrives, as on the 
base branch, instead of being emitted at once under the NULL rule.



##########
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
+    // getStateValueWatermarkColumn picks, such as not by a DATE column cast 
to TIMESTAMP.
+    def hasValidRange(input: LogicalPlan, other: LogicalPlan): Boolean =
+      if 
(input.output.exists(_.metadata.contains(EventTimeWatermark.delayKey))) {
+        StreamingJoinHelper.getStateValueWatermarkColumn(
+          input.output, other.outputSet, join.condition, 
Some(1000000)).isDefined
+      } else {
+        StreamingJoinHelper.getStateValueWatermark(
+          input.outputSet, other.outputSet, join.condition, 
Some(1000000)).isDefined
+      }
+
     // Check if the nullable side has a watermark, and there's a range 
condition which
     // implies a state value watermark on the first side.
     val hasValidWatermarkRange = join.joinType match {
-      case LeftOuter | LeftSemi => StreamingJoinHelper.getStateValueWatermark(
-        join.left.outputSet, join.right.outputSet, join.condition, 
Some(1000000)).isDefined
-      case RightOuter => StreamingJoinHelper.getStateValueWatermark(
-        join.right.outputSet, join.left.outputSet, join.condition, 
Some(1000000)).isDefined
-      case FullOuter =>
-        Seq((join.left.outputSet, join.right.outputSet),
-          (join.right.outputSet, join.left.outputSet)).exists {
-          case (attributesToFindStateWatermarkFor, 
attributesWithEventWatermark) =>
-            
StreamingJoinHelper.getStateValueWatermark(attributesToFindStateWatermarkFor,
-              attributesWithEventWatermark, join.condition, 
Some(1000000)).isDefined
-        }
+      case LeftOuter | LeftSemi => hasValidRange(join.left, join.right)
+      case RightOuter => hasValidRange(join.right, join.left)
+      case FullOuter => hasValidRange(join.left, join.right) || 
hasValidRange(join.right, join.left)

Review Comment:
   **Blocking (P1):** With the default 
`spark.sql.streaming.statefulOperator.allowMultiple=true`, this case accepts a 
full outer join when either input has an eviction column. Because 
getStateValueWatermarkColumn considers only TIMESTAMP columns, an input bounded 
only through a column cast to TIMESTAMP now gets no value predicate. The full 
outer branch (StreamingSymmetricHashJoinExec.scala:554-580) emits that input's 
unmatched rows only from removeAndReturnOldState, so they are never emitted. 
For example, `orders FULL OUTER JOIN promos ON orderKey = promoKey AND 
orderTime >= promoTime AND CAST(promoEndDate AS TIMESTAMP) >= orderTime` passes 
because orders is bounded through orderTime. A promo that no order matches then 
stays in state for good, and its null-padded row is never emitted. Before this 
change the whole-input solve evicted promos by promoTime and emitted that row. 
Restarted checkpoints switch silently, because the V4 restart check sees no 
predicate. The PR says its new anal
 ysis error is for joins that 'would otherwise never emit its unmatched rows', 
but for a full outer join the check looks at only one input.
   
   **Recommended change:** In checkForStreamStreamJoinWatermark, for a 
stream-stream full outer join without a watermark in its join keys, also fail 
analysis with the existing range-condition message when an input with its own 
watermark has a bound under the whole-input solve, the bound the base branch 
evicted it by, but no eviction column in the active mode, taken from the 
mode-aware helper in StreamingJoinHelper that the other analysis checks and the 
V4 restart check use. An input with no bound at all keeps passing as on the 
base branch, and in the legacy mode, which still evicts such an input by its 
event time, the helper returns a column, so nothing new fails there. Extend the 
migration note's analysis-failure sentence to full outer joins and add 
analysis-checker tests.
   
   **Why this works:** A full outer join whose input the default mode would 
never evict, and whose unmatched rows from that input would therefore never be 
emitted, fails before it starts with the message the PR already gives for left 
and right outer joins, instead of running and silently losing those rows.
   
   **Compatibility:** Left outer, right outer, and left semi joins keep the 
check as the PR writes it, and the full outer joins that still pass evict and 
emit exactly as with the current patch.
   
   **Risks:** A full outer join that ran on the base branch with such an input 
now fails when it starts or restarts, until its condition bounds that input 
through its event time or another TIMESTAMP column or the input is evicted by 
its bounded expression; on the base branch it ran with early unmatched rows and 
lost matches for that input.
   
   **Constraints:** The new case applies only in the default mode and only to 
an input that the whole-input solve bounds but that gets no eviction column, so 
full outer joins whose inputs are bounded through TIMESTAMP columns, whose 
second input has no bound at all, or whose join keys carry the watermark, and 
every join in the legacy mode, pass as on the base branch.
   
   **Exclusions:**
   - Evicting an input by the cast expression that bounds it, the design the 
open question about TIMESTAMP-only eviction columns offers.
   
   **Verification:**
   - **Regression:** In the default mode, a full outer join on `leftKey = 
rightKey AND leftTime >= rightTime AND CAST(rightDate AS TIMESTAMP) >= 
leftTime` with watermarks on leftTime and rightTime fails analysis with the 
range-condition message, and so do the same join with its inputs swapped and 
the same join with a TIMESTAMP_NTZ or numeric column in place of the DATE 
column.
   - **Compatibility:** A full outer join whose inputs are both bounded through 
TIMESTAMP columns, one whose second input has its own watermark but no bound at 
all, and one with a watermark in its join keys still pass analysis, and the 
DATE-bounded join above passes with 
spark.sql.streaming.statefulOperator.allowMultiple set to false.



##########
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 own watermark, 
with its state value
+   * watermark. That is the event time if 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 =>
+      a.dataType == TimestampType && !eventTime.exists(_.semanticEquals(a))

Review Comment:
   **Nit (P3):** The exact `TimestampType` check here also excludes 
TIMESTAMP_NTZ columns. That matters because the cutoff is in UTC microseconds 
while NTZ values are local time. The new UnsupportedOperationsSuite block pins 
only a DATE cast and a TIMESTAMP column, so widening this to any timestamp type 
would pass every test. NTZ-bounded outer joins would then be silently accepted 
and evicted with a cutoff shifted by the session time-zone offset. One 
TIMESTAMP_NTZ case in the checker block and in the solver tests would pin it.
   
   **Verification:**
   - **Behavior:** An outer or left semi join whose only bound on a watermarked 
input goes through a TIMESTAMP_NTZ column fails analysis with the 
range-condition message, and the eviction-column choice returns no column for 
that input.



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