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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -156,6 +157,89 @@ object UnsupportedOperationChecker extends Logging {
     }
   }
 
+  /**
+   * Checks, in append mode, for an operator that drops late rows after a 
stream-stream join whose
+   * state of an input has no cutoff, as 
[[checkStreamingQueryGlobalWatermarkLimit]] does for other
+   * operators. It takes the optimized plan, whose join conditions eviction 
uses. A query from a
+   * checkpoint without `STATEFUL_OPERATOR_CHECK_JOIN_OUTPUT_WATERMARK` only 
logs a warning.
+   */
+  def checkStreamStreamJoinOutputWatermark(plan: LogicalPlan, outputMode: 
OutputMode): Unit = {
+    val failWhenDetected = SQLConf.get.statefulOperatorCorrectnessCheckEnabled 
&&
+      
SQLConf.get.getConf(SQLConf.STATEFUL_OPERATOR_CHECK_JOIN_OUTPUT_WATERMARK)
+    try {
+      plan.foreach { subPlan =>
+        // TODO: Update mode is not checked, although its aggregations also 
drop late rows.
+        if (outputMode == InternalOutputModes.Append && 
dropsLateRows(subPlan)) {
+          subPlan.foreach {
+            case j: Join if j ne subPlan =>
+              joinInputWithoutStateCutoff(j).foreach { side =>
+                throwError("Detected pattern of possible 'correctness' issue: 
the state of the " +
+                  s"$side input of a stream-stream join has no cutoff, so the 
join can emit its " +

Review Comment:
   **Nit (P3):** Two of the three paths that reach this message flag inputs 
whose state does have a cutoff, only not on their event time. A window 
aggregation on `la` after `la = ra AND lb = rb` with watermarks on `la` and 
`rb` gets this message, but the left state is evicted by `lb`, the join keys 
already carry both watermarks, and a range condition changes nothing, because a 
watermarked key makes eviction use the key predicate and the keyed case of the 
check ignores the condition; what lifts the error is putting both watermarks at 
the same key position, legacy mode, or disabling the check. For `rightTime 
BETWEEN leftTime AND expiry` followed by a window on `leftTime`, the left state 
has a cutoff on `expiry`, and the remedy is a range condition that bounds 
`leftTime` itself. The scaladoc of `checkStreamStreamJoinOutputWatermark` and 
the doc of `spark.sql.streaming.statefulOperator.checkJoinOutputWatermark` 
describe the check the same way.
   
   **Verification:**
   - **Behavior:** The window aggregation after la = ra AND lb = rb with 
watermarks on la and rb is rejected with a message that names lb as the key 
that evicts the left input, the expiry join's rejection names expiry, and the 
key-only join's rejection keeps the current wording.
   - **Inspection:** The scaladoc of checkStreamStreamJoinOutputWatermark and 
the checkJoinOutputWatermark doc describe the flagged inputs as inputs whose 
state is not bounded by their event time.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -156,6 +157,89 @@ object UnsupportedOperationChecker extends Logging {
     }
   }
 
+  /**
+   * Checks, in append mode, for an operator that drops late rows after a 
stream-stream join whose
+   * state of an input has no cutoff, as 
[[checkStreamingQueryGlobalWatermarkLimit]] does for other
+   * operators. It takes the optimized plan, whose join conditions eviction 
uses. A query from a
+   * checkpoint without `STATEFUL_OPERATOR_CHECK_JOIN_OUTPUT_WATERMARK` only 
logs a warning.
+   */
+  def checkStreamStreamJoinOutputWatermark(plan: LogicalPlan, outputMode: 
OutputMode): Unit = {
+    val failWhenDetected = SQLConf.get.statefulOperatorCorrectnessCheckEnabled 
&&

Review Comment:
   **Blocking (P1):** By the review's reading of the code, a checkpoint written 
before this change restores 
`spark.sql.streaming.statefulOperator.checkJoinOutputWatermark` as false 
(OffsetSeq.scala line 282), so `failWhenDetected` is false and this check only 
logs a warning on restart, also for inputs whose eviction this change moved. On 
state formats 1 to 3 nothing else stops the restart, so the moved eviction runs 
while `produceOutputWatermark` still assumes the old one. Take state format 2 
and `l LEFT OUTER JOIN r ON la = ra AND lb = rb` with 10-second watermarks on 
`la` and `rb`, followed by an append-mode count over `window(la, '10 
seconds')`. On the base branch a left row (la 60 s, lb 300 s) that never 
matches leaves state once the watermark reaches 60 s and is counted in [60 s, 
70 s). After an upgrade restart the row leaves state only once the watermark 
reaches 300 s, when the aggregation's late-row watermark, the previous batch's, 
is already past 70 s, so the aggregation drop
 s it; only the warning and the dropped-row metric show it. A left outer join 
on `rightTime BETWEEN leftTime AND expiry` followed by a window on `leftTime` 
loses rows the same way, and so does a right outer join on `leftKey = rightKey 
AND leftTime <= rightExpiry` followed by a window on `rightTime`, where the 
check reports the left input, which has no state cutoff, and never looks at the 
right input whose eviction moved to `rightExpiry`. New queries of these shapes 
now fail, but upgrading a running query is the usual way into this state, and 
the migration guide's entries mention only new queries.
   
   This extends existing discussions 
[1](https://github.com/apache/spark/pull/60668#issuecomment-6993169113), 
[2](https://github.com/apache/spark/pull/60668#issuecomment-6996207307), 
[3](https://github.com/apache/spark/pull/60668#issuecomment-7002683932), 
[4](https://github.com/apache/spark/pull/60668#issuecomment-7005947909), 
[5](https://github.com/apache/spark/pull/60668#issuecomment-7035658540).
   
   **Recommended change:** In checkStreamStreamJoinOutputWatermark, let a 
recorded false spark.sql.streaming.statefulOperator.checkJoinOutputWatermark 
lower a detection to a warning only for an input without a state cutoff. For an 
input whose eviction this change moved, to another TIMESTAMP column or to the 
opposite input's watermarked equality key, fail whenever 
spark.sql.streaming.statefulOperator.checkCorrectness.enabled is on and the 
join type emits that input's unmatched rows (left or full outer for the left 
input, right or full outer for the right input), so a restart from a checkpoint 
written before this change fails as a new query does; keep the warning for 
inner and left semi joins and for an input whose unmatched rows the join does 
not emit, which lose only matches the base branch never produced. Have 
joinInputWithoutStateCutoff report every flagged input of the join with the 
path that flagged it, instead of only the first flagged input, so the check can 
tell these cases ap
 art and does not miss a moved input behind an input without a state cutoff, 
such as the right input of a right outer join on leftKey = rightKey AND 
leftTime <= rightExpiry, where rightExpiry is another TIMESTAMP column of the 
right input. Commit 7eaf825baea introduced the warning-only restart for inputs 
without a cutoff, and later commits reused it for the moved evictions. Say in 
both 4.4-to-4.5 migration entries for the moved evictions that such queries 
restarted from existing checkpoints fail too, update the 
checkJoinOutputWatermark doc, and add restart cases to the join output 
watermark tests.
   
   **Why this works:** The recorded false default exists so that an upgraded 
query keeps the base branch's results while the check only warns. That premise 
holds for an input without a state cutoff and fails for an input whose eviction 
moved, because there the restart itself changes which rows reach the next 
operator below its watermark. Choosing the restart policy per detection path 
restores the invariant that an upgraded query either keeps the base branch's 
results or fails loudly.
   
   **Compatibility:** Restarts of joins whose flagged inputs keep the base 
branch's eviction, such as an input without a state cutoff, keep running with 
only the warning, because their results are the base branch's.
   
   **Risks:** Pipelines that run a late-dropping operator after a left, right 
or full outer join whose eviction this change moved, and that were running on 
an earlier version, fail at their first batch after the upgrade instead of 
silently dropping rows; turning off 
spark.sql.streaming.statefulOperator.checkCorrectness.enabled lets them run 
with the warning, and setting 
spark.sql.streaming.statefulOperator.allowMultiple to false keeps the earlier 
join eviction. On state format 4 such restarts now fail with the 
chained-operator error before the state format 4 incompatibility error, so 
users who turn the check off then meet the incompatibility error.
   
   **Constraints:** Keep the warning-only restart for an input without a state 
cutoff and for inner and left semi joins of the moved shapes, whose restarted 
results keep every row the base branch delivered. Keep new queries failing as 
they do now, and keep every detection a warning when the correctness check is 
off. Decide moved evictions from the same detection paths the check already 
uses, so it fails exactly the inputs the default mode evicts by another key or 
column. Examine every flagged input of a join, not only the first, so a moved 
input whose unmatched rows the join emits fails the restart even when another 
input of that join has no state cutoff.
   
   **Exclusions:**
   - Deriving the join's output watermark from what each input's state still 
holds, which would let these pipelines run without dropping rows, stays with 
SPARK-62001.
   - Update mode, which the check does not cover, keeps its existing TODO.
   
   **Verification:**
   - **Regression:** On state format 2, a left outer join on la = ra AND lb = 
rb with watermarks on la and rb followed by an append-mode count over a window 
on la, a left outer join on rightTime BETWEEN leftTime AND expiry followed by a 
count over a window on leftTime, and a right outer join on leftKey = rightKey 
AND leftTime <= rightExpiry, where rightExpiry is another TIMESTAMP column of 
the right input, followed by a count over a window on rightTime, each restarted 
after checkJoinOutputWatermark is removed from the latest offset log entry, 
fail at the first batch with the chained-operator correctness error.
   - **Compatibility:** The same restart of a key-only join followed by a 
window aggregation, and of an inner join on la = ra AND lb = rb followed by a 
window on la, only logs the warning and keeps running.
   - **Behavior:** With 
spark.sql.streaming.statefulOperator.checkCorrectness.enabled set to false, the 
crossed-key left outer restart logs the warning and runs.
   - **Inspection:** Both 4.4-to-4.5 migration entries for the moved evictions 
say that such queries restarted from existing checkpoints fail too, and the 
checkJoinOutputWatermark doc says which detections a recorded false lowers to a 
warning.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -156,6 +157,89 @@ object UnsupportedOperationChecker extends Logging {
     }
   }
 
+  /**
+   * Checks, in append mode, for an operator that drops late rows after a 
stream-stream join whose
+   * state of an input has no cutoff, as 
[[checkStreamingQueryGlobalWatermarkLimit]] does for other
+   * operators. It takes the optimized plan, whose join conditions eviction 
uses. A query from a
+   * checkpoint without `STATEFUL_OPERATOR_CHECK_JOIN_OUTPUT_WATERMARK` only 
logs a warning.
+   */
+  def checkStreamStreamJoinOutputWatermark(plan: LogicalPlan, outputMode: 
OutputMode): Unit = {
+    val failWhenDetected = SQLConf.get.statefulOperatorCorrectnessCheckEnabled 
&&
+      
SQLConf.get.getConf(SQLConf.STATEFUL_OPERATOR_CHECK_JOIN_OUTPUT_WATERMARK)
+    try {
+      plan.foreach { subPlan =>
+        // TODO: Update mode is not checked, although its aggregations also 
drop late rows.
+        if (outputMode == InternalOutputModes.Append && 
dropsLateRows(subPlan)) {
+          subPlan.foreach {
+            case j: Join if j ne subPlan =>
+              joinInputWithoutStateCutoff(j).foreach { side =>
+                throwError("Detected pattern of possible 'correctness' issue: 
the state of the " +
+                  s"$side input of a stream-stream join has no cutoff, so the 
join can emit its " +
+                  "old rows below its output watermark, and a later stateful 
operator drops them " +
+                  "as late. Add a watermark in the join keys or a range 
condition that bounds " +
+                  "that input by the other input's watermark, or set " +
+                  
"`spark.sql.streaming.statefulOperator.checkCorrectness.enabled` to false.")(j)
+              }
+            case _ =>
+          }
+        }
+      }
+    } catch {
+      case e: AnalysisException if !failWhenDetected =>
+        logWarning(log"${MDC(ANALYSIS_ERROR, e.message)};\n${MDC(QUERY_PLAN, 
plan)}", e)
+    }
+  }
+
+  // An input of a stream-stream join with an event time but no state cutoff, 
as eviction derives
+  // it: no watermark in the join keys, and no range condition that bounds the 
input by the
+  // watermark of the other input. With allowMultiple, an input that eviction 
picks another column
+  // for counts too, since its state keeps rows of any event time. A left semi 
join only emits
+  // left rows.
+  private def joinInputWithoutStateCutoff(join: Join): Option[String] = join 
match {
+    case Join(left, right, joinType, condition, _) if left.isStreaming && 
right.isStreaming &&
+        !StreamingJoinHelper.isWatermarkInJoinKeys(join) =>
+      Seq(("left", left, right), ("right", right, left)).take(if (joinType == 
LeftSemi) 1 else 2)
+        .collectFirst {
+          case (side, input, other) if input.output.exists(hasEventTimeCol) && 
(
+              StreamingJoinHelper.getStateValueWatermark(
+                input.outputSet, other.outputSet, condition, 
Some(1000000)).isEmpty ||
+              SQLConf.get.getConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE) &&
+              StreamingJoinHelper.getStateValueWatermarkColumn(input.output, 
other.outputSet,
+                condition, Some(1000000)).exists { case (column, _) => 
!hasEventTimeCol(column) }
+              ) => side
+        }
+    // With allowMultiple, an input is evicted by its equality key that the 
other input's
+    // watermark bounds. Where that is neither the key earlier versions 
evicted both inputs by
+    // nor the input's event time, its state keeps rows of any event time.
+    case ExtractEquiJoinKeys(joinType, leftKeys, rightKeys, _, _, left, right, 
_)
+        if left.isStreaming && right.isStreaming &&
+          SQLConf.get.getConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE) =>
+      def watermarked(keys: Seq[Expression]): Option[Int] = 
Some(keys.indexWhere {
+        case ne: NamedExpression => 
ne.metadata.contains(EventTimeWatermark.delayKey)
+        case _ => false
+      }).filter(_ >= 0)
+      val shared = watermarked(leftKeys).orElse(watermarked(rightKeys))
+      Seq(("left", leftKeys, rightKeys), ("right", rightKeys, leftKeys))
+        .take(if (joinType == LeftSemi) 1 else 2).collectFirst {
+          case (side, keys, otherKeys) if watermarked(otherKeys).exists { i =>
+            !shared.contains(i) && watermarked(Seq(keys(i))).isEmpty } => side
+        }
+    case _ => None
+  }
+
+  // A stateful operator that drops the input rows below its watermark for 
late rows. Its
+  // physical operator filters by an event-time column of its input, so it 
needs one.
+  private def dropsLateRows(p: LogicalPlan): Boolean = p.isStreaming &&

Review Comment:
   **Nit (P3):** The new tests reach three branches of this function: a window 
aggregation and `dropDuplicates` without an event-time key, which reject, and 
`flatMapGroupsWithState` without a timeout, which accepts; every rejection runs 
in the default mode. No test reaches `flatMapGroupsWithState` with an 
event-time timeout, `transformWithState` in event-time mode or its accept side, 
`dropDuplicatesWithinWatermark`, a later stream-stream join, or the PySpark 
nodes, and none runs the crossed-key or expiry join followed by a stateful 
operator with `spark.sql.streaming.statefulOperator.allowMultiple` set to 
false, the guard at UnsupportedOperationChecker.scala lines 206 and 216. By the 
review's reading of the tests, comparing the `flatMapGroupsWithState` timeout 
with `ProcessingTimeTimeout`, dropping the `Join` case, or removing either 
`allowMultiple` guard keeps every test green; the first two would let a later 
operator silently drop old joined rows, and the last would fail legacy-mode
  pipelines that the migration guide says keep the earlier behavior. 
`UnsupportedOperationsSuite`, which covers the sibling global-watermark check 
with logical plans, has no case for this one.
   
   **Verification:**
   - **Regression:** In append mode, flatMapGroupsWithState with an event-time 
timeout, transformWithState in event-time mode, dropDuplicatesWithinWatermark 
and a later stream-stream join are each rejected after a key-only stream-stream 
join, and transformWithState in processing-time mode is accepted.
   - **Compatibility:** With spark.sql.streaming.statefulOperator.allowMultiple 
set to false, the crossed-key join and the expiry join, each followed by a 
window aggregation, pass the check.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -710,17 +753,49 @@ case class StreamingSymmetricHashJoinExec(
         Predicate.create(Literal(false), Seq.empty).eval _ // false = do not 
remove if no predicate
     }
 
+    private[this] var updatedStateRowsCount = 0
+    private[this] var numRemovedFromOtherSideDuringJoinCount = 0
+    private[this] val allowMultipleStatefulOperators: Boolean =
+      conf.getConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE)
+
+    // When the default mode picked the column that the value predicate tests 
because the join
+    // condition bounds it, a row with a NULL in it can never match, and 
`column <= cutoff` never
+    // holds for it. The legacy mode, and the default mode for an input 
bounded only through a
+    // column cast to TIMESTAMP, test the event time, which the condition need 
not bound. A NULL in
+    // an equality key that the opposite watermark selects can never match 
either; the key that
+    // findJoinKeyOrdinalForWatermark selects keeps the previous behavior.
+    private[this] val isEvictionColumnNull: UnsafeRow => Boolean = 
stateWatermarkPredicate match {
+      case Some(JoinStateValueWatermarkPredicate(LessThanOrEqual(column, _), 
_, _, true)) =>
+        Predicate.create(IsNull(column), inputAttributes).eval _
+      case Some(_: JoinStateKeyWatermarkPredicate) if 
joinKeyOrdinalForWatermark !=
+          findJoinKeyOrdinalForWatermark(leftKeys, rightKeys) =>
+        Predicate.create(IsNull(joinKeys(joinKeyOrdinalForWatermark.get)), 
inputAttributes).eval _
+      case _ => _ => false
+    }
+
+    // Such a row is not stored, but an earlier version or the legacy mode can 
have stored one.
     private[this] val stateValueWatermarkPredicateFunc = 
stateWatermarkPredicate match {
-      case Some(JoinStateValueWatermarkPredicate(expr, _, _)) =>
+      case Some(JoinStateValueWatermarkPredicate(expr @ 
LessThanOrEqual(column, _), _, _, true)) =>
+        Predicate.create(Or(expr, IsNull(column)), inputAttributes).eval _
+      case Some(JoinStateValueWatermarkPredicate(expr, _, _, _)) =>
         Predicate.create(expr, inputAttributes).eval _
       case _ =>
         Predicate.create(Literal(false), Seq.empty).eval _  // false = do not 
remove if no predicate
     }
 
-    private[this] var updatedStateRowsCount = 0
-    private[this] var numRemovedFromOtherSideDuringJoinCount = 0
-    private[this] val allowMultipleStatefulOperators: Boolean =
-      conf.getConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE)
+    // A left semi join processes its right input first, so this batch's left 
rows can still match
+    // a right row that the completion check skips (SPARK-61380). Earlier 
versions tested it against
+    // the cutoff on the event time solved over the whole input, which a 
picked column can exceed.
+    private[this] val skipsEvictingRightRow: UnsafeRow => Boolean = 
stateWatermarkPredicate match {
+      case Some(p: JoinStateValueWatermarkPredicate) if 
p.conditionBoundsColumn &&
+          joinType == LeftSemi && joinSide == RightSide =>
+        val cutoff = 
StreamingJoinHelper.getStateValueWatermark(AttributeSet(inputAttributes),
+          AttributeSet(left.output), condition.full, 
eventTimeWatermarkForEviction)
+        
WatermarkSupport.watermarkExpression(WatermarkSupport.findEventTimeColumn(inputAttributes,
+          allowMultipleEventTimeColumns = false), cutoff)
+          .map(Predicate.create(_, inputAttributes).eval _).getOrElse((_: 
UnsafeRow) => false)

Review Comment:
   **Nit (P3):** Each task of the right joiner reruns 
`StreamingJoinHelper.getStateValueWatermark` with its INFO logging and compiles 
this predicate with the cutoff inlined as a literal, so by the review's reading 
of the code each executor compiles one more predicate in every micro-batch 
whose watermark advanced, on every state format, for the shape of the PR's own 
left semi test. The base branch decided this admission with the already 
compiled `stateValueWatermarkPredicateFunc`. Evaluating the comparison with an 
interpreted predicate against a cutoff solved once on the driver makes the same 
decisions without the compile or the per-task solver run.
   
   **Verification:**
   - **Behavior:** The left semi range eviction cases, for a right input 
evicted by its event time and by another TIMESTAMP column, return the same rows 
on state formats 2 and 4.
   - **Inspection:** The left semi admission test is built once from a cutoff 
solved on the driver and is evaluated without code generation.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -710,17 +753,49 @@ case class StreamingSymmetricHashJoinExec(
         Predicate.create(Literal(false), Seq.empty).eval _ // false = do not 
remove if no predicate
     }
 
+    private[this] var updatedStateRowsCount = 0
+    private[this] var numRemovedFromOtherSideDuringJoinCount = 0
+    private[this] val allowMultipleStatefulOperators: Boolean =
+      conf.getConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE)
+
+    // When the default mode picked the column that the value predicate tests 
because the join
+    // condition bounds it, a row with a NULL in it can never match, and 
`column <= cutoff` never
+    // holds for it. The legacy mode, and the default mode for an input 
bounded only through a
+    // column cast to TIMESTAMP, test the event time, which the condition need 
not bound. A NULL in
+    // an equality key that the opposite watermark selects can never match 
either; the key that
+    // findJoinKeyOrdinalForWatermark selects keeps the previous behavior.
+    private[this] val isEvictionColumnNull: UnsafeRow => Boolean = 
stateWatermarkPredicate match {
+      case Some(JoinStateValueWatermarkPredicate(LessThanOrEqual(column, _), 
_, _, true)) =>
+        Predicate.create(IsNull(column), inputAttributes).eval _
+      case Some(_: JoinStateKeyWatermarkPredicate) if 
joinKeyOrdinalForWatermark !=
+          findJoinKeyOrdinalForWatermark(leftKeys, rightKeys) =>
+        Predicate.create(IsNull(joinKeys(joinKeyOrdinalForWatermark.get)), 
inputAttributes).eval _
+      case _ => _ => false
+    }
+
+    // Such a row is not stored, but an earlier version or the legacy mode can 
have stored one.
     private[this] val stateValueWatermarkPredicateFunc = 
stateWatermarkPredicate match {
-      case Some(JoinStateValueWatermarkPredicate(expr, _, _)) =>
+      case Some(JoinStateValueWatermarkPredicate(expr @ 
LessThanOrEqual(column, _), _, _, true)) =>
+        Predicate.create(Or(expr, IsNull(column)), inputAttributes).eval _
+      case Some(JoinStateValueWatermarkPredicate(expr, _, _, _)) =>
         Predicate.create(expr, inputAttributes).eval _
       case _ =>
         Predicate.create(Literal(false), Seq.empty).eval _  // false = do not 
remove if no predicate
     }
 
-    private[this] var updatedStateRowsCount = 0
-    private[this] var numRemovedFromOtherSideDuringJoinCount = 0
-    private[this] val allowMultipleStatefulOperators: Boolean =
-      conf.getConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE)
+    // A left semi join processes its right input first, so this batch's left 
rows can still match
+    // a right row that the completion check skips (SPARK-61380). Earlier 
versions tested it against
+    // the cutoff on the event time solved over the whole input, which a 
picked column can exceed.
+    private[this] val skipsEvictingRightRow: UnsafeRow => Boolean = 
stateWatermarkPredicate match {
+      case Some(p: JoinStateValueWatermarkPredicate) if 
p.conditionBoundsColumn &&

Review Comment:
   **Non-blocking (P2):** When the picked column is not the right input's event 
time, this admission test discards rows that the picked-column eviction would 
keep. Take `left.join(right, expr("k = rk AND lt BETWEEN re AND rx"), 
"left_semi")` with 0-second watermarks on `lt` and `re`: the right input is 
evicted by `rx`, and the whole-input cutoff, the eviction watermark minus 1 ms, 
is applied here to `re`. By the review's reading of the code, after a batch 
that adds (9, 10 h) to both inputs, a right row (1, re 8 h, rx 12 h) is not 
stored because 8 h is at or below 10 h minus 1 ms, although `rx` 12 h keeps it 
under the new eviction, so a left row (1, lt 11 h) in the next batch, which 
satisfies the condition, is never emitted. With `k = rk AND lt >= re - INTERVAL 
1 HOUR AND rx >= lt - INTERVAL 3 HOURS`, a left row (1, lt 6 h) in the same 
batch as a right row (1, re 5 h, rx 20 h) is lost the same way, because the 
right input is processed first. An inner join on either condition stores th
 e right row and returns the match, while the base branch lost these matches 
for every join type, so this keeps the failure the range eviction repairs for 
left semi joins, on every state format. The existing left semi test picks the 
event time `re`, so no test covers this path.
   
   **Verification:**
   - **Regression:** On state formats 2 and 4, a left semi join on k = rk AND 
lt BETWEEN re AND rx with 0-second watermarks on lt and re emits the left row 
(1, lt 11 h) after the right row (1, re 8 h, rx 12 h) arrived in the batch 
whose eviction watermark is 10 h, and a left semi join on k = rk AND lt >= re - 
INTERVAL 1 HOUR AND rx >= lt - INTERVAL 3 HOURS emits the left row (1, lt 6 h) 
that arrives in the same batch as the right row (1, re 5 h, rx 20 h).
   - **Compatibility:** The existing left semi case for a right input evicted 
by its event time returns the same rows, and the right state is still evicted 
by rx at the end of each batch.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -156,6 +157,89 @@ object UnsupportedOperationChecker extends Logging {
     }
   }
 
+  /**
+   * Checks, in append mode, for an operator that drops late rows after a 
stream-stream join whose
+   * state of an input has no cutoff, as 
[[checkStreamingQueryGlobalWatermarkLimit]] does for other
+   * operators. It takes the optimized plan, whose join conditions eviction 
uses. A query from a
+   * checkpoint without `STATEFUL_OPERATOR_CHECK_JOIN_OUTPUT_WATERMARK` only 
logs a warning.
+   */
+  def checkStreamStreamJoinOutputWatermark(plan: LogicalPlan, outputMode: 
OutputMode): Unit = {
+    val failWhenDetected = SQLConf.get.statefulOperatorCorrectnessCheckEnabled 
&&
+      
SQLConf.get.getConf(SQLConf.STATEFUL_OPERATOR_CHECK_JOIN_OUTPUT_WATERMARK)
+    try {
+      plan.foreach { subPlan =>
+        // TODO: Update mode is not checked, although its aggregations also 
drop late rows.
+        if (outputMode == InternalOutputModes.Append && 
dropsLateRows(subPlan)) {
+          subPlan.foreach {
+            case j: Join if j ne subPlan =>
+              joinInputWithoutStateCutoff(j).foreach { side =>

Review Comment:
   **Blocking (P1):** This rejects the query as soon as any input of the join 
is flagged, whatever column the later operator filters late rows by. By the 
review's reading of the code, a new append-mode `left.join(right, expr("leftKey 
= rightKey AND rightTime <= leftTime + INTERVAL 10 
SECONDS")).groupBy(window($"leftTime", "10 seconds")).count()` with 10-second 
watermarks on both times now fails at its first batch because the right input 
has no state cutoff. On the base branch it runs and drops nothing: the join's 
output watermark is the left cutoff, the input watermark minus 10 s, the 
aggregation's late-row watermark is that value from the previous batch, and 
every row the join emits carries a `leftTime` above it, since new left rows 
pass late filtering and stored ones survived eviction at that cutoff. The same 
holds for a left outer or full outer join on that condition and for the 
mirrored right outer join with a window on `rightTime`; only an operator on the 
unbounded input's event
  time can drop the old rows. Users have to add a bound the query does not need 
or turn off the internal 
`spark.sql.streaming.statefulOperator.checkCorrectness.enabled`, and the 
migration guide's reason, that such a query could drop joined rows as late, 
does not hold for these queries.
   
   **Recommended change:** In checkStreamStreamJoinOutputWatermark, have 
joinInputWithoutStateCutoff report every flagged input of a join instead of 
only the first, and fail for a flagged input only when the late-dropping 
operator's late-row column derives from that input: take the column as the 
operator's physical node uses it (an aggregation's watermarked grouping key, 
otherwise the event-time column of the operator's input), follow its lineage 
down to the join through projections, filters, window expansion and watermark 
nodes, and treat any node whose lineage cannot be followed as deriving from 
every input of the join. Apply this to all three detection paths. Add cases to 
the join output watermark tests for a one-sided range join followed by a window 
on the bounded input's event time, which then runs, and keep the cases that 
reject a window on the unbounded input's event time.
   
   **Why this works:** A row the join emits below its output watermark carries 
an old event time only in the columns of the input whose state keeps old rows. 
An operator whose late-row column derives only from other inputs never treats 
such a row as late, so relating that column to the flagged input rejects 
exactly the pipelines that can drop rows, and the reject-when-unknown fallback 
keeps the check conservative where lineage is unclear.
   
   **Risks:** Queries the check now rejects at start whose late-dropping 
operator filters only by a column from inputs with a state cutoff will run; 
this includes moved-eviction shapes such as rightTime BETWEEN leftTime AND 
expiry followed by a window on rightTime, which then return correct results 
instead of failing. A lineage case the rule follows incorrectly, or a flagged 
input it does not examine, would accept a pipeline that drops rows silently, so 
the rule must examine every flagged input of the join and reject whenever 
lineage is not followed exactly.
   
   **Constraints:** Keep rejecting whenever the operator's late-row column 
cannot be traced to the join's inputs exactly. Take each operator's late-row 
column as its physical node takes it, including the first event-time column in 
legacy mode. Keep the moved-eviction paths limited to the default mode and keep 
update mode outside the check, as they are now. Examine every input that 
joinInputWithoutStateCutoff flags, not only the first, because the late-row 
column can derive from a second flagged input.
   
   **Exclusions:**
   - Deriving a join output watermark that would let a pipeline run even when 
its operator uses the flagged input's event time stays with SPARK-62001.
   
   **Verification:**
   - **Regression:** A new append-mode query joining on leftKey = rightKey AND 
rightTime <= leftTime + INTERVAL 10 SECONDS with watermarks on both times, 
followed by a count over a window on leftTime, runs and returns the base 
branch's counts, also as a left outer join and as a full outer join, and the 
mirrored right outer join on leftTime <= rightTime + INTERVAL 10 SECONDS 
followed by a window on rightTime runs too.
   - **Compatibility:** The same joins followed by a window on the unbounded 
input's event time, a key-only join followed by a window on leftTime, by a 
window on rightTime, or by a deduplication without an event-time key, a right 
outer join on leftKey = rightKey AND leftTime <= rightExpiry, where rightExpiry 
is another TIMESTAMP column of the right input, followed by a window on 
rightTime, the crossed-key join followed by a window on la, the expiry join 
followed by a window on leftTime, and a pipeline with a Union between the join 
and the operator are still rejected.



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