HeartSaVioR commented on code in PR #60286:
URL: https://github.com/apache/spark/pull/60286#discussion_r4603163132
##########
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
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 scaladoc of the interval-join rule now says what the first batch after
restoring an older generation does: it scans V4 state from the start, evicts a
row that an older version stored at timestamp 0 with a NULL event time, and a
preserved side emits it padded with nulls, which older versions never did, and
that this scan must stay. It is the same comment as in #60282.
<!-- sp2k-review11 reply 4599498390 -->
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala:
##########
@@ -602,8 +629,25 @@ class IncrementalExecution(
// The prevOffsetSeqMetadata.isDefined check guards against the first
batch, where
// watermark propagation yields Some(0) for late events even though no
state has been
// evicted yet, which would incorrectly skip entries at timestamp 0.
+ //
+ // On the first batch of a run, the late-events watermark comes from
re-simulating the
+ // previous batch with this run's plan and semantics. An upstream
stream-stream join's
+ // output watermark can then be above the one the previous batch
evicted with, so this
+ // join scans from the start in that batch in two cases:
+ // - The checkpoint is pinned to older join watermark semantics. Older
versions included
+ // every bounded input in a join's output watermark; this version
leaves out one that
+ // the next stateful operator does not read. The pinned marker never
advances, so this
+ // recurs on the first batch of every run of such a checkpoint.
Limiting it to the first
+ // run after the upgrade would mean guessing which version ran the
previous batch, and
+ // a wrong guess skips rows that were never evicted.
+ // - Another stream-stream join is below this one. Its output
watermark depends on the
+ // plan above it (see withJoinOutputWatermarkSides), which can
change between runs,
+ // for example when a stream-static join between the two joins is
removed.
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 example in the comment above `hasJoinBelow` is now a downstream operator
that reads another input's event time after a restart, the case that 'V4
chained joins scan from the start after the plan between them changes' tests.
Removing a stream-static join no longer moves the watermark, so it is not the
example.
<!-- sp2k-review11 reply 4599498403 -->
##########
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.
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.
Added in
[90dfad8d848](https://github.com/apache/spark/pull/60279/commits/90dfad8d84808a6c4e00b41b0c6ffa24c713db31).
Both comments, at the key branch and at the value branch, now carry
`TODO(SPARK-61449)` that names the narrower start: after the lower of the
previous cutoff and the smallest timestamp indexed since the previous eviction.
<!-- sp2k-review11 reply 4599498442 -->
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -717,21 +738,111 @@ case class StreamingSymmetricHashJoinExec(
Predicate.create(Literal(false), Seq.empty).eval _ // false = do not
remove if no predicate
}
+ // A NULL in the column that the state watermark predicate tests makes the
predicate unknown,
+ // so eviction never removes the row. The row cannot match either: that
column is an equality
+ // key, or a comparison in the join condition bounds it. Handle the row
like one that fails
+ // the pre-join filter.
+ // The check takes the generated key and the input row, so the key is
computed only once.
+ private[this] val isEvictionColumnNull: (UnsafeRow, UnsafeRow) => Boolean =
+ stateWatermarkPredicate match {
+ case Some(JoinStateKeyWatermarkPredicate(expr, _, _)) =>
+ // Only a NULL key fails equality. A struct key with a NULL field
can still be equal.
+ val ordinal = expr.collectFirst { case b: BoundReference =>
b.ordinal }.get
+ (key, _) => key.isNullAt(ordinal)
+ case Some(JoinStateValueWatermarkPredicate(LessThanOrEqual(column, _),
_, _)) =>
+ // Test the compared column, not the predicate: the predicate holds
the cutoff, which
+ // changes every batch and would generate and compile new code each
time.
+ val isNull = Predicate.create(IsNull(column), inputAttributes)
+ (_, row) => isNull.eval(row)
+ case _ =>
+ (_, _) => false
+ }
+
+ // V1 to V3 eviction tests every stored row each batch, so it also removes
a row whose
+ // eviction column is NULL. This version never stores such a row, but an
older version did,
+ // and the row can never match. isEvictionColumnNull reads only the key
for a key predicate
+ // and only the row for a value predicate.
+ private[this] val stateKeyEvictionFunc: UnsafeRow => Boolean =
+ key => stateKeyWatermarkPredicateFunc(key) || isEvictionColumnNull(key,
null)
+ private[this] val stateValueEvictionFunc: UnsafeRow => Boolean =
+ row => stateValueWatermarkPredicateFunc(row) ||
isEvictionColumnNull(null, row)
+
private[this] var updatedStateRowsCount = 0
private[this] var numRemovedFromOtherSideDuringJoinCount = 0
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] lazy val noLeftRowCanMatch: (UnsafeRow, UnsafeRow) =>
Boolean =
+ if (joinType == LeftSemi && joinSide == RightSide) {
+ val (keyCutoff, valueCutoff) =
getLeftSemiExactRightCutoffs(left.output, right.output,
+ leftKeys, rightKeys, condition.full, eventTimeWatermarkForLateEvents,
+ useFirstEventTimeColumn = !allowMultipleStatefulOperators)
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.
Added in
[90dfad8d848](https://github.com/apache/spark/pull/60279/commits/90dfad8d84808a6c4e00b41b0c6ffa24c713db31).
A legacy-mode left semi join whose inputs each keep a copy of their event
time, a second watermarked column, and whose right row is evicted in its batch
runs without failing, and the right state does not keep that row. If this call
passed `false` for the first-column flag, the join would fail with
`MULTIPLE_EVENT_TIME_COLUMNS` on that right row, which I checked by making that
change. An unused copy is pruned from the join input, so the test puts both
copies in a join key, cast to a string so that the key does not evict state by
itself. State format 4 rejects two event time columns in its state manager, so
the test runs for the formats 1 to 3.
<!-- sp2k-review11 reply 4599498490 -->
--
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]