spark-test commented on code in PR #60280:
URL: https://github.com/apache/spark/pull/60280#discussion_r4530213150
##########
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:
Thanks, closing both shapes in #60282 and #60283 makes sense. Since each PR
in the stack lands on master as its own commit, master will admit these two
shapes without finalizing them until those PRs merge, while the new admission
error says that an admitted join's watermarks and time constraints allow
unmatched state to be finalized. A short TODO here and at the stored-side
watermark branch of the eviction predicates, naming SPARK-61347 and SPARK-61348
and removed by those PRs, would keep that visible to anyone reading the code in
between.
<!-- SPARK_DEV_REVIEW_REPLY
{"feedback_id":"inline:4523185786","thread_id":"inline:4523185786","verdict_sha256":"9e7f6ee0d5875f247ef1cb628e86f2e04750d861d691756eceb6345cc5688f86"}
-->
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -35,22 +33,178 @@ import org.apache.spark.unsafe.types.CalendarInterval
object StreamingJoinHelper extends PredicateHelper with Logging {
/**
- * Check the provided logical plan to see if its join keys contain a
watermark attribute.
- *
- * Will return false if the plan is not an equijoin.
- * @param plan the logical plan to check
+ * Find the equality key filtered by this input's watermark. Its ordinal can
be used to
+ * evict the opposite input's state, whose equality keys have the same
ordering.
+ * For leftTime = rightTime, a watermark on rightTime bounds leftTime even
when leftTime
+ * has no watermark. It does not bound right-side state without a watermark
on leftTime.
+ * A key computed from the event time by adding constant intervals, such as
+ * leftTime = rightTime + INTERVAL 10 SECONDS, is bounded too if the solver
can count the
+ * intervals exactly or they never move a time backward; see
[[getStateKeyWatermark]]. The
+ * result does not depend on the session time zone, so neither does the V4
state layout.
+ */
+ def getStateKeyWatermarkOrdinal(
+ keys: Seq[Expression],
+ inputAttributes: Seq[Attribute]): Option[Int] = {
+ getEventTimeKeyOrdinal(keys, inputAttributes).orElse {
+ keys.indices.find(getStateKeyWatermark(keys, inputAttributes, _,
Some(0L)).isDefined)
+ }
+ }
+
+ /** Find the equality key that is this input's event-time column itself. */
+ def getEventTimeKeyOrdinal(
+ keys: Seq[Expression],
+ inputAttributes: Seq[Attribute]): Option[Int] = {
+ // When multiple stateful operators are disabled, late filtering uses the
first event-time
+ // column. Otherwise, execution rejects multiple distinct event-time
columns.
+ inputAttributes.find(_.metadata.contains(delayKey)).flatMap { eventTime =>
+ keys.indexWhere(_.semanticEquals(eventTime)) match {
+ case ordinal if ordinal >= 0 => Some(ordinal)
+ case _ => None
+ }
+ }
+ }
+
+ /**
+ * Get the cutoff for the opposite input's equality key at `ordinal`, given
this input's
+ * watermark. `keys` and `inputAttributes` belong to this input, whose
future rows have an event
+ * time above the watermark. When the key is that event time, the equal key
of any state row
+ * they can still match is above the watermark too. When the key is the
event time shifted by
+ * exact intervals, solving `stateKey >= rightTime + INTERVAL 10 SECONDS`
shifts the cutoff by
+ * that interval, less 1 ms as for range conditions. When the shift has
whole days, months or
+ * years but never moves a time backward, the cutoff is the watermark
itself. Returns None for
+ * any other key, including a shift with whole days, months or years that
can move a time
+ * backward.
+ */
+ def getStateKeyWatermark(
+ keys: Seq[Expression],
+ inputAttributes: Seq[Attribute],
+ ordinal: Int,
+ eventWatermark: Option[Long]): Option[Long] = {
+ if (getEventTimeKeyOrdinal(keys, inputAttributes).contains(ordinal)) {
+ eventWatermark
+ } else {
+ shiftOfKey(keys(ordinal), inputAttributes).flatMap {
+ case KeyShift(eventTime, true, _) =>
+ val stateKey = AttributeReference("stateKey", TimestampType)()
+ getStateValueWatermark(AttributeSet(Seq(stateKey)),
AttributeSet(Seq(eventTime)),
Review Comment:
**Blocking (P1):** `intervalShift` evaluates any foldable interval, so `rt +
INTERVAL 1 HOUR * 2` or `rt + make_dt_interval(0, 2, 0, 0)` is classified as an
exact forward shift. This branch then hands the key to
`getStateValueWatermark`, but `collectTerms` reads only interval literals: a
`MultiplyDTInterval`, `MakeDTInterval` or interval-cast term marks the
condition invalid, the solver returns no bound, and nothing falls back to the
unshifted watermark. The admission check runs in `ResolveWriteToStream` on the
analyzed plan, before `ConstantFolding`.
Reading the code, a left outer join on `lk = rk AND lt = rt + INTERVAL 1
HOUR * 2` with watermarks on both inputs therefore fails analysis with 'it
requires a watermark on the right input and a time constraint', although it has
both. The base branch admitted this join because the watermarked `lt` is an
equality key, and its eviction is correct for a forward shift. Execution here
would also bound the left state, at the watermark plus 2 hours, once the
interval is folded. Full outer and left semi joins of this shape are rejected
the same way, as are backward shifts written like this. No test uses a
non-literal interval.
Replacing each foldable interval operand with a literal of the value
`intervalShift` already computes, before calling the solver, would make
admission derive the same cutoff as execution.
**Verification:**
- **Regression:** A left outer join on lk = rk AND lt = rt + INTERVAL 1 HOUR
* 2 with watermarks on both inputs passes analysis, and so do a full outer join
and a left semi join of the same shape.
- **Behavior:** A key shifted by make_dt_interval(0, 2, 0, 0) gets the same
cutoff at analysis as the same key shifted by the literal INTERVAL 2 HOURS.
- **Compatibility:** Keys shifted backward by whole days or months,
truncated keys, and keys built from an unwatermarked column are still rejected.
##########
docs/streaming/ss-migration-guide.md:
##########
@@ -25,6 +25,60 @@ 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.
Review Comment:
**Nit (P3):** This entry, and the Left Outer and Left Semi rows of the join
support table, say the requirement is a watermark on the other input and a time
condition that limits how late a matching row can arrive. The checker accepts
less than that. An equality key that is the other input's event time shifted
backward by whole days, months or years, such as `lt = rt - INTERVAL 1 DAY`,
gets no bound, and neither does a truncated key such as `lt = CAST(CAST(rt AS
BIGINT) AS TIMESTAMP)`. A left outer join on either one fails analysis even
with watermarks on both inputs, although each equality limits how late a match
can arrive. Users who hit that error are asked for a watermark and a time
constraint they already have, and these documents never say that such an
equality does not count. Naming these keys here and in the support table would
close the gap, along with a note that a time range condition on the two event
times can bound such a join instead when both inputs have watermarks.
**Verification:**
- **Inspection:** The migration guide's outer and semi join entry and the
join support documentation state that an equality key shifted backward by whole
days, months or years, or truncated from the other input's event time, does not
count as the required time constraint.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -224,98 +228,218 @@ 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 an exact
constant in the opposite
+ // key. See StreamingJoinHelper.getStateKeyWatermark for the shifts it
accepts.
+ 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)
+ 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
+ }
+
+ /**
+ * 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. 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 two-sided time-interval join on the event
times (see
+ * [[isOwnEventTimeIntervalJoin]]). This excludes other 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. A NULL selected
key does not matter:
+ * old V4 state indexed it at timestamp 0 under its own key, and evicting
that row, which can
+ * never match, emits its correct outer row.
+ */
+ private[sql] def isWatermarkCheckpointCompatible(
+ leftAttributes: Seq[Attribute],
+ rightAttributes: Seq[Attribute],
leftKeys: Seq[Expression],
- rightKeys: Seq[Expression]): Option[Int] = {
- // Join keys of both sides generate rows of the same fields, that is, same
sequence of data
- // types. If one side (say left side) has a column (say timestamp) that
has a watermark on it,
- // then it will never consider joining keys that are < state key watermark
(i.e. event time
- // watermark). On the other side (i.e. right side), even if there is no
watermark defined,
- // there has to be an equivalent column (i.e., timestamp). And any right
side data that has the
- // timestamp < watermark will not match will not match with left side
data, as the left side get
- // filtered with the explicitly defined watermark. So, the watermark in
timestamp column in
- // left side keys effectively causes the timestamp on the right side to
have a watermark.
- // We will use the ordinal of the left timestamp in the left keys to find
the corresponding
- // right timestamp in the right keys.
- leftKeys.zipWithIndex.collectFirst {
- case (ne: NamedExpression, index) if ne.metadata.contains(delayKey) =>
index
- } orElse {
- rightKeys.zipWithIndex.collectFirst {
- case (ne: NamedExpression, index) if ne.metadata.contains(delayKey) =>
index
+ rightKeys: Seq[Expression],
+ condition: Option[Expression]): 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
}
}
+
+ 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
+ alignedOwnEventTimeKeys || isOwnEventTimeIntervalJoin(leftAttributes,
rightAttributes,
+ leftKeys, rightKeys, condition, leftEventTime.head,
rightEventTime.head)
+ } else {
+ false
+ }
+ }
+
+ /**
+ * Whether every ordering conjunct compares the two inputs' event times,
each shifted only by
+ * exact constant intervals, and both event times get a range bound. Older
versions solved
+ * every column of an input but then found bounds only in the same
conjuncts, so they derived
+ * the same value predicates, scan starts, V4 index columns and output
watermark. Old V4 stored
+ * a null event time at timestamp 0 under the row's own key; both versions
scan that entry the
+ * same way. No equality key may use an event time: older versions evicted
such keys at the
+ * unshifted watermark.
+ */
+ private def isOwnEventTimeIntervalJoin(
+ leftAttributes: Seq[Attribute],
+ rightAttributes: Seq[Attribute],
+ leftKeys: Seq[Expression],
+ rightKeys: Seq[Expression],
+ condition: Option[Expression],
+ leftEventTime: Attribute,
+ rightEventTime: Attribute): Boolean = {
+ def conjuncts(e: Expression): Seq[Expression] = e match {
+ case And(left, right) => conjuncts(left) ++ conjuncts(right)
+ case other => Seq(other)
+ }
+ def eventTimeOf(e: Expression): Option[Attribute] =
+ Seq(leftEventTime,
rightEventTime).find(StreamingJoinHelper.isExactIntervalShift(e, _))
Review Comment:
**Blocking (P1):** This PR's review-round commit switched this operand test
from `isIntervalShift` to `isExactIntervalShift`, which treats every interval
of a day or more as inexact. SPARK-61344's version accepted whole days in
fixed-offset zones. Restarting a Spark 4.3 checkpoint of `leftKey = rightKey
AND rightTime >= leftTime AND rightTime <= leftTime + INTERVAL 1 DAY` (or
`INTERVAL 24 HOURS`), with both event times watermarked, now fails with
`STREAMING_JOIN_CHECKPOINT_INCOMPATIBLE` in UTC as well, and the flipped UTC
case in `StreamingJoinCheckpointCompatibilitySuite` pins that.
The rejection protects nothing. Exactness matters only to the equality-key
shift helpers. For these range-only joins, `collectTerms` counts a day as 24
hours in every zone, on the base branch and here alike. Both versions derive
the same left cutoff (the right watermark less 86400000 ms less 1 ms), the same
right cutoff (the left watermark less 1 ms), the same scan starts and the same
V4 index columns. Owners of such queries, a common way to write interval joins,
would still have to start a new checkpoint and replay at least a day of input,
losing buffered join state when the source no longer retains it.
Accepting any constant-interval shift as a range operand, in every zone
because the old and new rules agree in daylight saving zones too, while keeping
the `boundsEventTime` check, would let these checkpoints resume. Month
intervals, which the solver cannot bound, would still be rejected.
**Verification:**
- **Regression:** Restarting an older checkpoint without the
watermark-semantics marker of leftKey = rightKey AND rightTime >= leftTime AND
rightTime <= leftTime + INTERVAL 1 DAY, with both event times watermarked,
resumes in UTC and in America/Los_Angeles and produces the same rows as an
uninterrupted run.
- **Compatibility:** Older checkpoints of interval joins with a month
interval, a bound on another column, or a one-directional bound are still
rejected with STREAMING_JOIN_CHECKPOINT_INCOMPATIBLE before state is opened.
- **Compatibility:** Older checkpoints with a shifted event-time equality
key are still rejected, and those with aligned own event-time keys or exact
intervals still resume.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -706,32 +707,65 @@ 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,
+ AttributeSet(eventTime.toSeq), join.condition,
Some(1000000)).isDefined
+ }
+
+ 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 and that
operator stops " +
+ "emitting results."
+ }.getOrElse("")
+ val checkConf = SQLConf.STREAMING_JOIN_CHECK_FINALIZATION_ENABLED.key
+ 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." +
+ downstreamNote +
+ 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."
+ if (SQLConf.get.streamingJoinCheckFinalizationEnabled) {
Review Comment:
**Non-blocking (P2):** When
`spark.sql.streaming.join.checkFinalization.enabled` is false, this branch only
logs a warning for every outer or left semi join that fails the directional
check. That includes joins the base branch rejected outright: those with no
watermarked attribute among the equality keys and no range bound for a
preserved side. A left outer join on `lk = rk` with no watermark on either
input fails analysis on the base branch. Here it runs, never evicts either
side's state and never outputs an unmatched left row.
The PR description says the conf turns the new outer and semi admission
failures into warnings, and when the sibling
`spark.sql.streaming.statefulOperator.checkCorrectness.enabled` is false it
skips only its own check. As written, a session that disables this check to
keep a previously admitted join running also stops rejecting joins that were
never supported. Keeping the base branch's admission rule as the floor when the
conf is false would close that gap. The error's suggestion to set the conf
would then belong only on joins the conf can actually run.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60280#issuecomment-6775625413).
**Verification:**
- **Regression:** With spark.sql.streaming.join.checkFinalization.enabled
set to false, a left outer stream-stream join on lk = rk with no watermark on
either input fails analysis, as on the base branch.
- **Behavior:** With the conf set to false, a left outer or left semi join
on lt = rt with a watermark only on lt logs the warning and runs.
- **Behavior:** The admission error for a left outer join with no watermark
on either input does not suggest setting the conf, and the error for a left
outer join on lt = rt with a watermark only on lt still does.
- **Compatibility:** With the conf at its default, every admission decision
is unchanged.
##########
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:
Thanks for confirming. Because #60307 is a separate PR against master and
not part of this stack, this PR on its own still loses these rows: with `lt +
INTERVAL 10 SECONDS = rt`, the right cutoff is now the eviction watermark plus
10 seconds, so in every batch that advances the watermark the left semi store
skip drops right rows that the same batch's left rows can still match, where
before that needed the watermark to advance by more than the shift. Could this
PR land after #60307, or carry its change that a left semi join keeps every
right row until the end-of-batch eviction, together with a left semi test for a
shifted key whose pair arrives in one batch?
<!-- SPARK_DEV_REVIEW_REPLY
{"feedback_id":"inline:4523185797","thread_id":"inline:4523185797","verdict_sha256":"9e7f6ee0d5875f247ef1cb628e86f2e04750d861d691756eceb6345cc5688f86"}
-->
--
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]