HeartSaVioR commented on code in PR #60286:
URL: https://github.com/apache/spark/pull/60286#discussion_r4603159934
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -224,98 +238,390 @@ object StreamingSymmetricHashJoinHelper extends Logging {
WatermarkSupport.findEventTimeColumn(rightAttributes,
allowMultipleEventTimeColumns = useFirstEventTimeColumn)
- val joinKeyOrdinalForWatermark: Option[Int] =
findJoinKeyOrdinalForWatermark(
- leftKeys, rightKeys)
-
def getOneSideStateWatermarkPredicate(
oneSideInputAttributes: Seq[Attribute],
oneSideJoinKeys: Seq[Expression],
- otherSideInputAttributes: Seq[Attribute]):
Option[JoinStateWatermarkPredicate] = {
- val isWatermarkDefinedOnInput =
oneSideInputAttributes.exists(_.metadata.contains(delayKey))
+ otherSideInputAttributes: Seq[Attribute],
+ otherSideJoinKeys: Seq[Expression]):
Option[JoinStateWatermarkPredicate] = {
+ // State is bounded by future input from the opposite side, not by its
own watermark.
+ val joinKeyOrdinalForWatermark =
StreamingJoinHelper.getStateKeyWatermarkOrdinal(
+ otherSideJoinKeys, otherSideInputAttributes, eventTimeLags)
val isWatermarkDefinedOnJoinKey = joinKeyOrdinalForWatermark.isDefined
if (isWatermarkDefinedOnJoinKey) { // case 1 and 3 in the
StreamingSymmetricHashJoinExec docs
+ val ordinal = joinKeyOrdinalForWatermark.get
val keyExprWithWatermark = BoundReference(
- joinKeyOrdinalForWatermark.get,
- oneSideJoinKeys(joinKeyOrdinalForWatermark.get).dataType,
- oneSideJoinKeys(joinKeyOrdinalForWatermark.get).nullable)
- val expr = watermarkExpression(Some(keyExprWithWatermark),
eventTimeWatermarkForEviction)
- expr.map { e =>
- // V4 can skip keys at or below the previous watermark only if
late-input filtering
- // rejects new rows in that range on this same key. A watermark on
the other input's
- // equality key can drive eviction even when this input has no
watermark, or has one
- // on a different column. New rows can then pass late-input
filtering with keys
- // already eligible for eviction. V4 must scan from the beginning to
find them;
- // otherwise, outer joins can fail to emit null rows for these
unmatched inputs.
- val prevStateKeyWatermark =
- if (oneSideInputAttributes.find(_.metadata.contains(delayKey))
-
.exists(oneSideJoinKeys(joinKeyOrdinalForWatermark.get).semanticEquals)) {
- eventTimeWatermarkForLateEvents
- } else {
- None
- }
- // watermarkExpression only provides the expression when
eventTimeWatermarkForEviction
- // is defined.
- JoinStateKeyWatermarkPredicate(
- e,
- eventTimeWatermarkForEviction.get,
- prevStateKeyWatermark)
- }
- } else if (isWatermarkDefinedOnInput) { // case 2 in the
StreamingSymmetricHashJoinExec docs
- val stateValueWatermark = StreamingJoinHelper.getStateValueWatermark(
- attributesToFindStateWatermarkFor =
AttributeSet(oneSideInputAttributes),
- attributesWithEventWatermark =
AttributeSet(otherSideInputAttributes),
- condition,
- eventTimeWatermarkForEviction)
- // A row can pass late-input filtering but already be eligible for
eviction in this batch.
- // When the previous join-derived state cutoff is ahead of the
late-input watermark, a new
- // row can fall at or below that cutoff. V4 must scan from the
beginning to find such rows.
- val prevStateValueWatermark = eventTimeWatermarkForLateEvents.flatMap
{ lateWatermark =>
- StreamingJoinHelper.getStateValueWatermark(
- attributesToFindStateWatermarkFor =
AttributeSet(oneSideInputAttributes),
- attributesWithEventWatermark =
AttributeSet(otherSideInputAttributes),
- condition,
- eventTimeWatermarkForLateEvents).filter(_ <= lateWatermark)
+ ordinal, oneSideJoinKeys(ordinal).dataType,
oneSideJoinKeys(ordinal).nullable)
+ // The opposite watermark bounds this key when the opposite key is
that input's event
+ // time, possibly shifted by constant intervals: by the shift for an
exact interval, and
+ // unshifted for whole days, months or years that never move a time
backward. See
+ // StreamingJoinHelper.getStateKeyWatermark for which shifts qualify.
+ def keyWatermark(watermark: Option[Long]): Option[Long] =
+ StreamingJoinHelper.getStateKeyWatermark(
+ otherSideJoinKeys, otherSideInputAttributes, ordinal, watermark,
eventTimeLags)
+ keyWatermark(eventTimeWatermarkForEviction).flatMap { stateWatermark =>
+ watermarkExpression(Some(keyExprWithWatermark),
Some(stateWatermark)).map { e =>
+ // V4 can skip keys at or below the previous watermark only if
late-input filtering
+ // rejects new rows in that range on this same key. A watermark on
the other input's
+ // equality key can drive eviction even when this input has no
watermark, or has one
+ // on a different column. New rows can then pass late-input
filtering with keys
+ // already eligible for eviction. V4 must scan from the beginning
to find them;
+ // otherwise, outer joins can fail to emit null rows for these
unmatched inputs.
+ val prevStateKeyWatermark =
+ if (oneSideInputAttributes.find(_.metadata.contains(delayKey))
+ .exists(oneSideJoinKeys(ordinal).semanticEquals)) {
+ // Late filtering drops new keys at or below the late-input
watermark, and the
+ // previous batch evicted keys up to its cutoff, which is the
cutoff at that
+ // watermark. A shifted cutoff can lie on either side of the
watermark, so the
+ // scan starts after the lower of the two.
+ eventTimeWatermarkForLateEvents.flatMap { lateWatermark =>
+ keyWatermark(Some(lateWatermark)).map(math.min(_,
lateWatermark))
+ }
+ } else {
+ None
+ }
+ JoinStateKeyWatermarkPredicate(e, stateWatermark,
prevStateKeyWatermark)
+ }
}
- val inputAttributeWithWatermark =
oneSideInputAttributes.find(_.metadata.contains(delayKey))
- val expr = watermarkExpression(inputAttributeWithWatermark,
stateValueWatermark)
- expr.map { e =>
- // watermarkExpression only provides the expression when
eventTimeWatermarkForEviction
- // is defined
- JoinStateValueWatermarkPredicate(e, stateValueWatermark.get,
prevStateValueWatermark)
+ } else { // case 2 in the StreamingSymmetricHashJoinExec docs
+ // Future matches are limited by the opposite watermark. This input
needs no watermark;
+ // its event-time column may also have been pruned from the physical
join.
+ getStateValueWatermarkForInput(oneSideInputAttributes,
otherSideInputAttributes, condition,
+ eventTimeWatermarkForEviction, eventTimeLags).flatMap { case
(attribute, watermark) =>
+ // Late filtering only constrains the input's event-time column. A
different indexed
+ // column can admit values below the previous cutoff and must be
scanned from the start.
+ val prevStateValueWatermark = eventTimeWatermarkForLateEvents.filter
{ _ =>
+ oneSideInputAttributes.find(_.metadata.contains(delayKey))
+ .exists(_.semanticEquals(attribute))
+ }.flatMap { lateWatermark =>
+ // Also scan from the start if the derived cutoff exceeds the
late-input watermark.
+
StreamingJoinHelper.getStateValueWatermarkForLags(AttributeSet(Seq(attribute)),
+ otherSideInputAttributes, condition, Some(lateWatermark),
eventTimeLags)
+ .filter(_ <= lateWatermark)
+ }
+ watermarkExpression(Some(attribute), Some(watermark)).map { e =>
+ JoinStateValueWatermarkPredicate(e, watermark,
prevStateValueWatermark)
+ }
}
- } else {
- None
}
}
val leftStateWatermarkPredicate =
- getOneSideStateWatermarkPredicate(leftAttributes, leftKeys,
rightAttributes)
+ getOneSideStateWatermarkPredicate(leftAttributes, leftKeys,
rightAttributes, rightKeys)
val rightStateWatermarkPredicate =
- getOneSideStateWatermarkPredicate(rightAttributes, rightKeys,
leftAttributes)
+ getOneSideStateWatermarkPredicate(rightAttributes, rightKeys,
leftAttributes, leftKeys)
JoinStateWatermarkPredicates(leftStateWatermarkPredicate,
rightStateWatermarkPredicate)
}
- private[join] def findJoinKeyOrdinalForWatermark(
+ /** Keep each cutoff attached to the column constrained by the join
condition. */
+ private def getStateValueWatermarkForInput(
+ inputAttributes: Seq[Attribute],
+ otherInputAttributes: Seq[Attribute],
+ condition: Option[Expression],
+ eventWatermark: Option[Long],
+ eventTimeLags: Option[EventTimeLags]): Option[(Attribute, Long)] = {
+ // TODO(SPARK-61508): an inner or left semi join side that is bounded only
through a column
+ // that is not TIMESTAMP, cast to TIMESTAMP, has no eviction predicate,
so it keeps its rows
+ // for the life of the query until eviction through the cast is
supported. Projecting the
+ // column to TIMESTAMP before the join bounds that state.
+ val eventTime = inputAttributes.find(_.metadata.contains(delayKey))
+ // First try the watermarked column. If it has no inferable bound, try the
other timestamp
+ // and time-window columns in input schema order and use the first with a
bound. This makes
+ // the indexed column deterministic for a fixed input schema and join
condition. The solver
+ // gives a cutoff for no other column, so the admission check, which tries
every column,
+ // accepts the same bounds.
+ val candidates = eventTime.toSeq ++ inputAttributes.filter { attribute =>
+ StreamingJoinHelper.canTakeRangeCutoff(attribute) &&
+ !eventTime.exists(_.semanticEquals(attribute))
+ }
+ candidates.iterator.flatMap { attribute =>
+
StreamingJoinHelper.getStateValueWatermarkForLags(AttributeSet(Seq(attribute)),
+ otherInputAttributes, condition, eventWatermark, eventTimeLags,
+ exactForUnwatermarkedColumns = true).map(attribute -> _)
+ }.take(1).toSeq.headOption
+ }
+
+ /**
+ * Get the equality-key ordinal at which a V4 state manager stores and looks
up a side's rows.
+ * A side evicted by key uses the key that the opposite input's watermark
bounds. Any other side
+ * stores each row at its own event time, unless it is evicted on another
column. When that
+ * event time is an equality key, its ordinal gives the same stored
timestamps and lets a lookup
+ * read one timestamp instead of scanning every timestamp of the key.
+ */
+ def getStateKeyOrdinalForLookup(
+ oneSideAttributes: Seq[Attribute],
+ oneSideKeys: Seq[Expression],
+ otherSideAttributes: Seq[Attribute],
+ otherSideKeys: Seq[Expression],
+ predicate: Option[JoinStateWatermarkPredicate]): Option[Int] = {
+ def storesRowsAtKey(ordinal: Int): Boolean = predicate match {
+ case Some(p: JoinStateValueWatermarkPredicate) =>
+ p.expr.references.forall(_.semanticEquals(oneSideKeys(ordinal)))
+ case _ => true
+ }
+ StreamingJoinHelper.getStateKeyWatermarkOrdinal(otherSideKeys,
otherSideAttributes).orElse(
+ StreamingJoinHelper.getEventTimeKeyOrdinal(oneSideKeys,
oneSideAttributes)
+ .filter(storesRowsAtKey))
+ }
+
+ /**
+ * Conservatively prove that older state can use the current watermark
semantics. Without
+ * watermarks there is no affected state. An input that neither version
evicts keeps the same
+ * rows, but its state watermark in the join's output watermark changed, so
such an input is
+ * accepted only when no stateful operator after the join reads it:
`consumedSides` names the
+ * inputs whose state watermark reaches a later operator through the join's
output watermark,
+ * both when that operator cannot be traced, and none when no stateful
operator follows, with a
+ * single global watermark, or for the right input of a left semi join. A
key-only join, with
+ * no other condition and no equality key that uses an event time, is
evicted by neither
+ * version, and V4 reads its rows by key prefix. Otherwise each side must
have exactly one
+ * event-time column, and either its own event time must be the sole
watermarked equality key
+ * at the same ordinal, or the join must be a time-interval join on the
event times (see
+ * [[isOwnEventTimeIntervalJoin]]). This excludes other range bounds. A key
computed from the
+ * event time by a constant is accepted only when it shifts the event time
forward, the other
+ * input's key at that ordinal is its own event time, no other equality key
uses an event time,
+ * and no stateful operator after the join reads the shifted input's event
time. Older versions
+ * evicted both sides at the unshifted watermark at that ordinal. For a
forward shift, that is
+ * the cutoff this version uses for the shifted side, and at or below the
one it uses for the
+ * other side, which can no longer match rows at or below it, and both
versions store V4 rows
+ * at that ordinal. Only the shifted input's bound in the output watermark
changes. Older
+ * versions evicted a backward shift before its last match. A NULL selected
key does not change
+ * the semantics: such a row can never match.
+ * Old V4 state indexed it at timestamp 0 under its own key, and the first
batch after the
+ * restart scans V4 state from the start, so it evicts the row and a
preserved side emits it
+ * unless an older version already joined it. V1 to V3 test every stored row
each batch and
+ * also evict such a row.
+ */
+ private[sql] def isWatermarkCheckpointCompatible(
+ leftAttributes: Seq[Attribute],
+ rightAttributes: Seq[Attribute],
leftKeys: Seq[Expression],
- rightKeys: Seq[Expression]): Option[Int] = {
- // Join keys of both sides generate rows of the same fields, that is, same
sequence of data
- // types. If one side (say left side) has a column (say timestamp) that
has a watermark on it,
- // then it will never consider joining keys that are < state key watermark
(i.e. event time
- // watermark). On the other side (i.e. right side), even if there is no
watermark defined,
- // there has to be an equivalent column (i.e., timestamp). And any right
side data that has the
- // timestamp < watermark will not match will not match with left side
data, as the left side get
- // filtered with the explicitly defined watermark. So, the watermark in
timestamp column in
- // left side keys effectively causes the timestamp on the right side to
have a watermark.
- // We will use the ordinal of the left timestamp in the left keys to find
the corresponding
- // right timestamp in the right keys.
- leftKeys.zipWithIndex.collectFirst {
- case (ne: NamedExpression, index) if ne.metadata.contains(delayKey) =>
index
- } orElse {
- rightKeys.zipWithIndex.collectFirst {
- case (ne: NamedExpression, index) if ne.metadata.contains(delayKey) =>
index
+ rightKeys: Seq[Expression],
+ condition: Option[Expression],
+ consumedSides: Set[JoinSide]): Boolean = {
+ val leftEventTime = leftAttributes.filter(_.metadata.contains(delayKey))
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 #60279. The restart check now counts each input's
watermarked columns by
distinct expression ID, as `findEventTimeColumn` does. Tests: a unit case
with the event time
listed twice, and a restart of a `leftTime = rightTime` join whose left
input selects its event
time twice. The test checks that the planned join keeps both copies; the
older checkpoint now
resumes and matches a row stored before the restart. Inputs with two
distinct watermarked
columns keep their earlier outcome.
<!-- sp2k-review11 reply 4599498369 -->
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -224,98 +238,390 @@ object StreamingSymmetricHashJoinHelper extends Logging {
WatermarkSupport.findEventTimeColumn(rightAttributes,
allowMultipleEventTimeColumns = useFirstEventTimeColumn)
- val joinKeyOrdinalForWatermark: Option[Int] =
findJoinKeyOrdinalForWatermark(
- leftKeys, rightKeys)
-
def getOneSideStateWatermarkPredicate(
oneSideInputAttributes: Seq[Attribute],
oneSideJoinKeys: Seq[Expression],
- otherSideInputAttributes: Seq[Attribute]):
Option[JoinStateWatermarkPredicate] = {
- val isWatermarkDefinedOnInput =
oneSideInputAttributes.exists(_.metadata.contains(delayKey))
+ otherSideInputAttributes: Seq[Attribute],
+ otherSideJoinKeys: Seq[Expression]):
Option[JoinStateWatermarkPredicate] = {
+ // State is bounded by future input from the opposite side, not by its
own watermark.
+ val joinKeyOrdinalForWatermark =
StreamingJoinHelper.getStateKeyWatermarkOrdinal(
+ otherSideJoinKeys, otherSideInputAttributes, eventTimeLags)
val isWatermarkDefinedOnJoinKey = joinKeyOrdinalForWatermark.isDefined
if (isWatermarkDefinedOnJoinKey) { // case 1 and 3 in the
StreamingSymmetricHashJoinExec docs
+ val ordinal = joinKeyOrdinalForWatermark.get
val keyExprWithWatermark = BoundReference(
- joinKeyOrdinalForWatermark.get,
- oneSideJoinKeys(joinKeyOrdinalForWatermark.get).dataType,
- oneSideJoinKeys(joinKeyOrdinalForWatermark.get).nullable)
- val expr = watermarkExpression(Some(keyExprWithWatermark),
eventTimeWatermarkForEviction)
- expr.map { e =>
- // V4 can skip keys at or below the previous watermark only if
late-input filtering
- // rejects new rows in that range on this same key. A watermark on
the other input's
- // equality key can drive eviction even when this input has no
watermark, or has one
- // on a different column. New rows can then pass late-input
filtering with keys
- // already eligible for eviction. V4 must scan from the beginning to
find them;
- // otherwise, outer joins can fail to emit null rows for these
unmatched inputs.
- val prevStateKeyWatermark =
- if (oneSideInputAttributes.find(_.metadata.contains(delayKey))
-
.exists(oneSideJoinKeys(joinKeyOrdinalForWatermark.get).semanticEquals)) {
- eventTimeWatermarkForLateEvents
- } else {
- None
- }
- // watermarkExpression only provides the expression when
eventTimeWatermarkForEviction
- // is defined.
- JoinStateKeyWatermarkPredicate(
- e,
- eventTimeWatermarkForEviction.get,
- prevStateKeyWatermark)
- }
- } else if (isWatermarkDefinedOnInput) { // case 2 in the
StreamingSymmetricHashJoinExec docs
- val stateValueWatermark = StreamingJoinHelper.getStateValueWatermark(
- attributesToFindStateWatermarkFor =
AttributeSet(oneSideInputAttributes),
- attributesWithEventWatermark =
AttributeSet(otherSideInputAttributes),
- condition,
- eventTimeWatermarkForEviction)
- // A row can pass late-input filtering but already be eligible for
eviction in this batch.
- // When the previous join-derived state cutoff is ahead of the
late-input watermark, a new
- // row can fall at or below that cutoff. V4 must scan from the
beginning to find such rows.
- val prevStateValueWatermark = eventTimeWatermarkForLateEvents.flatMap
{ lateWatermark =>
- StreamingJoinHelper.getStateValueWatermark(
- attributesToFindStateWatermarkFor =
AttributeSet(oneSideInputAttributes),
- attributesWithEventWatermark =
AttributeSet(otherSideInputAttributes),
- condition,
- eventTimeWatermarkForLateEvents).filter(_ <= lateWatermark)
+ ordinal, oneSideJoinKeys(ordinal).dataType,
oneSideJoinKeys(ordinal).nullable)
+ // The opposite watermark bounds this key when the opposite key is
that input's event
+ // time, possibly shifted by constant intervals: by the shift for an
exact interval, and
+ // unshifted for whole days, months or years that never move a time
backward. See
+ // StreamingJoinHelper.getStateKeyWatermark for which shifts qualify.
+ def keyWatermark(watermark: Option[Long]): Option[Long] =
+ StreamingJoinHelper.getStateKeyWatermark(
+ otherSideJoinKeys, otherSideInputAttributes, ordinal, watermark,
eventTimeLags)
+ keyWatermark(eventTimeWatermarkForEviction).flatMap { stateWatermark =>
+ watermarkExpression(Some(keyExprWithWatermark),
Some(stateWatermark)).map { e =>
+ // V4 can skip keys at or below the previous watermark only if
late-input filtering
+ // rejects new rows in that range on this same key. A watermark on
the other input's
+ // equality key can drive eviction even when this input has no
watermark, or has one
+ // on a different column. New rows can then pass late-input
filtering with keys
+ // already eligible for eviction. V4 must scan from the beginning
to find them;
+ // otherwise, outer joins can fail to emit null rows for these
unmatched inputs.
+ val prevStateKeyWatermark =
+ if (oneSideInputAttributes.find(_.metadata.contains(delayKey))
+ .exists(oneSideJoinKeys(ordinal).semanticEquals)) {
+ // Late filtering drops new keys at or below the late-input
watermark, and the
+ // previous batch evicted keys up to its cutoff, which is the
cutoff at that
+ // watermark. A shifted cutoff can lie on either side of the
watermark, so the
+ // scan starts after the lower of the two.
+ eventTimeWatermarkForLateEvents.flatMap { lateWatermark =>
+ keyWatermark(Some(lateWatermark)).map(math.min(_,
lateWatermark))
+ }
+ } else {
+ None
+ }
+ JoinStateKeyWatermarkPredicate(e, stateWatermark,
prevStateKeyWatermark)
+ }
}
- val inputAttributeWithWatermark =
oneSideInputAttributes.find(_.metadata.contains(delayKey))
- val expr = watermarkExpression(inputAttributeWithWatermark,
stateValueWatermark)
- expr.map { e =>
- // watermarkExpression only provides the expression when
eventTimeWatermarkForEviction
- // is defined
- JoinStateValueWatermarkPredicate(e, stateValueWatermark.get,
prevStateValueWatermark)
+ } else { // case 2 in the StreamingSymmetricHashJoinExec docs
+ // Future matches are limited by the opposite watermark. This input
needs no watermark;
+ // its event-time column may also have been pruned from the physical
join.
+ getStateValueWatermarkForInput(oneSideInputAttributes,
otherSideInputAttributes, condition,
+ eventTimeWatermarkForEviction, eventTimeLags).flatMap { case
(attribute, watermark) =>
+ // Late filtering only constrains the input's event-time column. A
different indexed
+ // column can admit values below the previous cutoff and must be
scanned from the start.
+ val prevStateValueWatermark = eventTimeWatermarkForLateEvents.filter
{ _ =>
+ oneSideInputAttributes.find(_.metadata.contains(delayKey))
+ .exists(_.semanticEquals(attribute))
+ }.flatMap { lateWatermark =>
+ // Also scan from the start if the derived cutoff exceeds the
late-input watermark.
+
StreamingJoinHelper.getStateValueWatermarkForLags(AttributeSet(Seq(attribute)),
+ otherSideInputAttributes, condition, Some(lateWatermark),
eventTimeLags)
+ .filter(_ <= lateWatermark)
+ }
+ watermarkExpression(Some(attribute), Some(watermark)).map { e =>
+ JoinStateValueWatermarkPredicate(e, watermark,
prevStateValueWatermark)
+ }
}
- } else {
- None
}
}
val leftStateWatermarkPredicate =
- getOneSideStateWatermarkPredicate(leftAttributes, leftKeys,
rightAttributes)
+ getOneSideStateWatermarkPredicate(leftAttributes, leftKeys,
rightAttributes, rightKeys)
val rightStateWatermarkPredicate =
- getOneSideStateWatermarkPredicate(rightAttributes, rightKeys,
leftAttributes)
+ getOneSideStateWatermarkPredicate(rightAttributes, rightKeys,
leftAttributes, leftKeys)
JoinStateWatermarkPredicates(leftStateWatermarkPredicate,
rightStateWatermarkPredicate)
}
- private[join] def findJoinKeyOrdinalForWatermark(
+ /** Keep each cutoff attached to the column constrained by the join
condition. */
+ private def getStateValueWatermarkForInput(
+ inputAttributes: Seq[Attribute],
+ otherInputAttributes: Seq[Attribute],
+ condition: Option[Expression],
+ eventWatermark: Option[Long],
+ eventTimeLags: Option[EventTimeLags]): Option[(Attribute, Long)] = {
+ // TODO(SPARK-61508): an inner or left semi join side that is bounded only
through a column
+ // that is not TIMESTAMP, cast to TIMESTAMP, has no eviction predicate,
so it keeps its rows
+ // for the life of the query until eviction through the cast is
supported. Projecting the
+ // column to TIMESTAMP before the join bounds that state.
+ val eventTime = inputAttributes.find(_.metadata.contains(delayKey))
+ // First try the watermarked column. If it has no inferable bound, try the
other timestamp
+ // and time-window columns in input schema order and use the first with a
bound. This makes
+ // the indexed column deterministic for a fixed input schema and join
condition. The solver
+ // gives a cutoff for no other column, so the admission check, which tries
every column,
+ // accepts the same bounds.
+ val candidates = eventTime.toSeq ++ inputAttributes.filter { attribute =>
+ StreamingJoinHelper.canTakeRangeCutoff(attribute) &&
+ !eventTime.exists(_.semanticEquals(attribute))
+ }
+ candidates.iterator.flatMap { attribute =>
+
StreamingJoinHelper.getStateValueWatermarkForLags(AttributeSet(Seq(attribute)),
+ otherInputAttributes, condition, eventWatermark, eventTimeLags,
+ exactForUnwatermarkedColumns = true).map(attribute -> _)
+ }.take(1).toSeq.headOption
+ }
+
+ /**
+ * Get the equality-key ordinal at which a V4 state manager stores and looks
up a side's rows.
+ * A side evicted by key uses the key that the opposite input's watermark
bounds. Any other side
+ * stores each row at its own event time, unless it is evicted on another
column. When that
+ * event time is an equality key, its ordinal gives the same stored
timestamps and lets a lookup
+ * read one timestamp instead of scanning every timestamp of the key.
+ */
+ def getStateKeyOrdinalForLookup(
+ oneSideAttributes: Seq[Attribute],
+ oneSideKeys: Seq[Expression],
+ otherSideAttributes: Seq[Attribute],
+ otherSideKeys: Seq[Expression],
+ predicate: Option[JoinStateWatermarkPredicate]): Option[Int] = {
+ def storesRowsAtKey(ordinal: Int): Boolean = predicate match {
+ case Some(p: JoinStateValueWatermarkPredicate) =>
+ p.expr.references.forall(_.semanticEquals(oneSideKeys(ordinal)))
+ case _ => true
+ }
+ StreamingJoinHelper.getStateKeyWatermarkOrdinal(otherSideKeys,
otherSideAttributes).orElse(
+ StreamingJoinHelper.getEventTimeKeyOrdinal(oneSideKeys,
oneSideAttributes)
+ .filter(storesRowsAtKey))
+ }
+
+ /**
+ * Conservatively prove that older state can use the current watermark
semantics. Without
+ * watermarks there is no affected state. An input that neither version
evicts keeps the same
+ * rows, but its state watermark in the join's output watermark changed, so
such an input is
+ * accepted only when no stateful operator after the join reads it:
`consumedSides` names the
+ * inputs whose state watermark reaches a later operator through the join's
output watermark,
+ * both when that operator cannot be traced, and none when no stateful
operator follows, with a
+ * single global watermark, or for the right input of a left semi join. A
key-only join, with
+ * no other condition and no equality key that uses an event time, is
evicted by neither
+ * version, and V4 reads its rows by key prefix. Otherwise each side must
have exactly one
+ * event-time column, and either its own event time must be the sole
watermarked equality key
+ * at the same ordinal, or the join must be a time-interval join on the
event times (see
+ * [[isOwnEventTimeIntervalJoin]]). This excludes other range bounds. A key
computed from the
+ * event time by a constant is accepted only when it shifts the event time
forward, the other
+ * input's key at that ordinal is its own event time, no other equality key
uses an event time,
+ * and no stateful operator after the join reads the shifted input's event
time. Older versions
+ * evicted both sides at the unshifted watermark at that ordinal. For a
forward shift, that is
+ * the cutoff this version uses for the shifted side, and at or below the
one it uses for the
+ * other side, which can no longer match rows at or below it, and both
versions store V4 rows
+ * at that ordinal. Only the shifted input's bound in the output watermark
changes. Older
+ * versions evicted a backward shift before its last match. A NULL selected
key does not change
+ * the semantics: such a row can never match.
+ * Old V4 state indexed it at timestamp 0 under its own key, and the first
batch after the
+ * restart scans V4 state from the start, so it evicts the row and a
preserved side emits it
+ * unless an older version already joined it. V1 to V3 test every stored row
each batch and
+ * also evict such a row.
+ */
+ private[sql] def isWatermarkCheckpointCompatible(
+ leftAttributes: Seq[Attribute],
+ rightAttributes: Seq[Attribute],
leftKeys: Seq[Expression],
- rightKeys: Seq[Expression]): Option[Int] = {
- // Join keys of both sides generate rows of the same fields, that is, same
sequence of data
- // types. If one side (say left side) has a column (say timestamp) that
has a watermark on it,
- // then it will never consider joining keys that are < state key watermark
(i.e. event time
- // watermark). On the other side (i.e. right side), even if there is no
watermark defined,
- // there has to be an equivalent column (i.e., timestamp). And any right
side data that has the
- // timestamp < watermark will not match will not match with left side
data, as the left side get
- // filtered with the explicitly defined watermark. So, the watermark in
timestamp column in
- // left side keys effectively causes the timestamp on the right side to
have a watermark.
- // We will use the ordinal of the left timestamp in the left keys to find
the corresponding
- // right timestamp in the right keys.
- leftKeys.zipWithIndex.collectFirst {
- case (ne: NamedExpression, index) if ne.metadata.contains(delayKey) =>
index
- } orElse {
- rightKeys.zipWithIndex.collectFirst {
- case (ne: NamedExpression, index) if ne.metadata.contains(delayKey) =>
index
+ rightKeys: Seq[Expression],
+ condition: Option[Expression],
+ consumedSides: Set[JoinSide]): Boolean = {
+ val leftEventTime = leftAttributes.filter(_.metadata.contains(delayKey))
+ val rightEventTime = rightAttributes.filter(_.metadata.contains(delayKey))
+ val keyOnly = condition.isEmpty && !(leftKeys ++ rightKeys).exists { key =>
+ key.references.exists(_.metadata.contains(delayKey)) || (key match {
+ case named: NamedExpression => named.metadata.contains(delayKey)
+ case _ => false
+ })
+ }
+
+ def watermarkKeyOrdinals(keys: Seq[Expression]): Seq[Int] = {
+ keys.zipWithIndex.collect {
+ case (key: NamedExpression, index) if key.metadata.contains(delayKey)
=> index
}
}
+
+ val leftOrdinals = watermarkKeyOrdinals(leftKeys)
+ val rightOrdinals = watermarkKeyOrdinals(rightKeys)
+ if (leftEventTime.isEmpty && rightEventTime.isEmpty) {
+ leftOrdinals.isEmpty && rightOrdinals.isEmpty
+ } else if (keyOnly && consumedSides.isEmpty) {
+ true
+ } else if (leftEventTime.size == 1 && rightEventTime.size == 1) {
+ val leftOrdinal = StreamingJoinHelper.getEventTimeKeyOrdinal(leftKeys,
leftAttributes)
+ val rightOrdinal = StreamingJoinHelper.getEventTimeKeyOrdinal(rightKeys,
rightAttributes)
+ val alignedOwnEventTimeKeys = leftOrdinal.isDefined && leftOrdinal ==
rightOrdinal &&
+ leftOrdinals == leftOrdinal.toSeq && rightOrdinals ==
rightOrdinal.toSeq
+ // One input's own event-time key paired with a forward shift of the
other input's.
+ def forwardShiftedKey(
+ ownOrdinal: Option[Int],
+ ownWatermarkOrdinals: Seq[Int],
+ shiftedKeys: Seq[Expression],
+ shiftedAttributes: Seq[Attribute],
+ shiftedWatermarkOrdinals: Seq[Int],
+ shiftedSide: JoinSide): Boolean = ownOrdinal.exists { ordinal =>
+ ownWatermarkOrdinals == Seq(ordinal) &&
shiftedWatermarkOrdinals.isEmpty &&
+ StreamingJoinHelper.isForwardShiftOfEventTime(shiftedKeys(ordinal),
shiftedAttributes) &&
+ leftKeys.indices.filter(_ != ordinal).forall { i =>
+ !(leftKeys(i).references ++ rightKeys(i).references)
+ .exists(_.metadata.contains(delayKey))
+ } && !consumedSides(shiftedSide)
+ }
+ alignedOwnEventTimeKeys ||
+ forwardShiftedKey(leftOrdinal, leftOrdinals, rightKeys,
rightAttributes, rightOrdinals,
+ RightSide) ||
+ forwardShiftedKey(rightOrdinal, rightOrdinals, leftKeys,
leftAttributes, leftOrdinals,
+ LeftSide) ||
+ isOwnEventTimeIntervalJoin(leftAttributes, rightAttributes, leftKeys,
rightKeys,
+ condition, leftEventTime.head, rightEventTime.head, consumedSides)
+ } else {
+ false
+ }
+ }
+
+ /**
+ * Whether every ordering conjunct compares the two inputs' TIMESTAMP event
times, each only cast
+ * or offset by constants (see [[StreamingJoinHelper.isConstantOffsetOf]]),
or gives no bound to
+ * either input in either version, and each event time either gets a range
bound or gets none and
+ * is not in `consumedSides`. Each half of a BETWEEN counts as one conjunct,
as the solver reads
+ * it. Older versions and this one solve such conjuncts the same way for
columns with their own
+ * watermark, and older versions solved every column of an input but then
found bounds only in the
+ * same conjuncts, so they derived the same value predicates, scan starts
and V4 index columns,
+ * and neither evicts an input that gets no bound. Old V4 stored a null
event time at timestamp 0
+ * under the row's own key; both versions scan that entry the same way. No
equality key may use an
+ * event time: older versions evicted both sides of such a key at the
unshifted watermark, which
+ * [[isWatermarkCheckpointCompatible]] accepts only for a forward shift
whose shifted input no
+ * later stateful operator reads. Time windows are excluded: this version
still derives the older
+ * ordering bound for them, but SPARK-61348 later removes it for windows
shorter than the other
+ * input's.
+ */
+ private def isOwnEventTimeIntervalJoin(
+ leftAttributes: Seq[Attribute],
+ rightAttributes: Seq[Attribute],
+ leftKeys: Seq[Expression],
+ rightKeys: Seq[Expression],
+ condition: Option[Expression],
+ leftEventTime: Attribute,
+ rightEventTime: Attribute,
+ consumedSides: Set[JoinSide]): Boolean = {
+ def conjuncts(e: Expression): Seq[Expression] = e match {
+ case And(left, right) => conjuncts(left) ++ conjuncts(right)
+ case other => Seq(other)
+ }
+ def eventTimeOf(e: Expression): Option[Attribute] =
+ Seq(leftEventTime,
rightEventTime).find(StreamingJoinHelper.isConstantOffsetOf(e, _))
+ def comparesInputs(a: Expression, b: Expression): Boolean =
+ (eventTimeOf(a), eventTimeOf(b)) match {
+ case (Some(x), Some(y)) => !x.semanticEquals(y)
+ case _ => false
+ }
+ // Whether the comparison references both inputs and neither version
derives a bound for
+ // either input from it, as for one between columns of both inputs that
have no watermark,
+ // or one with a month interval, which the solver cannot read. Older
versions solved every
+ // column of an input against the other input; this version solves one
candidate column at a
+ // time. A comparison within one input stays excluded: older versions read
some of them, such
+ // as one with a numeric constant, as a bound. The older solve skips the
admission rules that
+ // this version added, such as the TIMESTAMP column rule, so it passes
baseAdmissionRules.
+ def givesNoBound(comparison: Expression): Boolean = {
+ val inputs = Seq(leftAttributes -> rightAttributes, rightAttributes ->
leftAttributes)
+ inputs.forall { case (input, _) =>
+ comparison.references.exists(a => input.exists(_.semanticEquals(a)))
+ } && inputs.forall { case (input, other) =>
+ StreamingJoinHelper.getStateValueWatermark(AttributeSet(input),
AttributeSet(other),
+ Some(comparison), Some(1000000L), baseAdmissionRules = true).isEmpty
&&
+ getStateValueWatermarkForInput(input, other, Some(comparison),
Some(1000000L), None)
+ .isEmpty
+ }
+ }
+ // The solver reads bounds only from these conjunct shapes; other
conjuncts give no bound in
+ // either version.
+ val conditionIsInterval = condition.toSeq.flatMap(conjuncts).forall {
+ case c @ (_: LessThan | _: LessThanOrEqual | _: GreaterThan | _:
GreaterThanOrEqual) =>
+ val comparison = c.asInstanceOf[BinaryComparison]
+ comparesInputs(comparison.left, comparison.right) ||
givesNoBound(comparison)
+ case Between(input, lower, upper, _) =>
+ (comparesInputs(input, lower) ||
givesNoBound(GreaterThanOrEqual(input, lower))) &&
+ (comparesInputs(input, upper) || givesNoBound(LessThanOrEqual(input,
upper)))
+ case _ => true
+ }
+ val keysUseEventTime = (leftKeys ++ rightKeys).exists(
+ _.references.exists(_.metadata.contains(delayKey)))
+ def boundsEventTime(
+ predicate: Option[JoinStateWatermarkPredicate], eventTime: Attribute):
Boolean = {
+ predicate.exists {
+ case JoinStateValueWatermarkPredicate(e, _, _) =>
e.references.contains(eventTime)
+ case _ => false
+ }
+ }
+ val timestampEventTimes =
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. This is the same question as the restart decision challenge on
#60283, so we answer it
there instead of changing this PR on its own. The exclusion sits in #60279,
where it is exact: at
that point the solver still derives the older bound for every window
ordering. Which window
orderings keep the older cutoff is decided by #60283's window-length rule,
so a narrower check
belongs in #60283 and needs that rule's two solves. Until then, such a
checkpoint fails at
restart with the explicit error, before any state is opened, and no saved
row is misread. The
stale comment that calls SPARK-61348 a later change is tracked by the P3
finding on #60283.
<!-- sp2k-review11 reply 4599498359 -->
##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinRangeEvictionSuite.scala:
##########
@@ -0,0 +1,190 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.streaming
+
+import org.apache.logging.log4j.Level
+
+import org.apache.spark.sql.Row
+import org.apache.spark.sql.catalyst.analysis.StreamingJoinHelper
+import
org.apache.spark.sql.execution.streaming.operators.stateful.join.StreamingSymmetricHashJoinExec
+import org.apache.spark.sql.execution.streaming.runtime.MemoryStream
+import org.apache.spark.sql.execution.streaming.state.RocksDBStateStoreProvider
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.tags.SlowSQLTest
+
+@SlowSQLTest
+class StreamingJoinRangeEvictionSuite extends StreamTest {
+ import testImplicits._
+
+ private def withJoinConf(version: Int)(f: => Unit): Unit = {
+ withSQLConf(
+ SQLConf.STREAMING_JOIN_STATE_FORMAT_VERSION.key -> version.toString,
+ SQLConf.STATE_STORE_PROVIDER_CLASS.key ->
classOf[RocksDBStateStoreProvider].getName,
+ SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> "false")(f)
+ }
+
+ // V3 shares V2's eviction code. BETWEEN is replaced by the conjunction
before planning, so it
+ // only adds coverage for the outer-join watermark check during analysis.
+ for {
+ version <- Seq(2, 4)
+ joinType <- Seq("inner", "left_outer", "right_outer")
+ shape <- Seq("between", "conjunction", "upper", "interval", "downstream")
+ if shape != "between" || joinType != "inner"
+ } {
+ test(s"range eviction uses bounded timestamp, V$version $joinType $shape")
{
+ withJoinConf(version) {
+ val leftInput = MemoryStream[(Int, Long, Long)]
+ val rightInput = MemoryStream[(Int, Long)]
+ val left = leftInput.toDF().toDF("leftKey", "start", "end")
+ .select($"leftKey", timestamp_seconds($"start").as("leftTime"),
+ timestamp_seconds($"end").as("expiry"))
+ .withWatermark("leftTime", "60 seconds")
+ val right = rightInput.toDF().toDF("rightKey", "time")
+ .select($"rightKey", timestamp_seconds($"time").as("rightTime"))
+ .withWatermark("rightTime", "60 seconds")
+ val range = shape match {
+ case "between" | "downstream" => "rightTime BETWEEN leftTime AND
expiry"
+ case "conjunction" => "rightTime >= leftTime AND rightTime <= expiry"
+ case "interval" => "rightTime BETWEEN leftTime AND leftTime +
INTERVAL 10 MINUTES"
+ case _ => "rightTime <= expiry"
+ }
+ val condition = expr(s"leftKey = rightKey AND $range")
+ val joined = if (joinType == "right_outer") {
+ right.join(left, condition, joinType)
+ } else {
+ left.join(right, condition, joinType)
+ }
+ val output = joined.select($"leftKey", $"leftTime",
+ $"rightTime".cast("long").as("matchTime"))
+ val deduplicated = if (shape == "downstream") {
+ output.dropDuplicates("leftKey", "matchTime")
+ } else {
+ output
+ }
+ val result = deduplicated.select($"leftKey", $"matchTime",
$"leftTime".cast("long"))
+ val matched = Row(1, 460L, 100L)
+ val unmatched = Row(2, null, 100L)
+ testStream(result)(
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (1, 100L, 700L), (2, 100L, 700L)),
AddData(rightInput, (9, 100L)))),
+ CheckNewAnswer(),
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (8, 400L, 1000L)), AddData(rightInput, (9,
400L)))),
+ CheckNewAnswer(),
+ AddData(rightInput, (9, 400L)),
+ // The watermark has passed the start time, but the interval has not
expired.
+ CheckNewAnswer(),
+ Execute { query =>
+ val join = query.lastExecution.executedPlan.collectFirst {
+ case j: StreamingSymmetricHashJoinExec => j
+ }.get
+ assert(join.eventTimeWatermarkForEviction.contains(340000L))
+ if (shape != "interval") {
+ assert(join.produceOutputWatermark(340000L).contains(0L))
+ }
+ },
+ AddData(rightInput, (1, 460L)),
+ CheckNewAnswer(matched),
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (8, 1000L, 1600L)), AddData(rightInput, (9,
1000L)))),
+ CheckNewAnswer(),
+ AddData(rightInput, (9, 1100L)),
+ CheckNewAnswer((if (joinType != "inner") Seq(unmatched) else
Seq.empty): _*)
+ )
+ }
+ }
+ }
+
+ for {
+ version <- Seq(2, 3, 4)
+ joinType <- Seq("left_outer", "right_outer")
+ } {
+ test(s"range eviction includes newly admitted expired values, V$version
$joinType") {
+ withJoinConf(version) {
+ val leftInput = MemoryStream[(Int, Long, Long)]
+ val rightInput = MemoryStream[(Int, Long)]
+ val left = leftInput.toDF().toDF("leftKey", "start", "end")
+ .select($"leftKey", timestamp_seconds($"start").as("leftTime"),
+ timestamp_seconds($"end").as("expiry"))
+ .withWatermark("leftTime", "60 seconds")
+ val right = rightInput.toDF().toDF("rightKey", "time")
+ .select($"rightKey", timestamp_seconds($"time").as("rightTime"))
+ .withWatermark("rightTime", "60 seconds")
+ val condition = expr("leftKey = rightKey AND rightTime <= expiry")
+ val joined = if (joinType == "right_outer") {
+ right.join(left, condition, joinType)
+ } else {
+ left.join(right, condition, joinType)
+ }
+ val result = joined.select($"leftKey", $"rightKey",
$"leftTime".cast("long"))
+ testStream(result)(
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (8, 100L, 700L)), AddData(rightInput, (9,
100L)))),
+ CheckNewAnswer(),
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (8, 400L, 1000L)), AddData(rightInput, (9,
400L)))),
+ CheckNewAnswer(),
+ AddData(rightInput, (9, 400L)), CheckNewAnswer(),
+ // The start passes late filtering, but expiry is below the previous
eviction cutoff.
+ AddData(leftInput, (3, 460L, 200L)), CheckNewAnswer(Row(3, null,
460L)),
+ AddData(rightInput, (9, 500L)), CheckNewAnswer())
+ }
+ }
+ }
+
+ // In state format 4, the extra conjunct gives the left side a
value-eviction predicate on its
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
[90dfad8d848](https://github.com/apache/spark/pull/60279/commits/90dfad8d84808a6c4e00b41b0c6ffa24c713db31).
The comment now says that the extra conjunct gives the right side a
value-eviction predicate on `rightTime`, so that the range scan of the right
joiner solves the bound that shifts by a column of the other input. The same
fix answers the comment on #60279.
<!-- sp2k-review11 reply 4599498416 -->
##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinSuite.scala:
##########
@@ -2425,6 +2802,275 @@ 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),
+ // The right key cutoff is the watermark plus 10 seconds less 1 ms, so
the right row
+ // (1, 112) is at or below it although the watermark advances by only 5
seconds. The left
+ // keys of (7, 100) and (7, 105) stay above the 105-second left cutoff.
+ ("a key shifted by more than the watermark step",
+ "leftTime + INTERVAL 10 SECONDS = rightTime", 102, 112, 105, 2L, 2L),
+ // 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. The right row (1,
110, 160) matches the
+ // left row (1, 120) of the same batch and is evicted at its end, whether
the cutoff is applied
+ // to rightExpiry or to rightTime. Storing only the right rows above the
cutoff at the
+ // late-events watermark would drop this match when the cutoff is applied to
rightTime.
+ 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))
+ }
+ }
+
+ test("left semi join keeps a same-batch match bounded by another right
column when both " +
+ "watermarks are equal") {
+ withSQLConf(SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> "false",
+ SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.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(),
+ // Both watermarks are 100 seconds, and the right cutoff is 130
seconds less 1 ms. The
+ // right row passes late filtering but is at or below the cutoff on
rightTime, and 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
[90dfad8d848](https://github.com/apache/spark/pull/60279/commits/90dfad8d84808a6c4e00b41b0c6ffa24c713db31).
You are right that the legacy-mode test with a second right column cannot
reach the same-batch decision: with equal watermarks, a right row that its
batch evicts cannot match a left row that passes late filtering unless the
cutoff is not exact. The test is renamed and its comment says that the right
cutoff applies to `rightExpiry`, so the right row stays in state and matches
the later left row, and that the default-mode test and the tests of the exact
cutoffs cover the same-batch decision. A new test with the truncating-cast
condition of the default-mode test, in legacy mode and skipped in state format
4, makes the join store the right row that its batch evicts when the cutoff is
not exact: with the left semi clause removed from the store decision, the left
row at 100.6 seconds does not match. It is the same test as in #60279.
<!-- sp2k-review11 reply 4599498481 -->
--
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]