HeartSaVioR commented on code in PR #60307:
URL: https://github.com/apache/spark/pull/60307#discussion_r4550509286
##########
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:
> [!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.
Added "left semi join keeps a same-batch match bounded by another right
column when both watermarks are equal". It runs your case with
`allowMultiple=false`: both watermarks are 100 s, and the right row (1, 110 s,
rightExpiry 1000 s) and the left row (1, 120 s) arrive in one batch. It asserts
the output only, so it stays valid when SPARK-61344 applies the cutoff to
`rightExpiry`. It runs in state formats 2, 3 and 4. I checked that it fails if
the store path is skipped whenever the two watermarks are equal.
<!-- sp2k-review4 reply 4547695255 -->
##########
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:
> [!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.
Added left-first variants:
- the two minute-to-hour skip tests also run with `leftTime + INTERVAL 1
MINUTE <= rightTime AND leftTime + INTERVAL 1 HOUR >= rightTime`;
- the whole-day tests have a fourth bound, `leftTime + INTERVAL 1 DAY <=
rightTime AND leftTime + INTERVAL 2 DAYS >= rightTime`, in America/Los_Angeles
and UTC.
Each expects the same output and state rows as its right-first counterpart.
With the left-first orientation dropped from the filter, the two minute-to-hour
cases and the UTC whole-day case fail. The America/Los_Angeles case stores the
row either way. By my reading, it would fail under the loosening you describe,
which accepts whole days in that zone as exact. I did not run that mutation.
<!-- sp2k-review4 reply 4547695267 -->
--
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]