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


##########
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: 'such as' introduces examples of the preceding noun, so a reader has to 
work out that the intended meaning is '..., so not by a DATE column cast to 
TIMESTAMP'.
   
   See **Shared repair plan 1** in the review body.



##########
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):** For a full outer join this case passes when either input 
has a usable range, so an input that lost its only bound still runs. Take 
`leftKey = rightKey AND leftTime >= rightTime - INTERVAL 1 HOUR AND leftTime <= 
CAST(rightDate AS TIMESTAMP) + INTERVAL 1 DAY` with watermarks on leftTime and 
rightTime and rightDate = to_date(rightTime). The left input passes through its 
event time, but getStateValueWatermarkColumn finds no TIMESTAMP column to evict 
the right input by, so by the review's reading of the code the default mode 
never evicts the right state and never emits a right row that found no match as 
(null, right). The base branch evicted that input by rightTime with the cutoff 
it solved for rightDate and emitted the row. The migration guide says an outer 
join whose only such bound is on a non-TIMESTAMP column now fails analysis, but 
this one keeps running with missing rows and growing state, including after a 
restart from an existing checkpoint. Legacy mode still
  solves over the whole input and is not affected.
   
   **Recommended change:** In the default mode, make the full outer case of the 
stream-stream join analysis check also fail when an input with its own 
watermark has a range bound that the whole-input solver finds 
(StreamingJoinHelper.getStateValueWatermark over the input) but the per-column 
rule (getStateValueWatermarkColumn) does not, that is, an input that execution 
can no longer evict, using the same per-input, mode-aware eviction choice that 
execution uses. Name full outer joins in the migration-guide sentence that says 
such joins fail analysis, and add analysis tests for the case.
   
   **Why this works:** A full outer join whose second input lost its only 
usable bound fails at analysis with the existing stream-stream join message, so 
the join never runs with an input whose unmatched rows can never be emitted.
   
   **Risks:** Full outer joins whose second input is bounded only through a 
non-TIMESTAMP column ran on the base branch and now fail analysis at start and 
restart in the default mode; users must bound that input through its event time 
or a TIMESTAMP column, or run it in legacy mode.
   
   **Constraints:** Apply the new rejection only in the default mode, and keep 
inputs without their own watermark on the whole-input check they use today.
   
   **Exclusions:**
   - Inner joins and inputs whose rows are never emitted unmatched, which keep 
their unbounded state, are left to the open question about documenting or 
rejecting inputs bounded only through non-TIMESTAMP columns.
   
   **Verification:**
   - **Regression:** A full outer join on `leftKey = rightKey AND leftTime >= 
rightTime - INTERVAL 1 HOUR AND leftTime <= CAST(rightDate AS TIMESTAMP) + 
INTERVAL 1 DAY` with watermarks on leftTime and rightTime fails analysis in the 
default mode, with the input order reversed as well.
   - **Compatibility:** The same join passes analysis with 
spark.sql.streaming.statefulOperator.allowMultiple set to false, and a full 
outer join bounded through only one input's event time, whose other input has 
no range bound, keeps passing in the default mode.



##########
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:
   **Nit (P3):** Every TIMESTAMP column of the input becomes a candidate, 
including ones the join condition never references, and each costs a full 
solver pass that re-splits the condition and reruns collectTerms. An input 
whose event time the condition does not bound and that has 20 TIMESTAMP columns 
runs 21 passes per side, twice per micro-batch, where the base branch ran one, 
and a conjunct the solver cannot use logs its warning once per pass. Keeping 
only candidates the condition references, with the event time first, returns 
the same column.
   
   **Verification:**
   - **Behavior:** For the range shapes the join tests use, the selected column 
and cutoff are unchanged, including when the input carries extra TIMESTAMP 
columns that the condition does not mention.
   - **Regression:** For an input with several TIMESTAMP columns the condition 
does not reference and a conjunct the solver cannot use, such as one with 
abs(), the solver's warning for that conjunct is logged once per selection 
instead of once per column.



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

Review Comment:
   **Non-blocking (P2):** This branch ignores 
spark.sql.streaming.statefulOperator.allowMultiple. With it set to false, 
execution still solves the bound over the whole input and applies it to the 
event time (StreamingSymmetricHashJoinHelper.scala:268-274), so a left outer 
join bounded only through `CAST(leftDate AS TIMESTAMP) > rightTime` would be 
evicted exactly as on the base branch, yet it now fails analysis on start and 
on restart from its checkpoint. The migration guide says joins keep the earlier 
behavior in legacy mode; in that mode the check needs the whole-input solver 
that execution uses.
   
   See **Shared repair plan 1** in the review body.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -4399,6 +4399,20 @@ object SQLConf {
       .checkValue(v => Set(1, 2, 3, 4).contains(v), "Valid versions are 1, 2, 
3, and 4")
       .createWithDefault(2)
 
+  val STREAMING_JOIN_STATE_V4_INDEX_VERSION =
+    buildConf("spark.sql.streaming.join.stateFormatV4.indexVersion")
+      .internal()
+      .withBindingPolicy(ConfigBindingPolicy.NOT_APPLICABLE)
+      .doc("How state format version 4 of stream-stream joins orders the state 
of an input that " +

Review Comment:
   **Nit (P3):** This describes only the range case, but the same version now 
also decides the equality-key ordering: version 1 orders each input by the 
opposite input's watermarked key, and a restart with version 0 fails when that 
key differs from the shared one. For `la = ra AND lb = rb` with watermarks on 
la and rb, the check in doExecute fails a version-0 restart naming lb although 
no condition bounds another column, and the doc mentions neither that case nor 
what version 1 does for equality keys.
   
   **Verification:**
   - **Inspection:** The doc of 
spark.sql.streaming.join.stateFormatV4.indexVersion describes the range and the 
equality-key ordering for versions 0 and 1 and both cases in which a version-0 
restart fails.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -403,19 +428,21 @@ case class StreamingSymmetricHashJoinExec(
     // Create left and right side hash joiners and store in the joiner manager.
     // Both sides should use the same store generator if we are re-using the 
same store instance.
     val joinStateManagerStoreGenerator = new JoinStateManagerStoreGenerator()
-    val joinKeyOrdinalForWatermark =
-      
StreamingSymmetricHashJoinHelper.findJoinKeyOrdinalForWatermark(leftKeys, 
rightKeys)
+    def joinKeyOrdinalForWatermark(side: JoinSide): Option[Int] =
+      findStateKeyOrdinalForWatermark(side, leftKeys, rightKeys, 
!allowMultipleStatefulOperators)

Review Comment:
   **Non-blocking (P2):** The key ordinal here, like the ordering column the 
value predicate supplies, depends on 
spark.sql.streaming.statefulOperator.allowMultiple, but that setting is not 
recorded in the offset log, and a query started on this version records index 
version 1 in either mode, so the restart check never runs for it. For `la = ra 
AND lb = rb` with watermarks on la and rb on state format 4, a query started in 
the default mode stores left rows at (key, lb). Reading the code, if it is 
restarted with allowMultiple set to false, which the migration guide offers as 
the way to keep the earlier behavior, the left manager looks rows up at (key, 
la), so a matching right row misses them and both are later emitted unmatched. 
Switching the other way fails the same way, and on the value path a switch 
mixes event-time-ordered and column-ordered entries in one index.
   
   **Recommended change:** Tie the V4 layout to the checkpoint: when a new 
query writes its first offset-log entry with 
spark.sql.streaming.statefulOperator.allowMultiple set to false, record index 
version 0, which already means ordering by the event time and the shared 
equality key, and record 1 otherwise. Run the V4 restart check for both 
versions: for each input, derive the ordering key or column that the recorded 
version implies and the one the current mode derives, and fail with 
STREAMING_JOIN_STATE_V4_CHECKPOINT_INCOMPATIBLE when they differ, rewording 
that error so it also names the allowMultiple setting as a cause, because its 
current text says the Spark version that wrote the checkpoint ordered the state 
differently. Extend the index-version doc and the migration guide to say that 
switching allowMultiple on a state format 4 query of these join shapes needs a 
new checkpoint, and add restart tests for both switch directions.
   
   **Why this works:** A restart can then only read V4 state with the layout it 
was written with: queries started in legacy mode keep the previous key and 
event-time ordering, queries started in the default mode keep the new ordering, 
and a mode switch that would change either fails before any state is read.
   
   **Risks:** Users who switch allowMultiple on a state format 4 query whose 
join has watermarks on different equality keys, or a range bounded through 
another TIMESTAMP column, must start a new checkpoint; joins whose layout is 
the same in both modes restart as before.
   
   **Constraints:** Choose the recorded version only when a query has no offset 
log yet; a restart must keep the value its checkpoint recorded.
   
   **Exclusions:**
   - State formats 1 to 3, which keep no ordered layout, are left unchanged.
   
   **Verification:**
   - **Regression:** Start the crossed-key V4 full outer join in each mode, 
restart it in the other mode, and check that each restart fails with 
STREAMING_JOIN_STATE_V4_CHECKPOINT_INCOMPATIBLE for the left input before any 
row is emitted, with a message that names the allowMultiple setting; do the 
same for a left outer join on `rightTime BETWEEN leftTime AND expiry`.
   - **Compatibility:** A V4 interval join bounded through both event times 
restarts across a mode switch with the same results, and a query started in 
legacy mode records index version 0 in its offset log.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -262,40 +262,58 @@ 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):** For an input evicted by its own event time, the start 
bound is now solved on the event time alone and dropped when it lies above the 
late watermark. With `leftKey = rightKey AND leftTime > rightTime + INTERVAL 10 
MINUTES AND leftTime < rightTime + INTERVAL 1 HOUR AND rightTime <= expiry` on 
state format 4, the left bound at the late watermark is W_late + 10 minutes, so 
by the code it is dropped and every eviction of the left state scans the 
timestamp index from its first entry, walking the entries earlier evictions 
deleted until compaction removes them. The base branch computed the bound over 
all of the input's columns, which the expiry cutoff kept at W_late - 1 ms, so 
it scanned only above it, and its eviction for this condition was already 
correct. Results do not change; the cost is the extra scanning in every batch.
   
   See **Shared repair plan 2** in the review body.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -262,40 +262,58 @@ 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 =>

Review Comment:
   **Non-blocking (P2):** On the first batch after a restart, this bound is the 
new event-time-only cutoff at the previous batch's watermark, but a checkpoint 
that an earlier version, or this version with allowMultiple set to false, wrote 
was evicted only up to the minimum over all of the input's columns. For a state 
format 4 left outer join on `leftKey = rightKey AND rightTime >= leftTime AND 
rightTime <= leftTime + INTERVAL 10 MINUTES AND rightTime <= expiry + INTERVAL 
1 HOUR`, the earlier version evicted left rows with leftTime <= W - 1 hour, 
while this bound starts the scan above W_prev - 10 minutes. Reading the code, 
left rows with leftTime between W_prev - 1 hour and W_prev - 10 minutes are 
then never scanned again: they stay in state, and the unmatched ones are never 
emitted. The version-0 check in doExecute passes, because the column is still 
the event time and the key is unchanged.
   
   See **Shared repair plan 2** in the review body.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -722,6 +751,21 @@ 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. The same holds for 
an equality key
+    // that the opposite watermark selects; the key that 
findJoinKeyOrdinalForWatermark selects
+    // keeps the previous behavior.
+    private[this] val isEvictionColumnNull: UnsafeRow => Boolean = 
stateWatermarkPredicate match {

Review Comment:
   **Blocking (P1):** This check only sees rows as they arrive. Rows that an 
earlier version stored before the upgrade, or that this version stored with 
allowMultiple set to false before a switch to the default mode, never pass 
through it. For a full outer join on `la = ra AND lb = rb` with watermarks on 
la and rb on state format 2, a left row (la = 100, lb = NULL) stored by the 
base branch would have been evicted by la and emitted as (100, null, null, 
null). Reading the code, after the restart the left predicate tests lb <= 
watermark, which is never true for NULL, and the state format 1 to 3 managers 
remove only rows whose predicate is true, so the row is never evicted or 
emitted. A stored NULL expiry under `rightTime BETWEEN leftTime AND expiry` 
behaves the same.
   
   **Recommended change:** In the default mode, when an input's key predicate 
tests a key position other than the shared one, or its value predicate tests a 
column other than the input's event time, build the predicate so that it also 
evicts rows where that key or column is NULL (`IS NULL OR ... <= cutoff`). 
Carry the evicting column or key position in the predicate objects instead of 
recovering it from the expression shape, and use it in the arrival-time NULL 
check, in stateValueWatermarkColumnOrdinal, and in the V4 restart check, so the 
new expression shape does not disable them. Add streaming restart tests in the 
join tests.
   
   **Why this works:** Condition eviction on state formats 1 to 3 visits every 
stored row each batch, so on the first batch after the restart the extended 
predicate removes the stranded rows, and an outer join emits them as unmatched 
rows, which is correct because a NULL key or bounded column can never match.
   
   **Compatibility:** Predicates on the shared key and on an input's own event 
time, and every legacy-mode predicate, keep the base branch's shape and outcome.
   
   **Risks:** After the restart, the first eviction emits the stranded rows as 
unmatched outer rows; this is the correct output, but it appears all at once in 
that batch.
   
   **Constraints:** Keep the predicate on the shared key and on the event time 
exactly as the base branch builds it, and keep legacy-mode predicates unchanged.
   
   **Verification:**
   - **Regression:** Write state format 2 and 3 checkpoints in legacy mode, or 
with a bundled checkpoint from an earlier version, that store a NULL-lb left 
row of the crossed-key full outer join and a NULL-expiry left row of the range 
left outer join, restart them in the default mode, and check that each row is 
emitted unmatched once and that the state row count drops by those rows.
   - **Compatibility:** A NULL-lb or NULL-expiry row that arrives after the 
restart is still emitted on arrival without entering state, and the same joins 
run with spark.sql.streaming.statefulOperator.allowMultiple set to false keep 
the base branch's eviction predicates.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -309,12 +327,32 @@ object StreamingSymmetricHashJoinHelper extends Logging {
     // left side keys effectively causes the timestamp on the right side to 
have a watermark.
     // We will use the ordinal of the left timestamp in the left keys to find 
the corresponding
     // right timestamp in the right keys.
-    leftKeys.zipWithIndex.collectFirst {
+    watermarkedKeyOrdinal(leftKeys).orElse(watermarkedKeyOrdinal(rightKeys))
+  }
+
+  /**
+   * The ordinal of the equality key that evicts the state of one side: the 
first watermarked key
+   * of the opposite input, whose future rows have that key above the 
watermark. When the
+   * opposite input has no watermarked key, and in the legacy mode with a 
single global
+   * watermark, this is [[findJoinKeyOrdinalForWatermark]].
+   */
+  def findStateKeyOrdinalForWatermark(
+      joinSide: JoinSide,
+      leftKeys: Seq[Expression],
+      rightKeys: Seq[Expression],
+      useFirstEventTimeColumn: Boolean): Option[Int] = {
+    val otherSideKeys = if (joinSide == LeftSide) rightKeys else leftKeys
+    val sharedOrdinal = findJoinKeyOrdinalForWatermark(leftKeys, rightKeys)
+    if (useFirstEventTimeColumn) {
+      sharedOrdinal
+    } else {
+      watermarkedKeyOrdinal(otherSideKeys).orElse(sharedOrdinal)

Review Comment:
   **Nit (P3):** When the opposite input's watermarked key appears in the join 
keys only inside an expression, as in `lb = rb + INTERVAL 1 HOUR` or a 
truncation of rb, watermarkedKeyOrdinal finds no watermarked NamedExpression 
and this falls back to the shared key, so the left input is still evicted by la 
and loses the same matches the PR fixes for `lb = rb`. The PR description 
defers that case, but the scaladoc above names only the no-watermarked-key and 
legacy fallbacks; a TODO naming shifted and truncated keys would show readers 
that the fix is partial.
   
   **Verification:**
   - **Inspection:** The scaladoc or a TODO at findStateKeyOrdinalForWatermark 
names the shifted or truncated opposite-key case, its fallback to the shared 
key, and that the fix is deferred.



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