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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -680,9 +680,12 @@ case class StreamingSymmetricHashJoinExec(
       joinStateManagerStoreGenerator: JoinStateManagerStoreGenerator,
       joinKeyOrdinalForWatermark: Option[Int]) {
 
-    // Filter the joined rows based on the given condition.
-    val preJoinFilter =
-      Predicate.create(preJoinFilterExpr.getOrElse(Literal(true)), 
inputAttributes).eval _
+    // Filter the joined rows based on the given condition. A row whose 
watermarked join key is
+    // NULL can never match, and eviction by that key may never reach it, so 
it fails this filter.
+    val preJoinFilter = Predicate.create(
+      (preJoinFilterExpr ++ joinKeyOrdinalForWatermark.map(i => 
IsNotNull(joinKeys(i))))

Review Comment:
   **Nit (P3):** `IsNotNull` evaluates its child in full: its generated code is 
the child's code plus a null test (`nullExpressions.scala:582-591`), and this 
predicate and `keyGenerator` are separate generated classes. So when the key at 
`joinKeyOrdinalForWatermark` is a computed expression on this input, as on the 
right side of `lk = rk AND lt = to_timestamp(rs)` with the watermark on `lt`, 
this predicate evaluates `to_timestamp(rs)` for every row that passes the 
side-only conjuncts, and `keyGenerator(thisRow)` at 
`StreamingSymmetricHashJoinExec.scala:854` evaluates it again. On the base 
branch the join task evaluated it once. Results and state are unchanged; the 
extra CPU grows with this input's rows times the expression's cost, small for 
interval arithmetic and larger for casts, parsing or UDFs. This comes from 
reading the code; the cost has not been measured. Bare-column keys, such as the 
window and timestamp keys in the new tests, pay only a null-bit read.
   
   **Recommended change:** In StreamingSymmetricHashJoinExec.scala, build 
preJoinFilter from preJoinFilterExpr alone, as on the base branch, and in 
storeAndJoinWithOtherSide, right after val key = keyGenerator(thisRow) at line 
854, send a row whose projected key is NULL at joinKeyOrdinalForWatermark to 
generateFilteredJoinedRow(thisRow) instead of probing the other side and 
storing it. Keep the comment that explains why such a row can never match next 
to the new check. In the stream-stream join tests, add a case whose watermarked 
key is compared with a computed expression on the other input, such as a 
deterministic UDF that counts its calls.
   
   **Why this works:** The key projection sets the null bit of field i exactly 
when joinKeys(i) evaluates to NULL, so testing key.isNullAt(i) on the row that 
keyGenerator already produced routes every row as IsNotNull(joinKeys(i)) does, 
without evaluating the expression again. The side-only predicate still runs 
first, so the key is evaluated only for rows it passes, as on the base branch.
   
   **Compatibility:** Rows whose watermarked equality key is NULL keep the PR's 
handling: an outer join emits them padded with NULLs in the batch they arrive 
in, other joins and sides drop them, and none of them enters state.
   
   **Risks:** Rows whose watermarked key is NULL now pay one key projection 
before they are rejected, as every row that passed the side-only conjuncts did 
on the base branch; only those rows are affected, results do not change, and 
returning to the predicate form restores the current cost.
   
   **Constraints:** The side-only predicate must still run before the key 
projection, so the key is evaluated only for rows that pass it, as on the base 
branch. A row whose watermarked key is NULL must reach 
generateFilteredJoinedRow before any probe of the other side's state, any 
append, and any state format V4 event-time read from its key.
   
   **Exclusions:**
   - NULLs in the equality keys without a watermark and rows with a NULL 
watermarked key already stored in a checkpoint keep their current handling, 
which the PR leaves to SPARK-61382 and leaves in state respectively.
   
   **Verification:**
   - **Regression:** For a stream-stream join whose watermarked key is compared 
with a computed expression on the other input, such as a deterministic UDF that 
counts its calls, a micro-batch of n rows evaluates that expression no more 
often than on the base branch, which is n fewer evaluations than the PR's 
current code performs.
   - **Compatibility:** Rows whose watermarked key is NULL, on either input, 
keep the handling that the PR's tests check under state formats V2, V3 and V4: 
outer joins emit them padded with NULLs in their batch, inner joins and 
non-preserved sides drop them, no such row stays in state, and V4 raises no 
NullPointerException for a NULL window key.
   - **Inspection:** The pre-join predicate is built from the side-only 
conjuncts alone, and the NULL test for the watermarked key reads the projected 
key row instead of evaluating a join key expression.



##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinSuite.scala:
##########
@@ -2069,6 +2069,74 @@ abstract class StreamingOuterJoinBase extends 
StreamingJoinSuite {
     }
   }
 
+  for {
+    joinType <- Seq("inner", "left_outer", "full_outer")
+    windowKey <- Seq(true, false)
+    nullsInFirstBatch <- Seq(true, false)
+  } {
+    val keyType = if (windowKey) "window" else "timestamp"
+    val batch = if (nullsInFirstBatch) "the first" else "a later"
+    test(s"SPARK-62046: $joinType join with NULL watermarked $keyType keys in 
$batch batch") {
+      val leftInput = MemoryStream[(Int, Int)]
+      val nullInput = MemoryStream[Int]
+      val rightInput = MemoryStream[(Int, Int)]
+      val leftWithTime = leftInput.toDF().toDF("lk", "t")
+        .select($"lk", timestamp_seconds($"t").as("lt"))
+        .withWatermark("lt", "10 seconds")
+      val keyed = leftWithTime.select($"lk",
+        (if (windowKey) window($"lt", "10 seconds") else $"lt").as("lw"))
+      // A union keeps the watermark on lw, which is NULL for the rows of 
nullInput.
+      val left = keyed.union(nullInput.toDF().toDF("lk")
+        .select($"lk", lit(null).cast(keyed.schema("lw").dataType).as("lw")))
+      // The right key has no watermark and is NULL for a negative input.
+      val rightTime = when($"s" >= 0, timestamp_seconds($"s"))
+      val rightKey = if (windowKey) {
+        when($"s" >= 0, struct(rightTime.as("start"),
+          (rightTime + expr("INTERVAL 10 SECONDS")).as("end")))
+      } else {
+        rightTime
+      }
+      val right = rightInput.toDF().toDF("rk", "s").select($"rk", 
rightKey.as("rw"))
+      val (leftEnd, rightEnd) = if (windowKey) ($"lw.end", $"rw.end") else 
($"lw", $"rw")
+      val joined = left.join(right, expr("lk = rk AND lw = rw"), joinType)

Review Comment:
   **Nit (P3):** This matrix, like the new full outer test in 
`StreamingFullOuterJoinBase`, joins on `lk = rk AND lw = rw` only, so it 
exercises the new pre-join check alone. When the join also has a conjunct on 
one input, `StreamingSymmetricHashJoinExec.scala:686-687` builds 
`And(sideConjunct, IsNotNull(key))` instead, and the existing side-condition 
tests (`setupWindowedJoinWithLeftCondition`, 
`setupWindowedJoinWithRightCondition`) use `window()` keys, which are never 
NULL. A change that kept the NULL check only when no side-only conjunct exists, 
such as `preJoinFilterExpr.orElse(guard)`, would pass the whole suite. Cases in 
this matrix, which already runs on V2, V3 and V4, would cover that combination 
if their condition also had a conjunct on a preserved input that the NULL-key 
rows satisfy, such as `lk > 0` for left outer and `lk > 0 AND rk > 0` for full 
outer. A conjunct on a preserved input stays in the join instead of being 
pushed below it, so the operator sees it. This is a t
 est gap only; no current behavior is wrong.
   
   **Verification:**
   - **Regression:** With a side-only conjunct on a preserved input that the 
NULL-key rows satisfy, the new cases fail if the NULL test for the watermarked 
key is skipped for a side that has such a conjunct: on state formats V2 and V3 
the NULL-key row would stay in state or join NULL to NULL, and on V4 a NULL 
window key would raise a NullPointerException.
   - **Behavior:** The new cases pass under state formats V2, V3 and V4 with 
window and timestamp keys: each batch's output matches, the NULL-key rows 
appear padded with NULLs in the batch they arrive in, and the final state holds 
no NULL-key row.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -680,9 +680,12 @@ case class StreamingSymmetricHashJoinExec(
       joinStateManagerStoreGenerator: JoinStateManagerStoreGenerator,
       joinKeyOrdinalForWatermark: Option[Int]) {
 
-    // Filter the joined rows based on the given condition.
-    val preJoinFilter =
-      Predicate.create(preJoinFilterExpr.getOrElse(Literal(true)), 
inputAttributes).eval _
+    // Filter the joined rows based on the given condition. A row whose 
watermarked join key is
+    // NULL can never match, and eviction by that key may never reach it, so 
it fails this filter.

Review Comment:
   **Nit (P3):** The PR description defers two cases that still have problems 
this PR fixes, but this comment covers only the watermarked key. NULLs in 
equality keys without a watermark (SPARK-61382) are still stored and can still 
match each other: a full outer join on `lk = rk AND lw = rw` still pairs a left 
`(NULL, w)` with a right `(NULL, w)`. And rows with a NULL watermarked key that 
a checkpoint already holds stay in state, because state formats V2 and V3 never 
evict them. Without a note, the filter reads as complete NULL-key handling, and 
a later change to it or to eviction could miss both. The gap has no runtime 
effect; a TODO would make the deferral visible, for example:
   
   ```suggestion
       // NULL can never match, and eviction by that key may never reach it, so 
it fails this filter.
       // TODO(SPARK-61382): NULLs in the other equality keys still reach the 
state and can match
       //   each other. Rows with a NULL watermarked key that a checkpoint 
already holds are not
       //   drained: state formats V2 and V3 never evict them.
   ```
   
   **Verification:**
   - **Inspection:** The comment at the NULL test for the watermarked key in 
StreamingSymmetricHashJoinExec.scala names SPARK-61382 for NULLs in the other 
equality keys and says that rows with a NULL watermarked key already stored in 
a checkpoint's state are not drained, and the change touches no code.



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