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


##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinSuite.scala:
##########
@@ -2425,6 +2425,231 @@ 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") {

Review Comment:
   **Nit (P3):** Like every new test that asserts a same-batch match through 
the new store path, this one runs that batch with the late-events watermark 
below the eviction watermark, here 100 s and 150 s. The description also claims 
this match "even when both watermarks are equal, as under 
`spark.sql.streaming.statefulOperator.allowMultiple=false`", but the only test 
under that setting uses the minute-to-hour bound, whose evicted right rows all 
lie at or below its exact cutoff, so it asserts only the skip. Every new test 
also disables no-data batches, so none runs a data batch after a no-data batch, 
the other case where both watermarks are equal.
   
   By this review's reading of the code, under `allowMultiple=false` with this 
condition and both watermarks at 100 s, right (1, 110 s, rightExpiry 1000 s) 
passes late filtering and is evicted in its batch, because the right eviction 
cutoff is 129.999 s, and left (1, 120 s) of the same batch matches it. If the 
add-to-state check in `StreamingSymmetricHashJoinExec` skipped storing such a 
row whenever the two watermarks are equal, on the premise that no evicted right 
row can then match, that left row would be dropped again as on the base branch, 
and no test would fail.
   
   Running this case once more under `allowMultiple=false`, with those two rows 
in a batch whose watermarks are both 100 s, and asserting that the left row is 
emitted would pin it. Asserting the output rather than that batch's state rows 
keeps the test valid once SPARK-61344 applies the cutoff to `rightExpiry`, when 
this right row is no longer evicted.
   
   **Verification:**
   - **Regression:** The new case fails on the base branch, which does not emit 
the left row, and fails if the store path for evicted right rows is skipped 
whenever the late-events and eviction watermarks are equal, in state formats 2, 
3 and 4.
   - **Behavior:** The case emits the matching left row in its own batch, and 
its expected output stays the same whether the right cutoff is applied to 
rightTime or, after SPARK-61344, to rightExpiry.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -296,6 +300,88 @@ 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 month
+   * part, and with no cast other than one from timestamp to timestamp. A day 
part counts only in
+   * a time zone with a fixed offset, such as UTC, where Spark adds a day as 
24 hours, as the
+   * solver counts it. 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 in a time
+   * zone with daylight saving time, 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 months, and whole days only where the zone that the 
shift adds them in
+    // has a fixed offset. Elsewhere a day can be 23 or 25 hours, but the 
solver counts 24.
+    def addsDaysExactly(shift: TimestampAddInterval): Boolean =
+      shift.timeZoneId.exists(zone => 
DateTimeUtils.getZoneId(zone).getRules.isFixedOffset)
+    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 s @ TimestampAddInterval(start, Literal(micros: Long, _: 
DayTimeIntervalType), _) =>
+        (-MICROS_PER_DAY < micros && micros < MICROS_PER_DAY || 
addsDaysExactly(s)) &&
+          isExactShiftOf(start, column)
+      case s @ TimestampAddInterval(start, Literal(i: CalendarInterval, 
CalendarIntervalType), _) =>
+        i.months == 0 && (i.days == 0 || addsDaysExactly(s)) && 
isExactShiftOf(start, column)
+      case _ => false
+    }
+    def conjuncts(e: Expression): Seq[Expression] = e match {
+      case And(left, right) => conjuncts(left) ++ conjuncts(right)
+      case Between(input, lower, upper, _) =>
+        Seq(GreaterThanOrEqual(input, lower), LessThanOrEqual(input, upper))
+      case other => Seq(other)
+    }
+    val valueCutoff = for {
+      left <- leftLateFiltered
+      right <- rightEventTime
+      watermark <- eventTimeWatermarkForLateEvents
+      cutoff <- condition.toSeq.flatMap(conjuncts).filter {
+        case c: BinaryComparison =>
+          isExactShiftOf(c.left, right) && isExactShiftOf(c.right, left) ||
+            isExactShiftOf(c.left, left) && isExactShiftOf(c.right, right)

Review Comment:
   **Nit (P3):** This disjunct admits a value-cutoff conjunct written with the 
left late-filtered column on the comparison's left, such as `leftTime + 
INTERVAL 1 MINUTE <= rightTime`, but no test depends on it. Every test whose 
result depends on a value cutoff writes its bound with the right event time 
first: the two minute-to-hour skip tests, the six whole-day tests and the 
truncating-cast test. The left-first bounds in the tests give a cutoff below 
the late-events watermark, so they skip no right row that passes late filtering 
(`leftTime <= rightTime + INTERVAL 10 SECONDS` in the new time-interval case, 
`leftTime <= rightTime + interval 5 seconds` in the range-condition test, and 
`leftTime < rightTime + INTERVAL 30 SECONDS` in the output-watermark tests and 
in `MultiStatefulOperatorsSuite`), or they give no cutoff at all (`leftTime >= 
rightTime - INTERVAL 1 HOUR` in the `rightExpiry` test). No test calls 
`getLeftSemiExactRightCutoffs` directly.
   
   So, by this review's reading of the code, every test still passes if this 
line is dropped or loosened. Without it, the minute-to-hour bound written 
left-first, `leftTime + INTERVAL 1 MINUTE <= rightTime AND leftTime + INTERVAL 
1 HOUR >= rightTime`, would store and remove the right row (2, 130) that the 
exact value-cutoff test expects to be skipped. Loosened to admit whole days in 
any zone, it would let `leftTime + INTERVAL 1 DAY <= rightTime` in 
America/Los_Angeles skip an evicted right row that a same-batch left row 
matches across a spring-forward transition, where Spark adds that day as 23 
hours.
   
   Running the two minute-to-hour skip tests and the whole-day bounds also with 
the bound written left-first, such as `leftTime + INTERVAL 1 DAY <= rightTime 
AND leftTime + INTERVAL 2 DAYS >= rightTime` next to the existing whole-day 
bounds, with the same expected output and state-row counts, would give this 
line the failure signal that the line above already has.
   
   **Verification:**
   - **Regression:** Dropping the left-first orientation from the exactness 
filter makes the left-first minute-to-hour cases fail on their updated state 
rows, in both watermark modes and in state formats 2, 3 and 4.
   - **Regression:** Letting the left-first orientation admit a whole-day shift 
in a zone whose offset varies makes the left-first America/Los_Angeles case 
fail on its updated state rows.
   - **Behavior:** Each left-first case reports the same output and the same 
total and updated state rows as its right-first counterpart.



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