HeartSaVioR commented on code in PR #60280:
URL: https://github.com/apache/spark/pull/60280#discussion_r4546997765
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -224,98 +230,334 @@ 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 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)
+ 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)
+ }
}
} 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)
+ // TODO(SPARK-61347): this needs the input's own watermark, although
the analysis check
+ // admits a range bound without one.
+ // TODO(SPARK-61348): the analysis check also admits a range bound on
a column that is
+ // not TIMESTAMP, which this branch never evicts.
+ 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)] = {
+ // TODO(SPARK-61348): the analysis check admits a range bound on a column
that is not
+ // TIMESTAMP, which no candidate below takes.
+ // TODO(SPARK-61349): a conjunct that uses only constants still caps the
cutoff, so it can
+ // stop eviction.
+ 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
+ }
+
+ /**
+ * 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 its event
time:
+ * `consumedSides` names the inputs whose event time such an operator reads,
both when the
+ * operator cannot be traced and none when no stateful operator follows. 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. It
also excludes a key
+ * computed from the event time by a constant, which older versions evicted
at the unshifted
+ * watermark. 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 keep such a row, as
older versions did,
+ * because its eviction predicate is unknown.
+ * TODO: evict the NULL-key rows that older versions stored in V1 to V3
state.
+ */
+ private[sql] def isWatermarkCheckpointCompatible(
+ leftAttributes: Seq[Attribute],
+ rightAttributes: Seq[Attribute],
+ leftKeys: Seq[Expression],
+ 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 &&
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. You are right: only a backward shift was evicted too early. Fixed in
[738ebe585c9](https://github.com/apache/spark/pull/60280/commits/738ebe585c98779d084c4c661c1b27a71ecbc8de).
The restart check now accepts an equality key that shifts one input's event
time forward, when the other input's key at that ordinal is its own event time,
no other key uses an event time, and no later stateful operator reads the
shifted input's event time. A new helper,
`StreamingJoinHelper.isForwardShiftOfEventTime`, uses the same shift rule as
eviction, so exact intervals, whole days, months or years, timestampadd and
foldable intervals all count. The docstrings and the migration guide now name
backward shifts and a read shifted input as the reasons to reject. New tests
restart forward-shift checkpoints in V1 to V4 and compare the matches with an
uninterrupted run. Backward shifts, keys shifted on both inputs, and a forward
shift whose shifted time a later operator reads are still rejected before
state is opened.
<!-- sp2k-review3 reply 4537719955 -->
##########
docs/streaming/ss-migration-guide.md:
##########
@@ -25,6 +25,95 @@ Please refer [Migration Guide: SQL, Datasets and
DataFrame](../sql-migration-gui
## Upgrading from Structured Streaming 4.3 to 4.4
+- Since Spark 4.4, left outer and left semi stream-stream joins require a
watermark on the
+ right input and a time condition that limits how late a matching right row
can arrive.
+ Right outer joins require the corresponding settings on the left; full outer
joins require
+ them on both sides. An equality key counts as such a time condition when it
is the other
+ input's event time, or that event time shifted by constant intervals, except
a shift backward
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
[738ebe585c9](https://github.com/apache/spark/pull/60280/commits/738ebe585c98779d084c4c661c1b27a71ecbc8de).
Both the migration guide and the note under the join support table now say
that a backward shift by months, years, or a day-time interval of 24 hours or
more does not count, with `rightTime - INTERVAL 36 HOURS` as an example. They
also say that `timestampadd` in hours, minutes or seconds counts at any size.
<!-- sp2k-review3 reply 4537719892 -->
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -706,32 +707,122 @@ 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)
+
+ // TODO(SPARK-61347): this accepts a range bound on an input without its
own watermark,
+ // which eviction does not finalize yet.
+ // TODO(SPARK-61348): this also accepts a range bound on a column that is
not TIMESTAMP,
+ // which eviction never finalizes.
+ // TODO(SPARK-61349): this also accepts a bound that uses only constants,
which does not
+ // follow the other input's watermark and so cannot finalize unmatched
state.
+ 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,
+ AttributeSet(eventTime.toSeq), join.condition,
Some(1000000)).isDefined
+ }
+
+ // The rule of Spark versions before 4.4: a watermarked equality key, or a
range bound that the
+ // solver finds for a finalized input. Disabling the finalization check
never goes below it.
+ def admittedBeforeFinalizationCheck: Boolean = {
+ def hasRangeBound(stateInput: LogicalPlan, otherInput: LogicalPlan):
Boolean =
+ StreamingJoinHelper.getStateValueWatermark(stateInput.outputSet,
otherInput.outputSet,
+ join.condition, Some(1000000)).isDefined
+ (leftKeys ++ rightKeys).exists {
+ case a: AttributeReference =>
a.metadata.contains(EventTimeWatermark.delayKey)
+ case _ => false
+ } || (join.joinType match {
+ case LeftOuter | LeftSemi => hasRangeBound(join.left, join.right)
+ case RightOuter => hasRangeBound(join.right, join.left)
+ case _ => hasRangeBound(join.left, join.right) ||
hasRangeBound(join.right, join.left)
+ })
+ }
+
+ val leftCanEvict = canEvictState(join.left, join.right, rightKeys)
+ val rightCanEvict = canEvictState(join.right, join.left, leftKeys)
+ val hasRequiredWatermarks = join.joinType match {
+ case LeftOuter | LeftSemi => leftCanEvict
+ case RightOuter => rightCanEvict
+ case FullOuter => leftCanEvict && rightCanEvict
case _ =>
throwError(
s"Join type ${join.joinType} is not supported with streaming
DataFrame/Dataset")(join)
}
- if (!watermarkInJoinKeys && !hasValidWatermarkRange) {
- throwError(
+ if (!hasRequiredWatermarks) {
+ val requirement = join.joinType match {
+ case FullOuter => "watermarks on both inputs and time constraints in
both directions"
+ case RightOuter => "a watermark on the left input and a time
constraint"
+ case _ => "a watermark on the right input and a time constraint"
+ }
+ // The join holds back its output watermark for an input whose state is
unbounded.
+ val downstreamRequirement = join.joinType match {
+ case LeftOuter => Some(("right", "left"))
+ case RightOuter => Some(("left", "right"))
+ case _ => None
+ }
+ val downstreamNote = downstreamRequirement.map { case (eventTimeInput,
boundingInput) =>
+ s" A stateful operator after the join that uses the $eventTimeInput
input's event time " +
+ s"also needs a watermark on the $boundingInput input and a reverse
time constraint; " +
+ "otherwise the join holds back its output watermark for that input,
so an " +
+ "append-mode aggregation over that event time fails at start, and
other operators " +
+ "keep that input's rows in state and do not emit results that wait
for the watermark."
+ }.getOrElse("")
+ // In legacy mode an input can keep its event time and a window over it,
both watermarked.
+ // Late rows are filtered by the first of them, so only that column
bounds state.
+ val legacyWindowNote = if
(SQLConf.get.getConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE)) {
+ ""
+ } else {
+ def windowNote(input: LogicalPlan, inputKeys: Seq[Expression], side:
String): String = {
+ val eventTime =
input.output.find(_.metadata.contains(EventTimeWatermark.delayKey))
+ val windowKey = inputKeys.collectFirst {
+ case a: Attribute if a.metadata.contains(TimeWindow.marker) &&
+ a.metadata.contains(EventTimeWatermark.delayKey) &&
+ !eventTime.exists(_.semanticEquals(a)) => a
+ }
+ val note = for (first <- eventTime; window <- windowKey) yield {
+ s" With ${SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key}=false, the
$side input " +
+ s"filters late rows by its first watermarked column,
${first.name}, so its window " +
+ s"key ${window.name} is not a time constraint. Put
${window.name} before " +
+ s"${first.name} in that input's columns, or drop ${first.name},
to bound state " +
+ "by the window."
+ }
+ note.getOrElse("")
+ }
+ val leftNote = if (rightCanEvict) "" else windowNote(join.left,
leftKeys, "left")
+ val rightNote = if (leftCanEvict) "" else windowNote(join.right,
rightKeys, "right")
+ join.joinType match {
+ case LeftOuter | LeftSemi => rightNote
+ case RightOuter => leftNote
+ case _ => leftNote + rightNote
+ }
+ }
+ val checkConf = SQLConf.STREAMING_JOIN_CHECK_FINALIZATION_ENABLED.key
+ val canDisableCheck = admittedBeforeFinalizationCheck
+ val disableNote = if (canDisableCheck) {
+ s" To run the query anyway, set $checkConf to false; the query then
keeps that " +
+ "state without bound, and an outer join never outputs those
unmatched rows."
+ } else {
+ ""
+ }
+ val message =
s"Stream-stream ${join.joinType} join between two streaming
DataFrame/Datasets " +
- "is not supported without a watermark in the join keys, or a
watermark on " +
- "the nullable side and an appropriate range condition")(join)
+ s"is not supported: it requires $requirement " +
+ "that allow unmatched state to be finalized. " +
+ "The time constraint may be equality on event time or a time range
condition. " +
+ "When upgrading an existing query, correct its watermarks and time
constraints, " +
+ "then use a new checkpoint and replay the input, reconciling prior
sink output." +
+ legacyWindowNote + downstreamNote + disableNote
+ if (SQLConf.get.streamingJoinCheckFinalizationEnabled ||
!canDisableCheck) {
+ throwError(message)(join)
+ } else {
+ logWarning(log"${MDC(ANALYSIS_ERROR, message)};\n${MDC(QUERY_PLAN,
join)}")
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
[738ebe585c9](https://github.com/apache/spark/pull/60280/commits/738ebe585c98779d084c4c661c1b27a71ecbc8de).
When the conf is false and the join is still runnable, the checker now logs a
separate warning. It says the join runs with the check disabled, names the
missing watermark and time constraint, and says the query keeps that state
without bound and an outer join never outputs those unmatched rows. The error
for the default conf is unchanged.
<!-- sp2k-review3 reply 4537719919 -->
##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationsSuite.scala:
##########
@@ -511,52 +517,275 @@ class UnsupportedOperationsSuite extends SparkFunSuite
with SQLHelper {
Seq("is not supported in Complete output mode", allowedModesMsg))
}
- // Left outer, right outer, full outer, left semi joins
- Seq(LeftOuter, RightOuter, FullOuter, LeftSemi).foreach { joinType =>
- // Stream-stream allowed with join on watermark attribute
- // Note that the attribute need not be watermarked on both sides.
- assertSupportedInStreamingPlan(
- s"$joinType join with stream-stream relations and join on attribute with
left watermark",
- streamRelation.join(streamRelation, joinType = joinType,
- condition = Some(attributeWithWatermark === attribute)),
- OutputMode.Append())
- assertSupportedInStreamingPlan(
- s"$joinType join with stream-stream relations and join on attribute with
right watermark",
- streamRelation.join(streamRelation, joinType = joinType,
- condition = Some(attribute === attributeWithWatermark)),
- OutputMode.Append())
- assertNotSupportedInStreamingPlan(
- s"$joinType join with stream-stream relations and join on
non-watermarked attribute",
- streamRelation.join(streamRelation, joinType = joinType,
- condition = Some(attribute === attribute)),
- OutputMode.Append(),
- Seq("without a watermark in the join keys"))
-
- val timeWithWatermark =
- AttributeReference("b", IntegerType)().withMetadata(watermarkMetadata)
- val relationWithWatermark = new TestStreamingRelation(timeWithWatermark)
- val (leftRelation, rightRelation) =
- if (joinType == RightOuter) {
- (relationWithWatermark, streamRelation)
- } else {
- (streamRelation, relationWithWatermark)
+ for {
+ joinType <- Seq(LeftOuter, RightOuter, FullOuter, LeftSemi)
+ leftWatermark <- Seq(false, true)
+ rightWatermark <- Seq(false, true)
+ conditionType <- Seq("equality", "range", "left bound", "right bound")
+ } {
+ val leftTime = AttributeReference("leftTime", TimestampType)()
+ val rightTime = AttributeReference("rightTime", TimestampType)()
+ val left = if (leftWatermark) leftTime.withMetadata(watermarkMetadata)
else leftTime
+ val right = if (rightWatermark) rightTime.withMetadata(watermarkMetadata)
else rightTime
+ val condition = conditionType match {
+ case "equality" => left === right
+ case "range" => left > right - 10 && left < right + 10
+ case "left bound" => left > right - 10
+ case "right bound" => left < right + 10
+ }
+ val leftCanEvict = rightWatermark && conditionType != "right bound"
+ val rightCanEvict = leftWatermark && conditionType != "left bound"
+ val correctedSupported = joinType match {
+ case LeftOuter | LeftSemi => leftCanEvict
+ case RightOuter => rightCanEvict
+ case FullOuter => leftCanEvict && rightCanEvict
+ case _ => false
+ }
+ val plan = new TestStreamingRelation(left).join(new
TestStreamingRelation(right),
+ joinType = joinType, condition = Some(condition))
+ val name = s"$joinType $conditionType with watermarks " +
+ s"left=$leftWatermark right=$rightWatermark"
+ if (correctedSupported) {
+ assertSupportedInStreamingPlan(name, plan, OutputMode.Append())
+ } else {
+ assertNotSupportedInStreamingPlan(name, plan, OutputMode.Append(),
+ Seq("requires", "allow unmatched state to be finalized"))
+ }
+ }
+
+ {
+ val leftTime = AttributeReference("leftTime", TimestampType)()
+ val leftOther = AttributeReference("leftOther", TimestampType)()
+ .withMetadata(watermarkMetadata)
+ val rightTime = AttributeReference("rightTime", TimestampType)()
+ .withMetadata(watermarkMetadata)
+ val rightOther = AttributeReference("rightOther", TimestampType)()
+ val left = new TestStreamingRelation(Seq(leftTime, leftOther))
+ val right = new TestStreamingRelation(Seq(rightTime, rightOther))
+
+ // Each side's state is evicted by the key that the opposite watermark
bounds.
+ assertSupportedInStreamingPlan("full outer with different watermark key
ordinals",
+ left.join(right, joinType = FullOuter,
+ condition = Some(leftTime === rightTime && leftOther === rightOther)),
OutputMode.Append())
+ }
+
+ {
+ val leftTime = AttributeReference("leftTime", TimestampType)()
+ .withMetadata(watermarkMetadata)
+ val rightTime = AttributeReference("rightTime", TimestampType)()
+ .withMetadata(watermarkMetadata)
+ val rightOther = AttributeReference("rightOther", TimestampType)()
+ val left = new TestStreamingRelation(leftTime)
+ val right = new TestStreamingRelation(Seq(rightTime, rightOther))
+
+ def shift(time: Expression, seconds: Int): Expression =
+ TimestampAddInterval(time, Literal(Duration.ofSeconds(seconds)))
+
+ // A key computed from the opposite event time by a constant is bounded by
its watermark.
+ Seq(10, -10).foreach { offset =>
+ Seq(LeftOuter, RightOuter, FullOuter, LeftSemi).foreach { joinType =>
+ assertSupportedInStreamingPlan(s"$joinType with a key shifted by
$offset",
+ left.join(right, joinType = joinType,
+ condition = Some(leftTime === shift(rightTime, offset))),
OutputMode.Append())
}
+ assertNotSupportedInStreamingPlan(
+ s"LeftOuter with a key shifted by $offset from an unwatermarked
column",
+ left.join(right, joinType = LeftOuter,
+ condition = Some(leftTime === shift(rightOther, offset))),
OutputMode.Append(),
+ Seq("requires a watermark on the right input"))
+ }
- // stream-stream allowed with range condition yielding state value
watermark
- assertSupportedInStreamingPlan(
- s"$joinType join with stream-stream relations and state value watermark",
- leftRelation.join(rightRelation, joinType = joinType,
- condition = Some(attribute > timeWithWatermark + 10)),
- OutputMode.Append())
+ // The admission check sees the analyzed plan, where an interval
expression such as
+ // INTERVAL 1 HOUR * 2 is not folded yet. It is bounded as its value is.
+ val twoHours = MultiplyDTInterval(Literal(Duration.ofHours(1)), Literal(2))
+ Seq(LeftOuter, FullOuter, LeftSemi).foreach { joinType =>
+ assertSupportedInStreamingPlan(s"$joinType with a key shifted by an
interval expression",
+ left.join(right, joinType = joinType,
+ condition = Some(leftTime === TimestampAddInterval(rightTime,
twoHours, Some("UTC")))),
+ OutputMode.Append())
+ }
+ Seq(
+ "minus two days" -> TimestampAddInterval(rightTime,
+ MultiplyDTInterval(Literal(Duration.ofDays(1)), Literal(-2)),
Some("UTC")),
+ "minus two months" -> TimestampAddYMInterval(rightTime,
+ MultiplyYMInterval(Literal(Period.ofMonths(1)), Literal(-2)),
Some("UTC")),
+ "an unwatermarked column" -> TimestampAddInterval(rightOther, twoHours,
Some("UTC")),
+ "a truncated time" -> TimestampAddInterval(
+ rightTime.cast(LongType).cast(TimestampType), twoHours,
Some("UTC"))).foreach {
+ case (name, key) =>
+ assertNotSupportedInStreamingPlan(
+ s"LeftOuter with a key shifted by an interval expression: $name",
+ left.join(right, joinType = LeftOuter, condition = Some(leftTime ===
key)),
+ OutputMode.Append(), Seq("requires a watermark on the right input"))
+ }
- // stream-stream not allowed with insufficient range condition
- assertNotSupportedInStreamingPlan(
- s"$joinType join with stream-stream relations and state value watermark",
- leftRelation.join(rightRelation, joinType = joinType,
- condition = Some(attribute < timeWithWatermark + 10)),
- OutputMode.Append(),
- Seq("is not supported without a watermark in the join keys, or a
watermark on " +
- "the nullable side and an appropriate range condition"))
+ // timestampadd is a shift too: exact for a sub-day unit, and forward-only
for days, weeks,
+ // months, quarters and years with a non-negative amount.
+ Seq(
+ ("one hour", TimestampAdd("HOUR", Literal(1), rightTime, Some("UTC")),
true),
+ ("one day", TimestampAdd("DAY", Literal(1), rightTime,
Some("America/Los_Angeles")), true),
+ ("minus one day", TimestampAdd("DAY", Literal(-1), rightTime,
Some("UTC")), false),
+ ("one hour of an unwatermarked column",
+ TimestampAdd("HOUR", Literal(1), rightOther, Some("UTC")),
false)).foreach {
+ case (name, key, supported) =>
+ Seq(LeftOuter, FullOuter, LeftSemi).foreach { joinType =>
+ val plan = left.join(right, joinType = joinType, condition =
Some(leftTime === key))
+ val testName = s"$joinType with a key shifted by timestampadd of
$name"
+ if (supported) {
+ assertSupportedInStreamingPlan(testName, plan, OutputMode.Append())
+ } else {
+ val requirement = if (joinType == FullOuter) {
+ "watermarks on both inputs"
+ } else {
+ "a watermark on the right input"
+ }
+ assertNotSupportedInStreamingPlan(testName, plan,
OutputMode.Append(),
+ Seq(s"requires $requirement"))
+ }
+ }
+ }
+
+ // Whole days are added in the session time zone, where a day can be 23 or
25 hours, and
+ // months vary in length. A shift that never moves a time backward still
bounds the key, in
+ // every time zone; one that can move a time backward does not.
+ for {
+ zone <- Seq("UTC", "America/Los_Angeles")
+ (name, interval, supported) <- Seq(
+ ("one day", Literal(Duration.ofDays(1)), true),
+ ("minus one day", Literal(Duration.ofDays(-1)), false),
+ ("one month", Literal(Period.ofMonths(1)), true),
+ ("minus one month", Literal(Period.ofMonths(-1)), false))
+ } {
+ val shifted = interval.dataType match {
+ case _: YearMonthIntervalType => TimestampAddYMInterval(rightTime,
interval, Some(zone))
+ case _ => TimestampAddInterval(rightTime, interval, Some(zone))
+ }
+ Seq(LeftOuter, LeftSemi, FullOuter).foreach { joinType =>
+ val plan = left.join(right, joinType = joinType, condition =
Some(leftTime === shifted))
+ val testName = s"$joinType with a key shifted by $name in $zone"
+ if (supported) {
+ assertSupportedInStreamingPlan(testName, plan, OutputMode.Append())
+ } else {
+ val requirement = if (joinType == FullOuter) {
+ "watermarks on both inputs"
+ } else {
+ "a watermark on the right input"
+ }
+ assertNotSupportedInStreamingPlan(testName, plan,
OutputMode.Append(),
+ Seq(s"requires $requirement"))
+ }
+ }
+ }
+
+ // Truncation can map a future right row below the watermark, so it does
not bound the key.
+ assertNotSupportedInStreamingPlan("LeftOuter with a key truncated from the
right event time",
+ left.join(right, joinType = LeftOuter,
+ condition = Some(leftTime ===
rightTime.cast(LongType).cast(TimestampType))),
+ OutputMode.Append(), Seq("requires a watermark on the right input"))
+ }
+
+ // With allowMultiple=false, late rows are filtered by an input's first
watermarked column, so
+ // a time window key bounds the opposite state only when the window is that
column.
+ {
+ val windowType = new StructType().add("start", TimestampType).add("end",
TimestampType)
+ val windowMetadata = new MetadataBuilder()
+ .withMetadata(watermarkMetadata)
+ .putBoolean(TimeWindow.marker, true)
+ .build()
+ def windowJoin(joinType: JoinType, windowFirst: Boolean): LogicalPlan = {
+ def input(side: String): (LogicalPlan, Attribute, Attribute) = {
+ val key = AttributeReference(s"${side}Key", IntegerType)()
+ val time = AttributeReference(s"${side}Time", TimestampType)()
+ .withMetadata(watermarkMetadata)
+ val window = AttributeReference(s"${side}Window", windowType)()
+ .withMetadata(windowMetadata)
+ val output = if (windowFirst) Seq(key, window, time) else Seq(key,
time, window)
+ (TestStreamingRelation(output), key, window)
+ }
+ val (left, leftKey, leftWindow) = input("left")
+ val (right, rightKey, rightWindow) = input("right")
+ left.join(right, joinType = joinType,
+ condition = Some(leftKey === rightKey && leftWindow === rightWindow))
+ }
+ val legacyMode = SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key -> "false"
+ Seq(
+ LeftOuter -> Seq("right"),
+ LeftSemi -> Seq("right"),
+ RightOuter -> Seq("left"),
+ FullOuter -> Seq("left", "right")).foreach { case (joinType, sides) =>
+ test(s"$joinType on a window after its event time in legacy mode names
the column order") {
+ val error = intercept[AnalysisException] {
+ withSQLConf(legacyMode) {
+ UnsupportedOperationChecker.checkForStreaming(
+ wrapInStreaming(windowJoin(joinType, windowFirst = false)),
OutputMode.Append())
+ }
+ }
+ sides.foreach { side =>
+ assert(error.getMessage.contains(s"the $side input filters late rows
by its first " +
+ s"watermarked column, ${side}Time, so its window key ${side}Window
is not a time " +
+ s"constraint. Put ${side}Window before ${side}Time in that input's
columns, or " +
+ s"drop ${side}Time"))
+ }
+ Seq("left", "right").diff(sides).foreach { side =>
+ assert(!error.getMessage.contains(s"the $side input filters late
rows"))
+ }
+ }
+
+ test(s"$joinType on a window after its event time in the default mode
has no window hint") {
+ val error = intercept[AnalysisException] {
+ UnsupportedOperationChecker.checkForStreaming(
+ wrapInStreaming(windowJoin(joinType, windowFirst = false)),
OutputMode.Append())
+ }
+ assert(error.getMessage.contains("allow unmatched state to be
finalized"))
+
assert(!error.getMessage.contains(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key))
+ }
+
+ assertSupportedInStreamingPlan(s"$joinType on a window before its event
time in legacy mode",
+ windowJoin(joinType, windowFirst = true), OutputMode.Append(),
legacyMode)
+ }
+ }
+
+ // Disabling the finalization check turns the admission failure into a
warning.
+ Seq(LeftOuter, LeftSemi).foreach { joinType =>
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
[738ebe585c9](https://github.com/apache/spark/pull/60280/commits/738ebe585c98779d084c4c661c1b27a71ecbc8de).
We added the two cases you described. A full outer join on a one-sided range
with both inputs watermarked fails by default with an error that names the
conf, and runs with a warning when the conf is false. A right outer join whose
range bounds only the left input fails with the conf true or false, and its
error does not name the conf. These tests would fail if the right-outer
arguments swapped, if full outer needed both directions, or if that arm
returned false.
<!-- sp2k-review3 reply 4537719935 -->
##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinCheckpointCompatibilitySuite.scala:
##########
@@ -0,0 +1,779 @@
+/*
+ * 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 java.io.File
+import java.nio.file.Files
+
+import scala.jdk.CollectionConverters._
+import scala.util.Using
+
+import org.apache.hadoop.fs.Path
+
+import org.apache.spark.sql.{AnalysisException, DataFrame, Row}
+import org.apache.spark.sql.catalyst.expressions.{Alias, Attribute,
AttributeReference, Cast, Expression, GreaterThan}
+import org.apache.spark.sql.catalyst.plans.logical.EventTimeWatermark
+import org.apache.spark.sql.execution.streaming.checkpointing.{OffsetMap,
OffsetSeq, OffsetSeqLog}
+import
org.apache.spark.sql.execution.streaming.operators.stateful.join.{StreamingSymmetricHashJoinExec,
StreamingSymmetricHashJoinHelper}
+import
org.apache.spark.sql.execution.streaming.operators.stateful.join.StreamingSymmetricHashJoinHelper.{JoinStateKeyWatermarkPredicate,
JoinStateValueWatermarkPredicate, LeftSide, RightSide}
+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.sql.types.{IntegerType, LongType, MetadataBuilder,
StructField,
+ StructType, TimestampType}
+import org.apache.spark.tags.SlowSQLTest
+import org.apache.spark.util.Utils
+
+@SlowSQLTest
+class StreamingJoinCheckpointCompatibilitySuite extends StreamTest {
+ import testImplicits._
+
+ private val markerKey =
SQLConf.STREAMING_JOIN_CHECKPOINT_WATERMARK_SEMANTICS_VERSION.key
+ private val currentMarker =
+
SQLConf.STREAMING_JOIN_CHECKPOINT_WATERMARK_SEMANTICS_VERSION.defaultValue.get.toString
+
+ private def setMarker(checkpoint: String, marker: Option[String]): Unit = {
+ def update(conf: Map[String, String]): Map[String, String] = {
+ (conf - markerKey) ++ marker.map(markerKey -> _)
+ }
+ val offsetsPath = checkpoint + "/offsets"
+ val log = new OffsetSeqLog(spark, offsetsPath)
+ val (batchId, offsets) = log.getLatest().get
+ val updated = offsets match {
+ case o: OffsetSeq =>
+ o.copy(metadataOpt = o.metadataOpt.map(m => m.copy(conf =
update(m.conf))))
+ case o: OffsetMap =>
+ o.copy(metadata = o.metadata.copy(conf = update(o.metadata.conf)))
+ }
+ val path = new Path(offsetsPath, batchId.toString)
+ assert(path.getFileSystem(spark.sessionState.newHadoopConf()).delete(path,
false))
+ assert(log.add(batchId, updated))
+ }
+
+ private def snapshot(directory: File): Map[String, Seq[Byte]] = {
+ Using.resource(Files.walk(directory.toPath)) { paths =>
+ paths.iterator().asScala.filter(Files.isRegularFile(_)).map { path =>
+ directory.toPath.relativize(path).toString ->
Files.readAllBytes(path).toSeq
+ }.toMap
+ }
+ }
+
+ private def pinnedMarker(checkpoint: String): Option[String] = {
+ new OffsetSeqLog(spark, checkpoint +
"/offsets").getLatest().get._2.metadataOpt.get
+ .conf.get(markerKey)
+ }
+
+ private def markerAt(checkpoint: String, batchId: Long): Option[String] = {
+ new OffsetSeqLog(spark, checkpoint +
"/offsets").get(batchId).get.metadataOpt.get
+ .conf.get(markerKey)
+ }
+
+ private def withJoinConf(version: Int, logVersion: Int)(f: => Unit): Unit = {
+ withSQLConf(
+ SQLConf.STREAMING_JOIN_STATE_FORMAT_VERSION.key -> version.toString,
+ SQLConf.STREAMING_OFFSET_LOG_FORMAT_VERSION.key -> logVersion.toString,
+ SQLConf.STATE_STORE_PROVIDER_CLASS.key ->
classOf[RocksDBStateStoreProvider].getName,
+ SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> "false")(f)
+ }
+
+ private def assertNonNullableOutput(dataFrame: DataFrame, columnNames:
String*): Unit = {
+ val outputByName = dataFrame.queryExecution.analyzed.output.map(a =>
a.name -> a).toMap
+ columnNames.foreach { columnName =>
+ val attribute = outputByName(columnName)
+ assert(!attribute.nullable, s"Expected $columnName to be non-null in
$attribute")
+ }
+ }
+
+ private def joinInputs(shape: String): (MemoryStream[(Int, Int)],
+ MemoryStream[(Int, Int)], DataFrame) = {
+ val leftInput = MemoryStream[(Int, Int)]
+ val rightInput = MemoryStream[(Int, Int)]
+ val leftData = leftInput.toDF().toDF("leftKey", "time")
+ .select($"leftKey", timestamp_seconds($"time").as("leftTime"),
+ timestamp_seconds($"time" + 10).as("expiry"))
+ val rightData = rightInput.toDF().toDF("rightKey", "time")
+ .select($"rightKey", timestamp_seconds($"time").as("rightTime"))
+ val left = if (Seq("equality", "expiry", "pruned expiry", "unbounded")
+ .contains(shape)) {
+ leftData.withWatermark("leftTime", "100 seconds")
+ } else {
+ leftData
+ }
+ val right = if (shape != "no watermark") {
+ rightData.withWatermark("rightTime", "100 seconds")
+ } else {
+ rightData
+ }
+ val condition = shape match {
+ case "range" => "leftKey = rightKey AND leftTime > rightTime - INTERVAL
5 SECONDS"
+ case "expiry" => "leftKey = rightKey AND rightTime BETWEEN leftTime AND
expiry"
+ case "pruned expiry" => "leftKey = rightKey AND rightTime <= expiry"
+ case "unbounded" => "leftKey = rightKey"
+ case _ => "leftKey = rightKey AND leftTime = rightTime"
+ }
+ val joined = left.join(right, expr(condition))
+ val result = if (shape == "unbounded") {
+ // A stateful operator after this key-only join reads its output
watermark.
+ joined.select($"leftKey", $"rightKey", $"leftTime".cast("long"),
+ $"rightTime".cast("long")).dropDuplicates()
+ } else {
+ joined.select($"leftKey", $"rightKey")
+ }
+ (leftInput, rightInput, result)
+ }
+
+ private def nullableAlignedJoinInputs(): (MemoryStream[Int],
MemoryStream[Int], DataFrame) = {
+ val leftInput = MemoryStream[Int]
+ val rightInput = MemoryStream[Int]
+ val left = leftInput.toDF().toDF("value")
+ .select(when($"value" < 0, lit(null).cast(TimestampType))
+ .otherwise(timestamp_seconds($"value")).as("leftTime"))
+ .withWatermark("leftTime", "100 seconds")
+ val right = rightInput.toDF().toDF("value")
+ .select(timestamp_seconds($"value").as("rightTime"))
+ .withWatermark("rightTime", "100 seconds")
+ val joined = left.join(right, expr("leftTime = rightTime"), "full_outer")
+ .select($"leftTime".cast("long"), $"rightTime".cast("long"))
+ (leftInput, rightInput, joined)
+ }
+
+ private def nonNullableAlignedJoinInputs(): (MemoryStream[Long],
MemoryStream[Long],
+ DataFrame) = {
+ val leftInput = MemoryStream[Long]
+ val rightInput = MemoryStream[Long]
+ val left = leftInput.toDF().toDF("value")
+ .select(coalesce(timestamp_seconds($"value"), lit(new
java.sql.Timestamp(0L)))
+ .as("leftTime"))
+ .withWatermark("leftTime", "100 seconds")
+ val right = rightInput.toDF().toDF("value")
+ .select(coalesce(timestamp_seconds($"value"), lit(new
java.sql.Timestamp(0L)))
+ .as("rightTime"))
+ .withWatermark("rightTime", "100 seconds")
+ assertNonNullableOutput(left, "leftTime")
+ assertNonNullableOutput(right, "rightTime")
+ val joined = left.join(right, expr("leftTime = rightTime"), "full_outer")
+ .select($"leftTime".cast("long"), $"rightTime".cast("long"))
+ (leftInput, rightInput, joined)
+ }
+
+ test("checkpoint compatibility requires one aligned own-event-time equality
key") {
+ val watermarkMetadata = new MetadataBuilder()
+ .putLong(EventTimeWatermark.delayKey, 0L).build()
+ val leftId = AttributeReference("leftId", IntegerType)()
+ val rightId = AttributeReference("rightId", IntegerType)()
+ val leftTime = AttributeReference("leftTime", TimestampType,
+ metadata = watermarkMetadata)()
+ val rightTime = AttributeReference("rightTime", TimestampType,
+ metadata = watermarkMetadata)()
+ val compatible =
StreamingSymmetricHashJoinHelper.isWatermarkCheckpointCompatible(
+ _: Seq[Attribute], _: Seq[Attribute], _: Seq[Expression], _:
Seq[Expression], None,
+ consumedSides = Set(LeftSide, RightSide))
+
+ assert(compatible(Seq(leftId), Seq(rightId), Seq(leftId), Seq(rightId)))
+ assert(compatible(Seq(leftId, leftTime), Seq(rightId, rightTime),
+ Seq(leftId, leftTime), Seq(rightId, rightTime)))
+ assert(!compatible(Seq(leftId, leftTime), Seq(rightId, rightTime),
+ Seq(leftId, leftTime), Seq(rightTime, rightId)))
+ assert(!compatible(Seq(leftId, leftTime), Seq(rightId, rightTime),
+ Seq(leftId, leftTime, leftTime), Seq(rightId, rightTime, rightTime)))
+ assert(!compatible(Seq(leftId, leftTime), Seq(rightId, rightTime),
+ Seq(leftId), Seq(rightId)))
+ assert(!compatible(Seq(leftId, leftTime), Seq(rightId),
+ Seq(leftId, leftTime), Seq(rightId, rightId)))
+ assert(!compatible(Seq(leftId), Seq(rightId, rightTime),
+ Seq(leftId, leftId), Seq(rightId, rightTime)))
+ assert(!compatible(Seq(leftTime, rightTime), Seq(rightTime),
+ Seq(leftTime), Seq(rightTime)))
+ assert(!compatible(Seq(leftTime), Seq(rightTime, leftTime),
+ Seq(leftTime), Seq(rightTime)))
+ // Metadata alone must not select an earlier key or hide a computed
watermarked key.
+ val computed = Alias(leftTime, "computed")()
+ assert(!compatible(Seq(leftTime), Seq(rightTime),
+ Seq(computed, leftTime), Seq(rightTime, rightTime)))
+ assert(!compatible(Seq(leftId), Seq(rightId), Seq(computed), Seq(rightId)))
+
+ // A key-only join is accepted only when no stateful operator after it
reads its output
+ // watermark. Another condition, or a key that uses an event time, makes
it not key-only.
+ val notConsumed =
StreamingSymmetricHashJoinHelper.isWatermarkCheckpointCompatible(
+ _: Seq[Attribute], _: Seq[Attribute], _: Seq[Expression], _:
Seq[Expression],
+ _: Option[Expression], consumedSides = Set.empty)
+ val leftInput = Seq(leftId, leftTime)
+ val rightInput = Seq(rightId, rightTime)
+ assert(notConsumed(leftInput, rightInput, Seq(leftId), Seq(rightId), None))
+ assert(!notConsumed(leftInput, rightInput, Seq(leftId), Seq(rightId),
+ Some(GreaterThan(leftId, rightId))))
+ assert(!notConsumed(leftInput, rightInput, Seq(leftId, Cast(leftTime,
LongType)),
+ Seq(rightId, Cast(rightTime, LongType)), None))
+ assert(!notConsumed(leftInput, rightInput, Seq(leftId, computed),
Seq(rightId, rightTime),
+ None))
+
+ // Ordering time windows is excluded even when nothing reads the output
watermark: older
+ // versions derived an ordering bound for whole windows that this version
removes.
+ val windowType = StructType(Seq(
+ StructField("start", TimestampType), StructField("end", TimestampType)))
+ val leftWindow = AttributeReference("leftWindow", windowType,
+ metadata = watermarkMetadata)()
+ val rightWindow = AttributeReference("rightWindow", windowType,
+ metadata = watermarkMetadata)()
+ assert(!notConsumed(Seq(leftId, leftWindow), Seq(rightId, rightWindow),
Seq(leftId),
+ Seq(rightId), Some(GreaterThan(leftWindow, rightWindow))))
+ }
+
+ test("checkpoint compatibility does not depend on selected key nullability")
{
+ val watermarkMetadata = new MetadataBuilder()
+ .putLong(EventTimeWatermark.delayKey, 0L).build()
+ val nullableLeftTime = AttributeReference("leftTime", TimestampType,
+ metadata = watermarkMetadata)()
+ val nullableRightTime = AttributeReference("rightTime", TimestampType,
+ metadata = watermarkMetadata)()
+ val nonNullLeftTime = AttributeReference("leftTime", TimestampType,
nullable = false,
+ metadata = watermarkMetadata)()
+ val nonNullRightTime = AttributeReference("rightTime", TimestampType,
nullable = false,
+ metadata = watermarkMetadata)()
+ val nullableEndWindowType = StructType(Seq(
+ StructField("start", TimestampType, nullable = false),
+ StructField("end", TimestampType, nullable = true)))
+ val nonNullWindowType = StructType(Seq(
+ StructField("start", TimestampType, nullable = false),
+ StructField("end", TimestampType, nullable = false)))
+ val nullableEndWindow = AttributeReference("window", nullableEndWindowType,
+ nullable = false, metadata = watermarkMetadata)()
+ val nullableStructWindow = AttributeReference("window", nonNullWindowType,
+ nullable = true, metadata = watermarkMetadata)()
+ val nonNullWindow = AttributeReference("window", nonNullWindowType,
+ nullable = false, metadata = watermarkMetadata)()
+ val nonNullKeyNullableInput = nonNullLeftTime.withNullability(true)
+ val nullableInputNonNullKey = nullableLeftTime.withNullability(false)
+
+ def compatible(
+ leftAttribute: Attribute,
+ rightAttribute: Attribute,
+ leftKey: Option[Attribute] = None,
+ rightKey: Option[Attribute] = None): Boolean = {
+ StreamingSymmetricHashJoinHelper.isWatermarkCheckpointCompatible(
+ Seq(leftAttribute), Seq(rightAttribute),
+ Seq(leftKey.getOrElse(leftAttribute)),
Seq(rightKey.getOrElse(rightAttribute)), None,
+ consumedSides = Set(LeftSide, RightSide))
+ }
+
+ // Old V4 state indexed a NULL selected key at timestamp 0 under its own
key bytes, so it
+ // never shares a list with a real row. Such a row cannot match, so
evicting it is correct.
+ Seq(nullableLeftTime, nonNullLeftTime).foreach { leftTime =>
+ Seq(nullableRightTime, nonNullRightTime).foreach { rightTime =>
+ assert(compatible(leftTime, rightTime))
+ }
+ }
+ Seq(nullableEndWindow, nullableStructWindow, nonNullWindow).foreach {
window =>
+ assert(compatible(window, nonNullWindow))
+ }
+ assert(compatible(nonNullLeftTime, nonNullRightTime,
+ leftKey = Some(nonNullKeyNullableInput), rightKey =
Some(nonNullRightTime)))
+ assert(compatible(nullableLeftTime, nonNullRightTime,
+ leftKey = Some(nullableInputNonNullKey), rightKey =
Some(nonNullRightTime)))
+ }
+
+ for {
+ version <- Seq(1, 2, 3, 4)
+ logVersion <- Seq(1, 2)
+ // Every marker below the current one takes the same rejection branch.
+ oldMarker <- Seq(None, Some("0"), Some((currentMarker.toInt -
1).toString)).distinct
+ shape <- Seq("range", "expiry", "pruned expiry", "unbounded")
+ } {
+ test(s"reject old $shape checkpoint, V$version log=$logVersion
old=$oldMarker") {
+ withJoinConf(version, logVersion) {
+ val (leftInput, rightInput, joined) = joinInputs(shape)
+ withTempDir { checkpointDir =>
+ val checkpoint = checkpointDir.getCanonicalPath
+ testStream(joined)(
+ StartStream(checkpointLocation = checkpoint),
+ MultiAddData(leftInput, (1, 10))(rightInput, (1, 10)),
+ CheckNewAnswer(if (shape == "unbounded") Row(1, 1, 10L, 10L)
+ else Row(1, 1)),
+ StopStream)
+ // Emulate old offset metadata. State is written by the current
implementation;
+ // rejection must not open or reinterpret it, regardless of its
physical layout.
+ setMarker(checkpoint, oldMarker)
+ val originalBatchId = new OffsetSeqLog(spark, checkpoint +
"/offsets")
+ .getLatest().get._1
+ val stateBefore = snapshot(new File(checkpoint, "state"))
+ val commitsBefore = snapshot(new File(checkpoint, "commits"))
+ for (attempt <- 1 to 2) {
+ // Session defaults must not bypass the checkpoint-pinned marker
or state format.
+ withSQLConf(markerKey -> currentMarker,
+ SQLConf.STREAMING_JOIN_STATE_FORMAT_VERSION.key -> "2") {
+ testStream(joined)(
+ StartStream(checkpointLocation = checkpoint),
+ AddData(rightInput, (2, 20 + attempt)),
+ ExpectFailure[AnalysisException](assertFailure = error => {
+ checkError(error.asInstanceOf[AnalysisException],
+ condition = "STREAMING_JOIN_CHECKPOINT_INCOMPATIBLE",
+ parameters = Map(
+ "joinCondition" -> ".*leftKey.*rightKey.*",
+ "leftWatermarkColumns" ->
+ (if (shape == "expiry" || shape == "unbounded")
"leftTime" else "none"),
+ "rightWatermarkColumns" -> "rightTime"),
+ matchPVals = true)
+ }))
+ }
+ assert(snapshot(new File(checkpoint, "state")) == stateBefore)
+ assert(snapshot(new File(checkpoint, "commits")) == commitsBefore)
+ assert(markerAt(checkpoint, originalBatchId) == oldMarker)
+ }
+ }
+ }
+ }
+ }
+
+ for {
+ version <- Seq(1, 2, 3, 4)
+ logVersion <- Seq(1, 2)
+ shape <- Seq("equality", "no watermark", "range", "expiry", "pruned
expiry")
+ } {
+ test(s"resume compatible $shape checkpoint, V$version log=$logVersion") {
+ withJoinConf(version, logVersion) {
+ val (leftInput, rightInput, joined) = joinInputs(shape)
+ withTempDir { checkpointDir =>
+ val checkpoint = checkpointDir.getCanonicalPath
+ testStream(joined)(
+ StartStream(checkpointLocation = checkpoint),
+ MultiAddData(leftInput, (1, 10))(rightInput, (2, 10)),
+ CheckNewAnswer(),
+ StopStream)
+ assert(pinnedMarker(checkpoint).contains(currentMarker))
+ val oldCompatible = Seq("equality", "no watermark").contains(shape)
+ val expectedMarker = if (oldCompatible) "0" else currentMarker
+ if (oldCompatible) setMarker(checkpoint, None)
+ withSQLConf(markerKey -> "0",
+ SQLConf.STREAMING_JOIN_STATE_FORMAT_VERSION.key -> "2") {
+ testStream(joined)(
+ StartStream(checkpointLocation = checkpoint),
+ AddData(rightInput, (1, 10)),
+ CheckNewAnswer(Row(1, 1)),
+ Execute { query =>
+ val join = query.lastExecution.executedPlan.collect {
+ case j: StreamingSymmetricHashJoinExec => j
+ }.head
+ assert(join.stateFormatVersion == version)
+ },
+ StopStream)
+ }
+ assert(pinnedMarker(checkpoint).contains(expectedMarker))
+ }
+ }
+ }
+ }
+
+ test("resume old V4 aligned checkpoint when own equality key can be null") {
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
[738ebe585c9](https://github.com/apache/spark/pull/60280/commits/738ebe585c98779d084c4c661c1b27a71ecbc8de).
We added a checkpoint that Spark 4.3.0 wrote in state format 4 for the
nullable aligned full outer join. It holds a NULL key at timestamp 0. The new
test resumes it, and the first batch emits the null-padded row. A later batch
does not emit it again. The test fails if we turn off the older-version scan
reset.
<!-- sp2k-review3 reply 4537719976 -->
--
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]