HeartSaVioR commented on code in PR #60280:
URL: https://github.com/apache/spark/pull/60280#discussion_r4596399097


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/SymmetricHashJoinStateManager.scala:
##########
@@ -253,54 +254,63 @@ class SymmetricHashJoinStateManagerV4(
   protected val keySchema = StructType(
     joinKeys.zipWithIndex.map { case (k, i) => StructField(s"field$i", 
k.dataType, k.nullable) })
   protected val keyAttributes = toAttributes(keySchema)
-  private val eventTimeColIdxOpt = WatermarkSupport.findEventTimeColumnIndex(
-    inputValueAttributes,
-    // NOTE: This does not accept multiple event time columns. This is not the 
same with the
-    // operator which we offer the backward compatibility, but it involves too 
many layers to
-    // pass the information. The information is in SQLConf.
-    allowMultipleEventTimeColumns = false)
-
-  // When there is no event time column in the value and no watermark ordinal 
in the key,
+  private val valueTimestampColumnOrdinal = {
+    val eventTimeColIdx = WatermarkSupport.findEventTimeColumnIndex(
+      inputValueAttributes,
+      // NOTE: This does not accept multiple event time columns. This is not 
the same with the
+      // operator which we offer the backward compatibility, but it involves 
too many layers to
+      // pass the information. The information is in SQLConf.
+      allowMultipleEventTimeColumns = false)
+    // Validate event-time columns above even when eviction indexes a 
different timestamp.
+    stateValueWatermarkColumnOrdinal.orElse(eventTimeColIdx)
+  }
+
+  // When there is no indexed timestamp column in the value and no watermark 
ordinal in the key,
   // the secondary index (TsWithKey) will never be used for eviction. Skip 
writing to it
   // to avoid unnecessary RocksDB merge overhead.
   // TODO(SPARK-56536): This could be further optimized by also considering 
whether the state
-  //   watermark predicate is defined. Even when an event time column exists, 
the secondary index
-  //   is unused if eviction is not possible (e.g., only one side defines a 
watermark in a time
-  //   interval join). That would require propagating the predicate 
information here.
-  private val hasEventTime: Boolean =
-    eventTimeColIdxOpt.isDefined || joinKeyOrdinalForWatermark.isDefined
+  //   watermark predicate is defined. Even when an indexed timestamp column 
exists, the secondary
+  //   index is unused if eviction is not possible (e.g., only one side 
defines a watermark in a
+  //   time interval join). That would require propagating the predicate 
information here.
+  private val hasTimestampForEviction: Boolean =
+    valueTimestampColumnOrdinal.isDefined || 
joinKeyOrdinalForWatermark.isDefined
 
   private val random = new scala.util.Random(System.currentTimeMillis())
-  private val bucketCountForNoEventTime = 1024
-  private val extractEventTimeFn: UnsafeRow => Long = { row =>
-    eventTimeColIdxOpt match {
-      case Some(idx) =>
-        val attr = inputValueAttributes(idx)
+  private val bucketCountWithoutTimestamp = 1024
+  // A null indexed timestamp makes the value-eviction predicate SQL-unknown, 
so V2 and V3 never
+  // evict such a row. Return None for it, so it is kept out of the timestamp 
eviction index.

Review Comment:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM: Claude Sonnet 5.5 
(`claude-sonnet-5-5`, 1M context), running as an SP2K agent on behalf of 
@HeartSaVioR.
   
   Fixed in 
[4f0f7f34db1](https://github.com/apache/spark/pull/60279/commits/4f0f7f34db1b10d05842dad17bc9aea64194621f).
 The comment now says that a NULL indexed timestamp makes the value-eviction 
predicate
   SQL-unknown and that V1 to V3 remove such a row by a separate NULL check, so 
the row is kept out of the
   timestamp index.
   
   <!-- sp2k-review10 reply 4587582229 -->
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala:
##########
@@ -721,14 +945,74 @@ class IncrementalExecution(
 
     override def apply(plan: SparkPlan): SparkPlan = {
       val planWithStateOpId = plan transform composedRule
+      // Validate the checkpoint-pinned semantics before writing state 
metadata or opening state,
+      // including a restart retrying an incomplete batch zero.
+      if (isFirstBatchWithOlderJoinWatermarkSemantics) {
+        def watermarkColumns(input: SparkPlan): String = {
+          val columns = input.output.filter(
+            _.metadata.contains(EventTimeWatermark.delayKey))
+          if (columns.isEmpty) "none" else columns.map(_.name).mkString(", ")
+        }
+        // A join's output watermark reaches every stateful operator above it. 
One that uses its
+        // input watermark reads the inputs that the tracer names, or both 
inputs when it cannot
+        // be traced. An operator uses it when an input carries an event-time 
column, when it
+        // fires event-time timeouts, or when it passes the watermark to user 
code, as
+        // transformWithState does in every time mode. The join's output 
watermark changes
+        // nothing for any other operator, such as an update-mode count on a 
key.
+        def usesInputWatermark(operator: StatefulOperator): Boolean = operator 
match {
+          case _: TransformWithStateExec | _: TransformWithStateInPySparkExec 
=> true
+          case f: FlatMapGroupsWithStateExec if f.timeoutConf == 
EventTimeTimeout => true

Review Comment:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM: Claude Sonnet 5.5 
(`claude-sonnet-5-5`, 1M context), running as an SP2K agent on behalf of 
@HeartSaVioR.
   
   Added in 
[4f0f7f34db1](https://github.com/apache/spark/pull/60279/commits/4f0f7f34db1b10d05842dad17bc9aea64194621f).
 The test restarts an old checkpoint of a key-only join followed by an 
event-time
   `flatMapGroupsWithState` and checks that it fails with 
`STREAMING_JOIN_CHECKPOINT_INCOMPATIBLE` before any state
   changes. It does not isolate the two cases of `usesInputWatermark` that you 
name: event-time timeouts require a
   watermarked column in the operator's input, and the planned input keeps it, 
so the general rule that counts any
   operator whose input has a watermarked column already covers these 
operators, and removing the two cases does not
   change the result. If you know a query in which the planned input has none, 
please tell us. `applyInPandasWithState`
   needs Python workers, so it is not tested.
   
   <!-- sp2k-review10 reply 4587582160 -->
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -717,21 +738,111 @@ case class StreamingSymmetricHashJoinExec(
         Predicate.create(Literal(false), Seq.empty).eval _  // false = do not 
remove if no predicate
     }
 
+    // A NULL in the column that the state watermark predicate tests makes the 
predicate unknown,
+    // so eviction never removes the row. The row cannot match either: that 
column is an equality
+    // key, or a comparison in the join condition bounds it. Handle the row 
like one that fails
+    // the pre-join filter.
+    // The check takes the generated key and the input row, so the key is 
computed only once.
+    private[this] val isEvictionColumnNull: (UnsafeRow, UnsafeRow) => Boolean =
+      stateWatermarkPredicate match {
+        case Some(JoinStateKeyWatermarkPredicate(expr, _, _)) =>
+          // Only a NULL key fails equality. A struct key with a NULL field 
can still be equal.
+          val ordinal = expr.collectFirst { case b: BoundReference => 
b.ordinal }.get
+          (key, _) => key.isNullAt(ordinal)
+        case Some(JoinStateValueWatermarkPredicate(LessThanOrEqual(column, _), 
_, _)) =>
+          // Test the compared column, not the predicate: the predicate holds 
the cutoff, which
+          // changes every batch and would generate and compile new code each 
time.
+          val isNull = Predicate.create(IsNull(column), inputAttributes)
+          (_, row) => isNull.eval(row)
+        case _ =>
+          (_, _) => false
+      }
+
+    // V1 to V3 eviction tests every stored row each batch, so it also removes 
a row whose
+    // eviction column is NULL. This version never stores such a row, but an 
older version did,
+    // and the row can never match. isEvictionColumnNull reads only the key 
for a key predicate
+    // and only the row for a value predicate.
+    private[this] val stateKeyEvictionFunc: UnsafeRow => Boolean =
+      key => stateKeyWatermarkPredicateFunc(key) || isEvictionColumnNull(key, 
null)

Review Comment:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM: Claude Sonnet 5.5 
(`claude-sonnet-5-5`, 1M context), running as an SP2K agent on behalf of 
@HeartSaVioR.
   
   Added in 
[4f0f7f34db1](https://github.com/apache/spark/pull/60279/commits/4f0f7f34db1b10d05842dad17bc9aea64194621f).
 The checkpoint 
`checkpoint-version-4.3.0-streaming-join-null-equality-key-left-outer-v3` was 
written by a real Spark 4.3.0 build in state format 3, for a left outer join on 
`leftKey = rightKey AND leftTime = rightTime`, and it holds a left row with a 
NULL key, as that version stored it. The test restores it through the copy 
helper, so no local path is involved, and checks that this version outputs the 
row padded with nulls and that no state row for it remains: only the rows of 
keys 4 and 5 stay. With the NULL check removed from the key eviction function, 
the test fails, because the row is never output.
   
   <!-- sp2k-review10 reply 4587582268 -->
   



##########
docs/streaming/ss-migration-guide.md:
##########
@@ -25,6 +25,136 @@ Please refer [Migration Guide: SQL, Datasets and 
DataFrame](../sql-migration-gui
 
 ## Upgrading from Structured Streaming 4.3 to 4.4
 
+- Since Spark 4.4, left outer and left semi stream-stream joins require a 
watermark on the
+  right input and a time condition that limits how late a matching right row 
can arrive.
+  Right outer joins require the corresponding settings on the left; full outer 
joins require
+  them on both sides. An equality key counts as such a time condition when it 
is the other
+  input's event time, or that event time shifted by constant intervals, except 
a shift with
+  months, years, or a day-time interval of 24 hours or more that can move a 
time backward. To
+  decide this without the session time zone, Spark counts each such day as at 
least 12 hours and

Review Comment:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM: Claude Sonnet 5.5 
(`claude-sonnet-5-5`, 1M context), running as an SP2K agent on behalf of 
@HeartSaVioR.
   
   Fixed in 
[1a36b6c97e2](https://github.com/apache/spark/pull/60280/commits/1a36b6c97e28e2666ca2503c4a4f77bdbe21a45d).
 The migration guide and the join guide now give both lengths, a day as 12 to 
36 hours
   and a month as 28 to 31 such days, say that an added term counts at its 
shortest length and a subtracted one
   at its longest, and that the total must never be negative. Both name 
`rightTime + INTERVAL 5 DAYS - INTERVAL 2 DAYS`
   and `rightTime + INTERVAL 1 MONTH - INTERVAL 15 DAYS` as keys that do not 
count.
   
   <!-- sp2k-review10 reply 4587582037 -->
   



##########
common/utils/src/main/resources/error/error-conditions.json:
##########
@@ -8165,6 +8165,31 @@
     ],
     "sqlState" : "55019"
   },
+  "STREAMING_JOIN_CHECKPOINT_INCOMPATIBLE" : {
+    "message" : [
+      "Cannot reuse the checkpoint for the stream-stream join with condition 
<joinCondition>. Watermarked columns: left [<leftWatermarkColumns>], right 
[<rightWatermarkColumns>].",
+      "This Spark version changes how watermarks determine which rows can 
still match. Spark cannot verify that rows saved by the previous version can be 
reused safely for this join. Start the query with a new checkpoint and replay 
the required input, accounting for previously written results to avoid 
duplicates and correct any missing or incorrect output."
+    ],
+    "sqlState" : "0A000"
+  },
+  "STREAMING_JOIN_UNBOUNDED_DOWNSTREAM_EVENT_TIME" : {
+    "message" : [
+      "The append-mode aggregation after a stream-stream join uses the event 
time <eventTime> of the join's <side> input, but the join has no bound on that 
event time for the state of that input, so it holds back its output watermark 
and the aggregation would never emit results."
+    ],
+    "subClass" : {
+      "TIME_CONSTRAINT" : {
+        "message" : [
+          "Add a time constraint that limits how late a matching <otherSide> 
row can arrive, aggregate the event time of an input whose state the join can 
bound, or use the update output mode. A bound on the event time comes from an 
equality key that shifts the other input's event time by an exact interval 
(under one day, or timestampadd in hours, minutes or seconds), or from a range 
condition used in place of a shifted equality. To run the query anyway, set 
<config> to false."

Review Comment:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM: Claude Sonnet 5.5 
(`claude-sonnet-5-5`, 1M context), running as an SP2K agent on behalf of 
@HeartSaVioR.
   
   Fixed in 
[1a36b6c97e2](https://github.com/apache/spark/pull/60280/commits/1a36b6c97e28e2666ca2503c4a4f77bdbe21a45d).
 `STREAMING_JOIN_UNBOUNDED_DOWNSTREAM_EVENT_TIME` now has the sub-conditions 
`TIME_CONSTRAINT_OR_UPDATE_MODE` and 
`WATERMARK_AND_TIME_CONSTRAINT_OR_UPDATE_MODE`, which offer the update output 
mode, and `TIME_CONSTRAINT` and `WATERMARK_AND_TIME_CONSTRAINT`, which do not. 
The error picks the first pair only when the analyzed plan has no stream-stream 
outer join, because the update mode rejects such a join at analysis, even when 
the optimizer later turns it into an inner join, as the null filter of a window 
aggregation does. The tests check the sub-condition for an inner join, and for 
a left outer join whose right input has the watermark.
   
   <!-- sp2k-review10 reply 4587582060 -->
   



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