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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -722,6 +722,20 @@ case class StreamingSymmetricHashJoinExec(
     private[this] val allowMultipleStatefulOperators: Boolean =
       conf.getConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE)
 
+    // For the right side of a left semi join: whether a cutoff at the 
late-events watermark that
+    // is exact today shows that no left row passing late filtering can match 
a key and row.
+    private[this] val noLeftRowCanMatch: (UnsafeRow, UnsafeRow) => Boolean =

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 
[77e611b42e4](https://github.com/apache/spark/pull/60307/commits/77e611b42e4bbd2ce927b0f89238b2e978099d8a).
 `noLeftRowCanMatch` is now a `lazy val`, so a task whose right rows all stay 
in state never derives the cutoffs or compiles the predicates. All left semi 
tests keep their output and state row counts in formats 2, 3 and 4.
   
   <!-- sp2k-review3 reply 4537421462 -->
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -296,6 +299,82 @@ object StreamingSymmetricHashJoinHelper extends Logging {
     JoinStateWatermarkPredicates(leftStateWatermarkPredicate, 
rightStateWatermarkPredicate)
   }
 
+  /**
+   * For the right input of a left semi join, cutoffs at the late-events 
watermark that are exact
+   * today: no left row that passes late filtering can match a right row at or 
below them. Returns
+   * a predicate on the right join key and a predicate on the right input row, 
either of which
+   * can be absent.
+   *
+   * The key cutoff applies when the left input's late-filtered column is the 
left join key at an
+   * ordinal: the right key at that ordinal must then be above the late-events 
watermark. The
+   * value cutoff is on the right event time, solved only from conjuncts that 
compare it with the
+   * left input's late-filtered column, each shifted only by literal intervals 
without a day or
+   * month part, and with no cast. Any other conjunct can give a cutoff that 
is too high, so it

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 
[77e611b42e4](https://github.com/apache/spark/pull/60307/commits/77e611b42e4bbd2ce927b0f89238b2e978099d8a).
 The doc now says "with no cast other than one from timestamp to timestamp". 
The truncating cast stays as the example of what the rule rejects.
   
   <!-- sp2k-review3 reply 4537421489 -->
   



##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinSuite.scala:
##########
@@ -2425,6 +2425,182 @@ abstract class StreamingLeftSemiJoinBase extends 
StreamingJoinSuite {
     }
   }
 
+  // A left semi join processes the right input before the left input. A right 
row at or below
+  // its eviction cutoff passes late filtering when it is above the 
late-events watermark, and
+  // the left rows of the same batch must still find it. Each case runs a 
batch whose
+  // late-events watermark is 100 seconds and whose eviction watermark is 
`watermark` seconds.
+  // (name, condition, left time, right time, watermark, state rows after the 
second batch and
+  // after the third)
+  for ((name, condition, leftTime, rightTime, watermark, rowsBefore, 
rowsAfter) <- Seq(
+      ("equal event times", "leftTime = rightTime", 102, 102, 105, 2L, 0L),
+      // The left key leftTime + 10 seconds of (7, 100) stays above the 
100-second cutoff.
+      ("a key shifted by less than the watermark step",
+        "leftTime + INTERVAL 10 SECONDS = rightTime", 120, 130, 150, 3L, 1L),
+      // A value cutoff of the watermark less 10 seconds and 1 ms: (1, 130) is 
below 139.999 s.
+      ("a time interval",
+        "leftTime BETWEEN rightTime - INTERVAL 10 SECONDS AND rightTime + 
INTERVAL 10 SECONDS",
+        125, 130, 150, 4L, 2L))) {
+    test(s"left semi join keeps a same-batch match between the watermarks: 
$name") {
+      withSQLConf(SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> 
"false") {
+        val leftInput = MemoryStream[(Int, Int)]
+        val rightInput = MemoryStream[(Int, Int)]
+        val left = leftInput.toDF()
+          .select($"_1".as("leftKey"), timestamp_seconds($"_2").as("leftTime"))
+          .withWatermark("leftTime", "0 seconds")
+        val right = rightInput.toDF()
+          .select($"_1".as("rightKey"), 
timestamp_seconds($"_2").as("rightTime"))
+          .withWatermark("rightTime", "0 seconds")
+        val joined = left.join(right, expr(s"leftKey = rightKey AND 
$condition"), "left_semi")
+          .select($"leftKey", $"leftTime".cast("int"))
+
+        testStream(joined)(
+          MultiAddData(leftInput, (7, 100))(rightInput, (8, 100)),
+          CheckNewAnswer(),
+          MultiAddData(leftInput, (7, watermark))(rightInput, (8, watermark)),
+          CheckNewAnswer(),
+          assertNumStateRows(total = rowsBefore, updated = 4),
+          MultiAddData(leftInput, (1, leftTime))(rightInput, (1, rightTime)),
+          CheckNewAnswer((1, leftTime)),
+          // The right row is stored for the left row to probe and removed at 
the end of the
+          // batch, together with the other rows at or below the cutoffs.
+          assertNumStateRows(total = rowsAfter, updated = 1))
+      }
+    }
+  }
+
+  // The right cutoff comes from a bound on rightExpiry but is applied to 
rightTime, so a right
+  // row can be at or below the cutoff at the late-events watermark and still 
match a left row
+  // of the same batch. Storing only the right rows above that cutoff would 
drop this match.
+  // Each right row is evicted in the same batch whether the cutoff is applied 
to rightTime or
+  // to rightExpiry, so the state rows stay the same when SPARK-61344 applies 
it to rightExpiry.
+  test("left semi join keeps a same-batch match bounded by another right 
column") {
+    withSQLConf(SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> 
"false") {
+      val leftInput = MemoryStream[(Int, Int, Int)]
+      val rightInput = MemoryStream[(Int, Int, Int)]
+      val left = leftInput.toDF()
+        .select($"_1".as("leftKey"), timestamp_seconds($"_2").as("leftTime"))
+        .withWatermark("leftTime", "0 seconds")
+      val right = rightInput.toDF()
+        .select($"_1".as("rightKey"), timestamp_seconds($"_2").as("rightTime"),
+          timestamp_seconds($"_3").as("rightExpiry"))
+        .withWatermark("rightTime", "0 seconds")
+      val joined = left.join(right, expr("leftKey = rightKey AND " +
+        "rightExpiry >= leftTime + INTERVAL 30 SECONDS AND " +
+        "leftTime >= rightTime - INTERVAL 1 HOUR"), "left_semi")
+        .select($"leftKey", $"leftTime".cast("int"))
+
+      testStream(joined)(
+        MultiAddData(leftInput, (7, 100, 0))(rightInput, (8, 100, 100)),
+        CheckNewAnswer(),
+        MultiAddData(leftInput, (7, 150, 0))(rightInput, (8, 150, 150)),
+        CheckNewAnswer(),
+        assertNumStateRows(total = 3, updated = 4),
+        // The late-events watermark is 100 seconds, and the right cutoff at 
it is 130 seconds
+        // less 1 ms: above the right row's rightTime of 110 seconds, below 
its rightExpiry.
+        MultiAddData(leftInput, (1, 120, 0))(rightInput, (1, 110, 160)),
+        CheckNewAnswer((1, 120)),
+        assertNumStateRows(total = 2, updated = 1))
+    }
+  }
+
+  private def leftSemiJoin(
+      condition: String,
+      leftWatermark: Boolean = true,
+      rightWatermark: Boolean = true): (MemoryStream[(Int, Int)], 
MemoryStream[(Int, Int)],
+      DataFrame) = {
+    val leftInput = MemoryStream[(Int, Int)]
+    val rightInput = MemoryStream[(Int, Int)]
+    val leftData = leftInput.toDF()
+      .select($"_1".as("leftKey"), timestamp_seconds($"_2").as("leftTime"))
+    val rightData = rightInput.toDF()
+      .select($"_1".as("rightKey"), timestamp_seconds($"_2").as("rightTime"))
+    val left = if (leftWatermark) leftData.withWatermark("leftTime", "0 
seconds") else leftData
+    val right =
+      if (rightWatermark) rightData.withWatermark("rightTime", "0 seconds") 
else rightData
+    val joined = left.join(right, expr(s"leftKey = rightKey AND $condition"), 
"left_semi")
+      .select($"leftKey", $"leftTime".cast("int"))
+    (leftInput, rightInput, joined)
+  }
+
+  // An exact cutoff at the late-events watermark shows that no left row 
passing late filtering
+  // can match an evicted right row at or below it, so such a row is not 
stored, as before the

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 
[77e611b42e4](https://github.com/apache/spark/pull/60307/commits/77e611b42e4bbd2ce927b0f89238b2e978099d8a).
 The comment now says "so such a row is not stored, although the join otherwise 
stores the right rows a batch evicts".
   
   <!-- sp2k-review3 reply 4537421501 -->
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -296,6 +299,82 @@ object StreamingSymmetricHashJoinHelper extends Logging {
     JoinStateWatermarkPredicates(leftStateWatermarkPredicate, 
rightStateWatermarkPredicate)
   }
 
+  /**
+   * For the right input of a left semi join, cutoffs at the late-events 
watermark that are exact
+   * today: no left row that passes late filtering can match a right row at or 
below them. Returns
+   * a predicate on the right join key and a predicate on the right input row, 
either of which
+   * can be absent.
+   *
+   * The key cutoff applies when the left input's late-filtered column is the 
left join key at an
+   * ordinal: the right key at that ordinal must then be above the late-events 
watermark. The
+   * value cutoff is on the right event time, solved only from conjuncts that 
compare it with the
+   * left input's late-filtered column, each shifted only by literal intervals 
without a day or
+   * month part, and with no cast. Any other conjunct can give a cutoff that 
is too high, so it
+   * gives none here: for example a bound on another right column, an interval 
with whole days,
+   * or a truncating cast.
+   * TODO(SPARK-61344, SPARK-61381): derive exact cutoffs for those conditions 
too.
+   */
+  def getLeftSemiExactRightCutoffs(
+      leftAttributes: Seq[Attribute],
+      rightAttributes: Seq[Attribute],
+      leftKeys: Seq[Expression],
+      rightKeys: Seq[Expression],
+      condition: Option[Expression],
+      eventTimeWatermarkForLateEvents: Option[Long],
+      useFirstEventTimeColumn: Boolean): (Option[Expression], 
Option[Expression]) = {
+    // The column the left input's late filter compares with the late-events 
watermark.
+    val leftLateFiltered = WatermarkSupport.findEventTimeColumn(leftAttributes,
+      allowMultipleEventTimeColumns = useFirstEventTimeColumn)
+    val rightEventTime = WatermarkSupport.findEventTimeColumn(rightAttributes,
+      allowMultipleEventTimeColumns = useFirstEventTimeColumn)
+
+    val keyCutoff = leftLateFiltered.flatMap { column =>
+      leftKeys.indexWhere(_.semanticEquals(column)) match {
+        case ordinal if ordinal >= 0 =>
+          val rightKey = BoundReference(
+            ordinal, rightKeys(ordinal).dataType, rightKeys(ordinal).nullable)
+          watermarkExpression(Some(rightKey), eventTimeWatermarkForLateEvents)
+        case _ => None
+      }
+    }
+
+    // Whether the expression is the column shifted only by literal intervals 
that the solver
+    // counts exactly: no whole days, which Spark adds in the session time 
zone, and no months.
+    def isExactShiftOf(e: Expression, column: Attribute): Boolean = e match {
+      case a: Attribute => a.semanticEquals(column)
+      case Cast(child, TimestampType, _, _) if child.dataType == TimestampType 
=>
+        isExactShiftOf(child, column)
+      case TimestampAddInterval(start, Literal(micros: Long, _: 
DayTimeIntervalType), _) =>
+        -MICROS_PER_DAY < micros && micros < MICROS_PER_DAY && 
isExactShiftOf(start, column)

Review Comment:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM: Claude Opus 5.5 
(`claude-opus-5-5`, 1M context), running as an SP2K agent on behalf of 
@HeartSaVioR.
   
   Thanks, fixed in 
[77e611b42e4](https://github.com/apache/spark/pull/60307/commits/77e611b42e4bbd2ce927b0f89238b2e978099d8a).
 You are right that the 23- or 25-hour day only happens in zones with offset 
changes. `isExactShiftOf` now counts a whole-day part as exact when the zone 
that this `TimestampAddInterval` evaluates in has a fixed offset 
(`ZoneRules.isFixedOffset`), such as UTC. That covers a day-time interval of a 
day or more in either sign, and a calendar interval with days but no months. In 
any other zone the check is as strict as before, and months are still rejected. 
The skip only decides whether a right row that the batch evicts is written and 
removed within that batch, so it changes no stored state and does not depend on 
the zone of an earlier run.
   
   The comments in the helper and at the add-to-state check now say that the 
problem is limited to zones with daylight saving time. The whole-day test is 
now six tests: three whole-day forms (the BETWEEN bound, a negative day shift 
`rightTime - INTERVAL 1 DAY >= leftTime`, and `CAST('1 day' AS INTERVAL)`), 
each run with the session time zone set to America/Los_Angeles, where every 
evicted right row is stored, and to UTC, where the rows at or below the cutoff 
are not stored. Each Los Angeles test fails if its own day check is loosened.
   
   <!-- sp2k-review3 reply 4537421448 -->
   



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