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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -156,6 +156,67 @@ 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

Review Comment:
   Correction to my earlier comment: its premise was wrong. The optimizer's 
last CTE batch, ReplaceCTERefWithRepartition, which cannot be excluded, 
replaces every CTE reference that the optimizer's own InlineCTE keeps, 
MATERIALIZED and multi-reference non-deterministic ones included, with the 
definition's plan. So the optimized plan this check receives has no CTE nodes, 
InlineCTE(alwaysInline = true) returns it unchanged, and joins in such CTEs are 
checked without that call. This review raises the inert call and the scaladoc 
sentence that rests on my earlier claim as a separate finding.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4639356374","thread_id":"inline:4639356374","verdict_sha256":"4cd79ac19fb7c2f55522c91ec358f16909c13979feb12d7a72c345b49b7e06b9"}
 -->



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -156,6 +157,80 @@ object UnsupportedOperationChecker extends Logging {
     }
   }
 
+  /**
+   * Checks, in append mode, for an operator that drops late rows after a 
stream-stream join that
+   * emits the rows of an input whose state has no cutoff, as
+   * [[checkStreamingQueryGlobalWatermarkLimit]] does for other operators. It 
takes the optimized
+   * plan, whose join conditions eviction uses, with its CTE references 
inlined: the optimizer
+   * keeps some CTE definitions, such as MATERIALIZED ones, whose joins would 
be missed. A query
+   * from a checkpoint without `STATEFUL_OPERATOR_CHECK_JOIN_OUTPUT_WATERMARK` 
only logs a warning.
+   */
+  def checkStreamStreamJoinOutputWatermark(plan: LogicalPlan, outputMode: 
OutputMode): Unit = {
+    // A stream-stream join without an equality predicate fails in planning 
with its own error.
+    val hasJoinWithoutEquality = plan.exists {
+      case j @ Join(l, r, _, _, _) => l.isStreaming && r.isStreaming &&
+        ExtractEquiJoinKeys.unapply(j).isEmpty
+      case _ => false
+    }
+    if (hasJoinWithoutEquality) {
+      return
+    }
+    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)) {

Review Comment:
   **Nit (P3):** The check evaluates this append-mode test at every node, after 
a pre-pass for joins without an equality predicate that runs in every mode, so 
in update and complete mode it walks the plan twice and calls 
ExtractEquiJoinKeys on each stream-stream join, although only append mode can 
throw or warn. In append mode, dropsLateRows (lines 223-224) then builds and 
scans the output of every streaming node's children before it matches the 
operator type, and Project and Aggregate rebuild their output lists on each 
call, so the first batch does work that grows with plan nodes times columns 
although only late-dropping operators need the scan. Returning before the 
pre-pass unless the output mode is Append, with the update-mode TODO moved to 
that return, and matching the operator type first, as isStatefulOperation does, 
give the same result for every plan and mode. The cost is bounded to the first 
batch of each run and changes no plan or result.
   
   **Verification:**
   - **Inspection:** The join output watermark check returns before its first 
traversal unless the output mode is Append, with the update-mode TODO at that 
return and no output-mode test left inside the traversal; in dropsLateRows the 
operator-type match is evaluated before the scan of the children's outputs for 
an event-time column, the scan runs only for node types the match accepts, and 
the condition that the operator's input has an event-time column is kept.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -156,6 +157,80 @@ object UnsupportedOperationChecker extends Logging {
     }
   }
 
+  /**
+   * Checks, in append mode, for an operator that drops late rows after a 
stream-stream join that
+   * emits the rows of an input whose state has no cutoff, as
+   * [[checkStreamingQueryGlobalWatermarkLimit]] does for other operators. It 
takes the optimized
+   * plan, whose join conditions eviction uses, with its CTE references 
inlined: the optimizer
+   * keeps some CTE definitions, such as MATERIALIZED ones, whose joins would 
be missed. A query
+   * from a checkpoint without `STATEFUL_OPERATOR_CHECK_JOIN_OUTPUT_WATERMARK` 
only logs a warning.
+   */
+  def checkStreamStreamJoinOutputWatermark(plan: LogicalPlan, outputMode: 
OutputMode): Unit = {
+    // A stream-stream join without an equality predicate fails in planning 
with its own error.
+    val hasJoinWithoutEquality = plan.exists {
+      case j @ Join(l, r, _, _, _) => l.isStreaming && r.isStreaming &&
+        ExtractEquiJoinKeys.unapply(j).isEmpty
+      case _ => false
+    }
+    if (hasJoinWithoutEquality) {
+      return
+    }
+    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. A left semi join only emits left rows.
+  // TODO: An input evicted by another column is not checked yet, such as the 
right input of
+  //   `leftKey = rightKey AND leftTime = rightTs`, evicted by rightTs, not 
its event time.
+  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 => 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 &&
+    p.children.exists(_.output.exists(hasEventTimeCol)) && (p match {

Review Comment:
   **Nit (P3):** This conjunct and the event-time guard of 
joinInputWithoutStateCutoff at line 214 keep queries that never drop the join's 
rows as late accepted, but no test fails when either is removed on its own: 
every operator case in UnsupportedOperationsSuite wraps keyOnlyJoin, which 
keeps the watermarked lt in the operator's input, and every stream-stream join 
in the PR's tests is defined over two watermarked inputs. By the review's 
reading of the code, without this conjunct the check rejects 
Deduplicate(Seq(leftKey), keyOnlyJoin.select(leftKey)) naming the left input, 
so the one-sided range join followed by .select("leftKey").dropDuplicates(), 
whose deduplication filters nothing, would fail at its first micro-batch; 
without the guard it rejects a key join of a watermarked third input over a 
key-only join of two unwatermarked inputs, whose later join filters only the 
third input's rows. Both queries run on the base branch. The three-stream join 
test in StreamingJoinSuite has no
  watermark at all, so it stays accepted by whichever condition remains.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60713#discussion_r4639356336).
   
   **Verification:**
   - **Regression:** An append-mode plan in which a deduplication on the left 
key reads a key-only stream-stream join of two watermarked inputs narrowed to 
the left key passes the join output watermark check, and the same plan without 
the narrowing is rejected with the message naming the left input; with the 
condition that the operator's input has an event-time column removed, the first 
plan is rejected too and its case fails.
   - **Regression:** An append-mode plan in which a stream-stream join with a 
watermarked third input reads a key-only stream-stream join of two inputs 
without a watermark passes the join output watermark check; with the guard that 
reports only join inputs with an event-time column removed, it is rejected with 
the message naming the left input, and its case fails.



##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinOutputWatermarkSuite.scala:
##########
@@ -0,0 +1,254 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.streaming
+
+import java.io.File
+import java.sql.Timestamp
+
+import org.apache.hadoop.fs.Path
+import org.apache.logging.log4j.Level
+
+import org.apache.spark.sql.{AnalysisException, DataFrame}
+import org.apache.spark.sql.execution.streaming.checkpointing.{OffsetMap, 
OffsetSeq, OffsetSeqLog}
+import org.apache.spark.sql.execution.streaming.runtime.MemoryStream
+import org.apache.spark.sql.execution.streaming.state.RocksDBStateStoreProvider
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * A stateful operator after a stream-stream join whose state of an input has 
no cutoff. The join
+ * forwards its input watermark, so the operator would drop the old rows that 
the join emits.

Review Comment:
   **Nit (P3):** The join does not simply forward its input watermark: 
produceOutputWatermark returns the minimum of the input watermark and the state 
watermarks of the inputs that have one 
(StreamingSymmetricHashJoinExec.scala:1128-1143). For this suite's one-sided 
case, rightTime <= leftTime + INTERVAL 10 SECONDS (lines 79-85), that is the 
left state watermark, 10 seconds and 1 ms below the input watermark, and the 
check still rejects the query because the right input's state has no cutoff, so 
its stored rows can be emitted below that watermark.
   
   ```suggestion
    * A stateful operator after a stream-stream join whose state of an input 
has no cutoff. The join's
    * output watermark ignores that input, so the operator would drop the old 
rows the join emits.
   ```
   
   **Verification:**
   - **Inspection:** The class doc of the streaming join output watermark tests 
describes the failure as the join's output watermark not accounting for the 
input whose state has no cutoff, and no longer says the join forwards its input 
watermark.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala:
##########
@@ -158,6 +159,12 @@ class IncrementalExecution(
     // query started, which the plan must still apply to all the rows that it 
reads, see
     // StreamingV2ScanPushDown.
     StreamingV2ScanPushDown.checkPushedFilters(sparkSession, optimized, 
pushedFilterRewrites)
+    // Unlike the other unsupported operation checks, which run when the query 
starts, this one
+    // runs once the confs of the checkpoint are restored, on the plan that 
eviction derives from.
+    if (isFirstBatch && 
sparkSession.sessionState.conf.isUnsupportedOperationCheckEnabled) {
+      UnsupportedOperationChecker.checkStreamStreamJoinOutputWatermark(
+        InlineCTE(alwaysInline = true).apply(optimized), outputMode)

Review Comment:
   **Nit (P3):** By the review's reading of the optimizer, this call returns 
optimized unchanged. SparkOptimizer runs the non-excludable 
ReplaceCTERefWithRepartition after every batch except MarkSingleTaskExecution 
(SparkOptimizer.scala:141 and 168), and that rule replaces every CTE reference 
that the optimizer's own InlineCTE keeps, MATERIALIZED and multi-reference 
non-deterministic ones included, with the definition's plan and drops the 
WithCTE (ReplaceCTERefWithRepartition.scala:53-89), so InlineCTE.apply finds no 
CTE node to inline (InlineCTE.scala:63). A join defined in a MATERIALIZED CTE 
is therefore already inside the late-dropping operator's subtree, and the 
scaladoc sentence at UnsupportedOperationChecker.scala:164-165, which says the 
optimizer keeps such definitions and their joins would be missed, describes a 
plan the check never receives; the earlier review comment that asked for that 
sentence made the same mistake. The SQL CTE test passes with or without the 
call, becaus
 e the optimizer inlines its single-reference CTE anyway, so the coverage that 
actually holds for a kept definition has no test.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60713#discussion_r4639356374).
   
   **Verification:**
   - **Behavior:** A streaming SQL query over two inputs with 10-second 
watermarks, whose key-only join is defined in a WITH ... AS MATERIALIZED CTE 
and followed by a 10-second window count in append mode, fails when its first 
micro-batch is planned, with the message naming the left input, while the check 
receives the optimized plan without any CTE inlining.
   - **Inspection:** IncrementalExecution passes the optimized plan to the join 
output watermark check without InlineCTE, and the check's scaladoc describes 
that plan as having every CTE reference, MATERIALIZED ones included, already 
replaced by the optimizer.



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