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


##########
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:
   **Blocking (P1):** This check rejects every whole-day shift in every time 
zone, but the reason the comments give, a 23- or 25-hour day, holds only in 
zones with offset changes. In a session time zone with a fixed offset, such as 
UTC, `timestampAddDayTime` and `timestampAddInterval` add a day with 
`plusDays`, exactly 86400 s, which is what 
`StreamingJoinHelper.getStateValueWatermark` counts, so the cutoff at the 
late-events watermark is exact there.
   
   By this review's reading of the code, take `leftKey = rightKey AND rightTime 
BETWEEN leftTime + INTERVAL 1 DAY AND leftTime + INTERVAL 2 DAYS` with 0-second 
watermarks, a UTC session time zone and 
`spark.sql.streaming.statefulOperator.allowMultiple=false`, in a batch whose 
two watermarks are both 100 s. A right row at 3700 s passes late filtering and 
is evicted, because the right eviction cutoff is 86499.999 s, and a left row 
matching it would need a `leftTime` of at most 3700 - 86400 s, which is late. 
The base branch skips the row and already returns correct results for this 
query; the PR appends the row and removes it at the end of the batch. With 
in-order data and a watermark delay under a day, that is nearly every right row 
of every batch: one state-store append and removal per row with their 
delta-file or changelog records, and on state formats 1 to 3 one more value for 
every same-key left probe. In the default mode the PR likewise stores every 
evicted row at or below the exa
 ct cutoff, beyond the rows a same-batch left row can match. The earlier 
recommendation to exclude every day component was broader than needed.
   
   The whole-day test runs in America/Los_Angeles, which `SparkTestSuite` sets 
as the JVM default zone and so as the default session time zone, so it covers 
the store-all path that zones with daylight saving time keep, and no test runs 
a whole-day bound in a fixed-offset zone. Two of the three checks that reject 
day parts, the negative day-time bound and the calendar-interval `i.days == 0` 
check, also have no test that fails when they are loosened.
   
   This extends existing discussions 
[1](https://github.com/apache/spark/pull/60307#issuecomment-6792632717), 
[2](https://github.com/apache/spark/pull/60307#discussion_r4529610402), 
[3](https://github.com/apache/spark/pull/60307#discussion_r4531790506).
   
   **Recommended change:** In isExactShiftOf, count a TimestampAddInterval 
shift with a whole-day part, a day-time literal of a day or more in either sign 
or a calendar interval with days but no months, as exact when that expression's 
zoneId has fixed rules (ZoneRules.isFixedOffset), and keep rejecting it in 
every other zone. Correct the comments that give a 23- or 25-hour day as the 
reason in every zone, in the helper, at the add-to-state check and in the 
whole-day test, and narrow the TODO to zones with offset changes. The 
stream-stream left semi join tests run in America/Los_Angeles, the JVM default 
zone that SparkTestSuite sets and so the default session time zone, so the 
existing whole-day test keeps testing the store-all path; set that session time 
zone in it explicitly so the dependence is visible, and add cases under a UTC 
session time zone and for the negative day-time and calendar-day conditions.
   
   **Why this works:** In a zone whose rules have a fixed offset, plusDays adds 
exactly 86400 seconds per day, which is what the solver adds, so the cutoff 
solved at the late-events watermark is the true bound and no left row passing 
late filtering can match a right row at or below it; in a zone with offset 
changes the check still fails and the row is stored as now. Deciding per 
TimestampAddInterval from the zone it evaluates in keeps the rule exact even 
when one condition mixes zones.
   
   **Scope:** Make the left semi exactness test zone-aware for whole-day shifts 
and pin the time zone in the tests that exercise it.
   
   **Compatibility:** Joins whose shifts have no whole-day part, and every join 
in a zone with offset changes, keep their current cutoffs and stored rows.
   
   **Risks:** If the check read a zone other than the one TimestampAddInterval 
evaluates in, or treated a zone with recorded offset changes as fixed, the join 
would skip a right row that a same-batch left row matches and silently drop 
that left row; reading the expression's own zoneId and requiring 
ZoneRules.isFixedOffset avoids both, and zones such as Asia/Shanghai whose 
rules record past changes simply keep storing. The skip lowers 
numUpdatedStateRows and numRemovedStateRows for whole-day bounds in 
fixed-offset zones, back to the base branch's counts under allowMultiple=false; 
a wrong skip is the only harmful outcome, and the tests pin both zone kinds.
   
   **Constraints:** Keep months rejected in calendar intervals and year-month 
shifts rejected, since the solver treats months as invalid. Leave the solver, 
getStateWatermarkPredicates, eviction, the format 4 range-scan offsets, inner 
and outer joins and the left side's decision unchanged. Keep every check in 
zones with offset changes exactly as strict as now.
   
   **Exclusions:**
   - Exact cutoffs for whole-day bounds in zones with daylight saving time, 
truncating casts, bounds on other right columns and left-shifted keys stay with 
SPARK-61344 and SPARK-61381, pending the open decision on their cost.
   
   **Success:** In a fixed-offset session time zone such as UTC, a left semi 
join whose right event time is bounded below by the left late-filtered column 
plus a whole-day shift skips every evicted right row at or below the exact 
cutoff, and under allowMultiple=false writes and removes the same right state 
rows as the base branch. In a session time zone with daylight saving time, a 
positive or negative whole-day day-time shift and a calendar interval with days 
still give no cutoff, and every evicted right row is stored. Every same-batch 
match the PR restores is still emitted.
   
   **Verification:**
   - **Regression:** With the session time zone set to UTC, the condition 
rightTime BETWEEN leftTime + INTERVAL 1 DAY AND leftTime + INTERVAL 2 DAYS 
skips an evicted right row at or below the cutoff at the late-events watermark 
and still emits a same-batch match above it in the default mode, and under 
allowMultiple=false writes the same updated and removed right state rows as the 
base branch, under state formats 2, 3 and 4.
   - **Regression:** With the session time zone set to America/Los_Angeles, the 
same whole-day condition, a negative day-time shift on the right event time 
such as rightTime - INTERVAL 1 DAY >= leftTime, and a calendar interval with 
days, such as one from CAST('1 day' AS INTERVAL) or a legacy interval literal, 
each store every evicted right row, so a test fails if any of the three day 
conditions is loosened.
   - **Compatibility:** The existing same-batch, rightExpiry, exact-cutoff and 
windowed left semi join tests and the inner and outer stream-stream join tests 
keep their output and state-row counts.



##########
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:
   **Nit (P3):** `noLeftRowCanMatch` is built when each right-side joiner is 
constructed, so every right-side task of a left semi join with a cutoff runs 
`getLeftSemiExactRightCutoffs`, logs the solver's two INFO lines per solved 
conjunct, and compiles up to two predicates with `Predicate.create`. The 
predicates inline the late-events watermark as a long literal, so their 
generated code differs in every batch and is compiled again on each executor, 
next to the eviction predicates the base branch already compiles. The function 
is read only after `isNotEvictingInThisBatch` is false, so a task whose right 
rows all stay in state, such as one for `leftTime = rightTime` with in-order 
data, never needs it. The cost is bounded per batch and does not grow with 
rows; deferring the derivation to first use removes it there:
   
   ```suggestion
       private[this] lazy val noLeftRowCanMatch: (UnsafeRow, UnsafeRow) => 
Boolean =
   ```
   
   **Verification:**
   - **Compatibility:** Every stream-stream left semi join test keeps its 
output and its total, updated and removed state rows under state formats 2, 3 
and 4, including the exact-cutoff skip tests, whose cutoffs are now built on 
first use.
   - **Inspection:** The cutoff derivation and its predicate compilation are 
reachable only from the right side's add-to-state check after the row is found 
to be evicted in this batch.



##########
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:
   **Nit (P3):** This sentence says the conjuncts have no cast, but 
`isExactShiftOf` accepts `Cast(child, TimestampType, _, _)` when the child is 
already a timestamp, the identity cast that resolving `timestamp + interval` 
wraps around `TimestampAddInterval`. That cast changes no value, so behavior is 
unaffected, but a maintainer extending this rule reads that every cast is 
rejected. Wording such as "with no cast other than one from timestamp to 
timestamp" matches the code, and the sentence's own example, a truncating cast, 
still names what the rule rejects.
   
   **Verification:**
   - **Inspection:** The scaladoc names the timestamp-to-timestamp cast as the 
only cast it admits and a truncating cast as one it rejects, matching 
isExactShiftOf.



##########
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:
   **Nit (P3):** The comment ends "so such a row is not stored, as before the 
left semi join stored the right rows a batch evicts." Once this is merged, 
"before" has no referent, and the past tense reads as if the join used to store 
these rows. Stating the current behavior avoids that, for example: "so such a 
row is not stored, although the join otherwise stores the right rows a batch 
evicts."
   
   **Verification:**
   - **Inspection:** The comment above the minute-to-hour condition describes 
the current skip without referring to how the join behaved before this change.



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