spark-test commented on code in PR #60280:
URL: https://github.com/apache/spark/pull/60280#discussion_r4523185814
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -224,98 +228,148 @@ 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] = {
+ 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)
val isWatermarkDefinedOnInput =
oneSideInputAttributes.exists(_.metadata.contains(delayKey))
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)
+ ordinal, oneSideJoinKeys(ordinal).dataType,
oneSideJoinKeys(ordinal).nullable)
+ // The opposite watermark bounds this key, shifted by any constant in
the opposite key.
+ def keyWatermark(watermark: Option[Long]): Option[Long] =
+ StreamingJoinHelper.getStateKeyWatermark(
+ otherSideJoinKeys, otherSideInputAttributes, ordinal, watermark)
+ 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)) {
+ // A cutoff shifted above the late-input watermark also needs
a full scan.
+ eventTimeWatermarkForLateEvents.flatMap { lateWatermark =>
+ keyWatermark(Some(lateWatermark)).filter(_ <= lateWatermark)
+ }
+ } else {
+ None
+ }
+ JoinStateKeyWatermarkPredicate(e, stateWatermark,
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)
- }
- 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)
+ getStateValueWatermarkForInput(oneSideInputAttributes,
otherSideInputAttributes,
+ condition, eventTimeWatermarkForEviction).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.getStateValueWatermark(AttributeSet(Seq(attribute)),
+ AttributeSet(otherSideInputAttributes), condition,
Some(lateWatermark))
+ .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]): Option[(Attribute, Long)] = {
+ val eventTime = inputAttributes.find(_.metadata.contains(delayKey))
+ // First try the watermarked column. If it has no inferable bound, try the
other timestamp
+ // 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.
+ val candidates = eventTime.toSeq ++ inputAttributes.filter { attribute =>
+ attribute.dataType == TimestampType &&
!eventTime.exists(_.semanticEquals(attribute))
+ }
+ candidates.iterator.flatMap { attribute =>
+ StreamingJoinHelper.getStateValueWatermark(AttributeSet(Seq(attribute)),
+ AttributeSet(otherInputAttributes), condition,
eventWatermark).map(attribute -> _)
+ }.take(1).toSeq.headOption
+ }
+
+ /**
+ * Conservatively prove that older state can use the current watermark
semantics. Without
+ * watermarks there is no affected state. Otherwise each side must have
exactly one event-time
+ * column, and its own event time must be the sole watermarked equality key
at the same ordinal.
+ * This excludes range bounds and retained event times with no eviction
bound. It also excludes
+ * a key computed from the event time by a constant, which older versions
evicted at the
+ * unshifted watermark. V4 additionally requires the selected equality key
timestamp to be
+ * provably non-null, because old V4 indexed null selected key timestamps
and timestamp
+ * eviction does not recheck the key predicate. A non-null window() key
qualifies: its end is
+ * computed from a non-null event time.
+ */
+ 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],
+ stateFormatVersion: Int): Boolean = {
+ val leftEventTime = leftAttributes.filter(_.metadata.contains(delayKey))
+ val rightEventTime = rightAttributes.filter(_.metadata.contains(delayKey))
+
+ def watermarkKeyOrdinals(keys: Seq[Expression]): Seq[Int] = {
+ keys.zipWithIndex.collect {
+ case (key: NamedExpression, index) if key.metadata.contains(delayKey)
=> index
}
}
+
+ def selectedKeyTimestampCanBeNull(key: Attribute): Boolean = key.dataType
match {
+ // window() derives the end from a non-null event time, though
TimeWindow declares the
+ // field nullable.
+ case _: StructType if key.metadata.contains(TimeWindow.marker) =>
+ key.nullable
+ case struct: StructType =>
+ key.nullable || struct.fields.lift(1).forall(_.nullable)
+ case _ =>
+ key.nullable
+ }
+
+ val leftOrdinals = watermarkKeyOrdinals(leftKeys)
+ val rightOrdinals = watermarkKeyOrdinals(rightKeys)
+ if (leftEventTime.isEmpty && rightEventTime.isEmpty) {
+ leftOrdinals.isEmpty && rightOrdinals.isEmpty
+ } 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
+ val selectedKeysAreNonNull = stateFormatVersion < 4 ||
alignedOwnEventTimeKeys &&
Review Comment:
**Non-blocking (P2):** This rejects every pre-marker V4 checkpoint of an
aligned own-event-time equality join whose event-time attribute is nullable in
the plan, judged from plan nullability without reading the state. For example,
a Spark 4.3 left outer join on `lk = rk AND lt = rt` over a nullable `lt` that
never held a null stops at restart with
`STREAMING_JOIN_CHECKPOINT_INCOMPATIBLE`, and its owner has to rebuild from
replayed input, which cannot recover past results once the source history is
gone; the base branch restarts it. The case this guards against, an old
timestamp-0 index entry for a null key, holds a row that `=` lets no input
match, so evicting it when a scan reaches it, as the base branch does, emits
its correct null-padded row on a preserved outer side. Dropping the V4
nullability clause and keeping the aligned-key rule would let these checkpoints
restart.
**Verification:**
- **Compatibility:** A V4 left outer join on lk = rk AND lt = rt with a
nullable lt, written without the watermark-semantics marker and without null lt
values, restarts and produces the same matches and null-padded rows as an
uninterrupted run.
- **Regression:** Restarting old V4 state of a left outer join on lk = rk
AND lt = rt that holds a left row with a null lt indexed at timestamp 0 gives
the same output for that row as the base branch, including with
spark.sql.streaming.statefulOperator.allowMultiple=false, where every eviction
scan starts at the beginning of the index.
- **Compatibility:** Old checkpoints with range bounds or shifted keys are
still rejected with STREAMING_JOIN_CHECKPOINT_INCOMPATIBLE.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -706,32 +707,44 @@ object UnsupportedOperationChecker extends Logging {
}
private def checkForStreamStreamJoinWatermark(join: Join): Unit = {
- val watermarkInJoinKeys = StreamingJoinHelper.isWatermarkInJoinKeys(join)
-
- // Check if the nullable side has a watermark, and there's a range
condition which
- // implies a state value watermark on the first side.
- val hasValidWatermarkRange = join.joinType match {
- case LeftOuter | LeftSemi => StreamingJoinHelper.getStateValueWatermark(
- join.left.outputSet, join.right.outputSet, join.condition,
Some(1000000)).isDefined
- case RightOuter => StreamingJoinHelper.getStateValueWatermark(
- join.right.outputSet, join.left.outputSet, join.condition,
Some(1000000)).isDefined
- case FullOuter =>
- Seq((join.left.outputSet, join.right.outputSet),
- (join.right.outputSet, join.left.outputSet)).exists {
- case (attributesToFindStateWatermarkFor,
attributesWithEventWatermark) =>
-
StreamingJoinHelper.getStateValueWatermark(attributesToFindStateWatermarkFor,
- attributesWithEventWatermark, join.condition,
Some(1000000)).isDefined
- }
+ val keys = ExtractEquiJoinKeys.unapply(join)
+ val leftKeys = keys.map(_._2).getOrElse(Nil)
+ val rightKeys = keys.map(_._3).getOrElse(Nil)
+
+ def canEvictState(
+ stateInput: LogicalPlan,
+ otherInput: LogicalPlan,
+ otherKeys: Seq[Expression]): Boolean = {
+ val eventTime =
otherInput.output.find(_.metadata.contains(EventTimeWatermark.delayKey))
+ StreamingJoinHelper.getStateKeyWatermarkOrdinal(otherKeys,
otherInput.output).isDefined ||
+ StreamingJoinHelper.getStateValueWatermark(stateInput.outputSet,
Review Comment:
**Nit (P3):** This check admits two shapes that execution does not finalize
yet. One is a range bound on a stored side without its own watermark: a left
outer join on `lt BETWEEN rt - INTERVAL 5 SECONDS AND rt + INTERVAL 5 SECONDS`
with a watermark only on `rt` passes here, but its left state gets no eviction
predicate, because value eviction still requires the stored side's own
watermark. The other is a bound that exists only on a non-TIMESTAMP stored
column, such as `CAST(expiry AS TIMESTAMP)` over a BIGINT, which
`getStateValueWatermarkForInput` never tries. The description defers these to
SPARK-61347 and SPARK-61348, but nothing here or at the stored-side watermark
branch of `getStateWatermarkPredicates` says so, and the new error text says
the requirement lets unmatched state be finalized. A TODO at both places naming
the tickets would show that the fix is partial; please also say whether DATE
and TIMESTAMP_NTZ bounds fall under SPARK-61348.
**Verification:**
- **Inspection:** The range-bound check in the stream-stream join admission
and the stored-side watermark branch of the eviction predicate derivation each
name the follow-up ticket for the shapes they do not yet finalize.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -224,98 +228,148 @@ 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] = {
+ 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(
Review Comment:
**Blocking (P1):** The left state of a left outer join on `la = ra AND lb =
rb`, with watermarks on `la` and `rb`, is now evicted on `lb` instead of `la`.
Reading the code, a left row (la = 50 s, lb = null) can never match: the
optimizer filters the right input to non-null `ra` and `rb`, and `=` never
matches a null. Yet `lb <= watermark` is false for it in V2 and V3, and V4 now
stores it outside the eviction index, so the row stays in state forever and
`(50 s, null, null, null)` is never emitted. The base branch evicted it on `la`
and emitted it once the watermark passed 50 s. V4 also stops emitting a null
`lt` in a left outer `lt = rt` join with only `rt` watermarked, which the base
branch indexed at timestamp 0 and emitted. Full outer joins lose the same rows:
the StreamingJoinV4Suite test `full outer join keeps null ... window keys
unbounded` asserts that the null-window row stays in state, where the base
branch emitted it null-padded, or failed reading the null window when th
e windows were on the right input. Keeping such a row only lets a later null
key on the other side pair with it through the byte-equal state lookup, a pair
that `=` never forms.
**Recommended change:** In storeAndJoinWithOtherSide, treat a row on a
preserved side of an outer join (the left side of a left outer join, the right
side of a right outer join, either side of a full outer join) whose generated
equality key has a null field like a row that fails the pre-join filter: emit
it null-padded at once through the existing filtered-row path, and neither
probe the other side nor store it. The non-preserved side of left and right
outer joins keeps its behavior. Add join tests for left, right and full outer
joins whose newly selected eviction key, or V4 selected key, is null, and
change the V4 full outer null-window test to expect those rows null-padded in
the batch they arrive instead of kept in state.
**Why this works:** Under = equality a null key matches no row, and
null-safe equality never yields a null key field because ExtractEquiJoinKeys
turns it into coalesce and isnull pairs, so a preserved row whose generated key
has a null field can only be output null-padded; emitting it on arrival makes
that output independent of which key the eviction ordinal selects and of how
V2, V3 or V4 store a null timestamp.
**Scope:** Emit, without storing, preserved-side rows of outer joins whose
equality key is null, and test them for every state format and outer join type.
**Compatibility:** Rows with non-null equality keys, the non-preserved side
of left and right outer joins, and the opposite-side eviction ordinal behave as
they do now.
**Risks:** Preserved-side rows with a null equality key are now emitted when
they arrive rather than when evicted, including rows whose null key sits at an
unchanged ordinal, which V2 and V3 never emitted on the base branch; this
changes output for those inputs and has no setting. Full outer joins, and left
or right outer joins with constraint propagation disabled, no longer pair two
rows whose keys are null, as the byte-equal state lookup does on the base
branch and in this PR although = never matches them in batch joins; each such
row is now emitted null-padded instead of joined.
**Constraints:** Apply the rule only to preserved sides of outer joins and
only when a generated key field is null; rows with non-null keys keep their
current probing, storage and eviction.
**Exclusions:**
- Rows already stored with a null eviction key in checkpoints of earlier
versions are left as they are, as on the base branch after a restart.
**Success:** A left, right or full outer join emits a preserved-side row
whose equality key is null, null-padded, in the batch it arrives, and does not
keep it in state. Matching and eviction of rows with non-null keys are
unchanged.
**Verification:**
- **Regression:** A left outer join on la = ra AND lb = rb with watermarks
on la and rb emits a left row with a non-null la and a null lb null-padded and
keeps no state for it, in state formats V2, V3 and V4.
- **Regression:** A V4 left outer join on lt = rt with a watermark only on
rt emits a left row with a null lt null-padded.
- **Behavior:** The mirrored right outer join emits a right row with a null
key null-padded.
- **Regression:** A V4 full outer join on la = ra AND lb = rb whose lb or rb
is a null window emits that row null-padded in the batch it arrives and keeps
no state for it, with the null windows on either input.
- **Behavior:** A full outer join that receives a row with a null key on
each side emits both rows null-padded rather than one joined row.
- **Compatibility:** Rows with non-null keys match and are evicted as before
in left, right and full outer joins, in state formats V2, V3 and V4.
##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinV4Suite.scala:
##########
@@ -321,7 +321,7 @@ class StreamingInnerJoinV4Suite
val df2 = input2.toDF().toDF("key", "time")
.select($"key", timestamp_seconds($"time") as "ts", ($"key" * 3) as
"rightValue")
// Only left side has watermark; ts is part of the join key, so
- // joinKeyOrdinalForWatermark is defined -> hasEventTime = true for both
sides.
+ // joinKeyOrdinalForWatermark is defined -> hasTimestampForEviction =
true for both sides.
Review Comment:
**Nit (P3):** With the per-side ordinal this no longer holds for the left
side: the left joiner gets `getStateKeyWatermarkOrdinal(rightKeys,
right.output)` = `None` because the right input has no watermark, its secondary
index is filled through the event-time fallback, and the left state has no
eviction predicate. Only the right state is evicted through `ts` by the left
watermark, so the note below about the no-data batch evicting rows with `ts <=
10`, and the later comment that the watermark on the join key applies to both
sides, now hold only for the right side. The assertions still pass, for a
different reason.
**Verification:**
- **Inspection:** The comments in the secondary-index test match how the
join evicts and indexes each side when only the left join key is watermarked.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -224,98 +228,148 @@ 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] = {
+ 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)
val isWatermarkDefinedOnInput =
oneSideInputAttributes.exists(_.metadata.contains(delayKey))
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)
+ ordinal, oneSideJoinKeys(ordinal).dataType,
oneSideJoinKeys(ordinal).nullable)
+ // The opposite watermark bounds this key, shifted by any constant in
the opposite key.
+ def keyWatermark(watermark: Option[Long]): Option[Long] =
+ StreamingJoinHelper.getStateKeyWatermark(
+ otherSideJoinKeys, otherSideInputAttributes, ordinal, watermark)
+ 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)) {
+ // A cutoff shifted above the late-input watermark also needs
a full scan.
+ eventTimeWatermarkForLateEvents.flatMap { lateWatermark =>
+ keyWatermark(Some(lateWatermark)).filter(_ <= lateWatermark)
Review Comment:
**Non-blocking (P2):** For `lt = rt + INTERVAL 10 SECONDS`,
`keyWatermark(Some(lateWatermark))` is the late watermark plus 10 s less 1 ms,
so this filter always yields `None`, and V4 eviction walks the left index from
its first entry, including uncompacted tombstones below the late watermark, in
every batch. The base branch started that scan after the late watermark. Rows
kept by the previous batch sit above `keyWatermark(late)`, and late filtering
admits only keys above `late`, so starting after `min(keyWatermark(late),
late)` returns the same rows and keeps the higher cutoff. The extra cost grows
with the eviction history kept between compactions and was not measured.
See **Shared repair plan 1** in the review body.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -403,19 +404,19 @@ case class StreamingSymmetricHashJoinExec(
// Create left and right side hash joiners and store in the joiner manager.
// Both sides should use the same store generator if we are re-using the
same store instance.
val joinStateManagerStoreGenerator = new JoinStateManagerStoreGenerator()
- val joinKeyOrdinalForWatermark =
-
StreamingSymmetricHashJoinHelper.findJoinKeyOrdinalForWatermark(leftKeys,
rightKeys)
val joinerManager = OneSideHashJoinerManager(
new OneSideHashJoiner(
LeftSide, left.output, leftKeys, leftInputIter,
condition.leftSideOnly, postJoinFilter, stateWatermarkPredicates.left,
partitionId,
checkpointIds.left.keyToNumValues,
checkpointIds.left.keyWithIndexToValue,
- skippedNullValueCount, joinStateManagerStoreGenerator,
joinKeyOrdinalForWatermark),
+ skippedNullValueCount, joinStateManagerStoreGenerator,
+ StreamingJoinHelper.getStateKeyWatermarkOrdinal(rightKeys,
right.output)),
Review Comment:
**Non-blocking (P2):** For `df1.join(df2, Seq("key", "ts"))` with
`withWatermark("ts")` only on `df1`, the left manager now gets `None` here, so
every right row probing the left state goes through `getValuesInRange(key,
Long.MinValue, Long.MaxValue)`, a prefix scan with its own iterator, instead of
the single `get(key, ts)` the base branch used. The left rows are still stored
at their event time, which equals the key's `ts`, so the get would return the
same rows. Results are unchanged, and the per-probe cost was not measured.
Passing that side's own event-time key ordinal to the V4 manager when it has no
value-eviction predicate on another column would keep the point gets without
changing the stored layout or the eviction.
**Verification:**
- **Behavior:** V4 inner and right outer joins on Seq("key", "ts") with a
watermark only on the left ts return the same rows as before, including after a
restart.
- **Inspection:** The left V4 state manager of that join receives the
ordinal of its ts key, and its lookups take the single-get path rather than a
prefix scan.
- **Compatibility:** A checkpoint of that join written before the change
restarts and keeps matching its stored rows.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -224,98 +228,148 @@ 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] = {
+ 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)
val isWatermarkDefinedOnInput =
oneSideInputAttributes.exists(_.metadata.contains(delayKey))
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)
+ ordinal, oneSideJoinKeys(ordinal).dataType,
oneSideJoinKeys(ordinal).nullable)
+ // The opposite watermark bounds this key, shifted by any constant in
the opposite key.
+ def keyWatermark(watermark: Option[Long]): Option[Long] =
+ StreamingJoinHelper.getStateKeyWatermark(
+ otherSideJoinKeys, otherSideInputAttributes, ordinal, watermark)
+ keyWatermark(eventTimeWatermarkForEviction).flatMap { stateWatermark =>
Review Comment:
**Blocking (P1):** For a left semi join on `lk = rk AND lt + INTERVAL 10
SECONDS = rt`, this raises the right state's cutoff from the eviction watermark
to the eviction watermark plus 10 s less 1 ms. Left semi joins run the right
input first (`rightOutputIter ++ leftOutputIter`), and
`AddingProcessedRowToStateCompletionIterator` does not store a right row that
its state predicate evicts in this batch, although the batch's left rows have
not probed it yet. Tracing the code with a late-events watermark of 100 s and
an eviction watermark of 105 s: R(rt = 112 s) is not stored because 112 s <=
114.999 s, then L(lt = 102 s) passes late filtering, finds no match and is
stored, and it is never emitted. On the base branch the right cutoff was 105 s,
so R was stored and L was emitted in that batch. The right-first order and the
skip come from SPARK-55973 and already drop plain `lt = rt` pairs between the
two watermarks; this change extends the loss to shifted keys in every batch
that advanc
es the watermark. No test runs a left semi join with a shifted key.
**Recommended change:** For a left semi join, store every right row that the
batch's right input produces instead of skipping one that the right state
predicates already evict, so removeOldState evicts it at the end of the batch
after the batch's left rows have probed it. Inner and outer joins keep the
skip. Add join tests for a left semi join with a positively shifted left key
and with plain event-time equality where a left row and its matching right row
arrive in one batch between the two watermarks.
**Why this works:** Left semi joins process the right input first, so a
right row's only same-batch matches are left rows that probe after it; keeping
the row until the end-of-batch eviction makes it visible to them, and that
eviction still removes it before the next batch, when no later left row can
match it.
**Scope:** Keep a left semi join's right rows in state until the
end-of-batch eviction and cover same-batch pairs with join tests.
**Compatibility:** Inner and outer joins keep skipping right rows that the
batch evicts, and left semi output for rows that do not meet in the same batch
is unchanged.
**Risks:** Left semi joins now write, and evict in the same batch, right
rows that the eviction cutoff already covers, which adds state-store writes for
rows arriving between the late-events and eviction watermarks; output changes
only for the same-batch pairs that were dropped, and no setting gates it.
**Constraints:** Keep the skip for inner, left outer, right outer and full
outer joins, which probe the left input first.
**Success:** In a left semi join, a left row whose matching right row
arrives in the same batch is emitted even when that right row is at or below
the batch's right eviction cutoff. Right rows of a left semi join that the
cutoff covers are gone from state once the batch ends.
**Verification:**
- **Regression:** A left semi join on lk = rk AND lt + INTERVAL 10 SECONDS =
rt with both inputs watermarked emits the left row when it and its matching
right row arrive in one batch with the left event time between the batch's
late-events and eviction watermarks, in state formats V2, V3 and V4.
- **Regression:** A left semi join on plain lt = rt emits a left row whose
matching right row arrives in the same batch with an event time between the two
watermarks.
- **Behavior:** After such a batch the right state no longer holds the right
rows that the eviction cutoff covers.
- **Compatibility:** Inner and outer stream-stream joins still skip storing
right rows that are evicted in the same batch, with unchanged output and
state-row counts.
##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinEqualityWatermarkSuite.scala:
##########
@@ -0,0 +1,277 @@
+/*
+ * 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.spark.sql.Row
+import
org.apache.spark.sql.execution.streaming.operators.stateful.join.StreamingSymmetricHashJoinExec
+import
org.apache.spark.sql.execution.streaming.operators.stateful.join.StreamingSymmetricHashJoinHelper.{JoinStateKeyWatermarkPredicate,
JoinStateValueWatermarkPredicate}
+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
+
+class StreamingJoinEqualityWatermarkSuite extends StreamTest {
+ import testImplicits._
+
+ for {
+ version <- Seq(2, 3, 4)
+ restart <- Seq(false, true)
+ } {
+ test(s"equality eviction follows the opposite watermark, V$version
restart=$restart") {
+ 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") {
+ val leftInput = MemoryStream[(Int, Int)]
+ val rightInput = MemoryStream[(Int, Int)]
+ val left = leftInput.toDF().toDF("a", "b")
+ .select(timestamp_seconds($"a").as("la"),
timestamp_seconds($"b").as("lb"))
+ .withWatermark("la", "10 seconds")
+ val right = rightInput.toDF().toDF("a", "b")
+ .select(timestamp_seconds($"a").as("ra"),
timestamp_seconds($"b").as("rb"))
+ .withWatermark("rb", "10 seconds")
+ val joined = left.join(right, expr("la = ra AND lb = rb"),
"full_outer")
+ .select($"la".cast("int"), $"lb".cast("int"),
+ $"ra".cast("int"), $"rb".cast("int"))
+ withTempDir { checkpoint =>
+ val restartActions = if (restart) {
+ Seq(StopStream, StartStream(checkpointLocation =
checkpoint.getCanonicalPath))
+ } else {
+ Nil
+ }
+ testStream(joined)((Seq(
+ StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+ MultiAddData(leftInput, (5, 50))(rightInput, (80, 50)),
+ CheckNewAnswer(),
+ MultiAddData(leftInput, (60, 100))(rightInput, (70, 50)),
+ CheckNewAnswer(),
+ AddData(leftInput, (70, 100)),
+ // At watermark 40, left (5, 50) can still match fresh right input
on rb=50.
+ CheckNewAnswer()) ++ restartActions ++ Seq(
+ AddData(rightInput, (5, 50)),
+ CheckNewAnswer(Row(5, 50, 5, 50)),
+ // Fresh on la, but already expired on lb: V4 must visit it below
the old cutoff.
+ AddData(leftInput, (90, 10)),
+ CheckNewAnswer(Row(90, 10, null, null)),
+ MultiAddData(leftInput, (200, 200))(rightInput, (200, 200)),
+ CheckNewAnswer(Row(200, 200, 200, 200)),
+ MultiAddData(leftInput, (210, 210))(rightInput, (210, 210)),
+ CheckNewAnswer(Row(210, 210, 210, 210), Row(60, 100, null, null),
+ Row(70, 100, null, null), Row(null, null, 80, 50), Row(null,
null, 70, 50))
+ )): _*)
+ }
+ }
+ }
+ }
+
+ test("V4 window equality retains state for future unwatermarked input") {
+ withSQLConf(
+ SQLConf.STREAMING_JOIN_STATE_FORMAT_VERSION.key -> "4",
+ SQLConf.STATE_STORE_PROVIDER_CLASS.key ->
classOf[RocksDBStateStoreProvider].getName) {
+ val leftInput = MemoryStream[Int]
+ val rightInput = MemoryStream[Int]
+ val left = leftInput.toDF()
+ .select($"value".as("key"), timestamp_seconds($"value").as("time"))
+ .withWatermark("time", "10 seconds")
+ .select($"key", window($"time", "10 seconds"))
+ val right = rightInput.toDF()
+ .select($"value".as("key"), timestamp_seconds($"value").as("time"))
+ .select($"key", window($"time", "10 seconds"))
+ val joined = left.join(right, Seq("key", "window"))
+ .select($"key", $"window.end".cast("long"))
+ testStream(joined)(
+ AddData(leftInput, 1), CheckNewAnswer(),
+ AddData(rightInput, 1), CheckNewAnswer(Row(1, 10L)),
+ AddData(leftInput, 25), CheckNewAnswer(),
+ StopStream, StartStream(),
+ // The right input has no late filter; its old window must still find
left state.
+ AddData(rightInput, 1), CheckNewAnswer(Row(1, 10L)),
+ AddData(leftInput, 5), CheckNewAnswer())
+ }
+ }
+
+ for {
+ version <- Seq(2, 3, 4)
+ offset <- Seq(10, -10)
+ } {
+ test(s"equality on a shifted opposite event time evicts state, V$version
offset=$offset") {
+ 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") {
+ val leftInput = MemoryStream[(Int, Int)]
+ val rightInput = MemoryStream[(Int, Int)]
+ val left = leftInput.toDF().toDF("lk", "lt")
+ .select($"lk", timestamp_seconds($"lt").as("lt"))
+ .withWatermark("lt", "10 seconds")
+ val right = rightInput.toDF().toDF("rk", "rt")
+ .select($"rk", timestamp_seconds($"rt").as("rt"))
+ .withWatermark("rt", "10 seconds")
+ // A left row matches the right row whose time is `offset` seconds
earlier.
+ val joined = left.join(right,
+ expr(s"lk = rk AND lt = rt + INTERVAL $offset SECONDS"),
"left_outer")
+ .select($"lk", $"lt".cast("int"), $"rk", $"rt".cast("int"))
+ testStream(joined)(
+ MultiAddData(leftInput, (1, 100 + offset), (2, 90 + offset), (3, 145
+ offset))(
+ rightInput, (9, 50)),
+ CheckNewAnswer(),
+ AddData(rightInput, (1, 100)),
+ CheckNewAnswer(Row(1, 100 + offset, 1, 100)),
+ MultiAddData(leftInput, (9, 300))(rightInput, (9, 150)),
+ // At watermark 90, a future right row can still have time 90.
+ CheckNewAnswer(),
+ AddData(rightInput, (9, 151)),
+ // At watermark 140, the left key cutoff is 140 + offset.
+ CheckNewAnswer(Row(2, 90 + offset, null, null)),
Review Comment:
**Nit (P3):** In this evicting batch (late watermark 90 s, eviction
watermark 140 s) the only unmatched left row is `(2, 100 s)`, which lies above
`keyWatermark(90 s)` = 99.999 s. A V4 scan starting there would emit the same
rows, so this test would still pass if the scan-start rule regressed, while a
left row such as `(4, 95 s)` arriving in this batch would then be skipped and
never emitted null-padded. Adding such a row and asserting its null-padded
output for both shift signs, plus a `prevStateWatermark` assertion for shifted
keys in StreamingSymmetricHashJoinHelperSuite, would pin the boundary.
See **Shared repair plan 1** in the review body.
--
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]