spark-test commented on code in PR #60280: URL: https://github.com/apache/spark/pull/60280#discussion_r4537719892
########## 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: **Nit (P3):** This exception is narrower than the rule the admission check applies. `intervalShift` treats any day-time interval of 24 hours or more as inexact, because `DateTimeUtils.timestampAddDayTime` adds its whole-day part with `plusDays` in the session time zone, and a backward inexact shift gets no bound. So a left outer join on `lk = rk AND lt = rt - INTERVAL 36 HOURS` with watermarks on both inputs fails analysis with "it requires a watermark on the right input and a time constraint", although 36 hours is not a whole number of days and the query has both; `StreamingJoinHelperSuite` expects `eventTime - INTERVAL 36 HOURS` to be unbounded. Meanwhile `timestampadd(HOUR, -36, rightTime)` does count, because it adds hours exactly. The wording follows the previous review's suggestion, which had the same gap. Saying here and in the note below the join support table that a backward day-time interval of 24 hours or more does not count either, and that `timestampadd` in hours, min utes or seconds does, would match the check. This extends an [existing discussion](https://github.com/apache/spark/pull/60280#discussion_r4530212743). **Verification:** - **Inspection:** The rule in both guides matches the admission check for whole-day, 24-hour-or-longer day-time, month and timestampadd shifts in both directions. ########## 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: **Nit (P3):** When `spark.sql.streaming.join.checkFinalization.enabled` is false and `canDisableCheck` holds, this logs the message built for the failing case unchanged. For a left outer join on `lk = rk AND lt = rt` with a watermark only on `lt`, the query runs and logs "Stream-stream LeftOuter join ... is not supported", the downstream note says an append-mode aggregation over the right event time "fails at start" although `checkJoinOutputWatermarkConsumers` only logs with the conf false, and `disableNote`, which is appended exactly when `canDisableCheck` holds, tells the user to set the conf to false to run the query. The useful part, that the input's state is kept without bound and its unmatched rows are never output, gets buried. A separate warning for this branch, saying that the join runs with the check disabled, naming the missing watermark and time constraint, and stating that consequence, while the error for the enabled conf stays as it is, would fix it. This extends an [existing discussion](https://github.com/apache/spark/pull/60280#discussion_r4530212725). **Verification:** - **Behavior:** With the finalization check disabled, the warning logged for a left outer join on lt = rt with a watermark only on lt names the missing right watermark and does not tell the user to disable the check or say that an aggregation fails at start. - **Compatibility:** With the check enabled, the analysis errors for the same joins and for joins that earlier versions rejected keep their current text. ########## 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: **Blocking (P1):** This accepts an equality join on event times only when both inputs' own event times are the watermarked keys at one ordinal, and `isOwnEventTimeIntervalJoin` rejects any key that references an event time, so a forward-shifted key such as `lt = rt + INTERVAL 10 SECONDS`, with watermarks on `lt` and `rt`, fails the restart whatever reads the join's output. The stated reason, that older versions evicted such a key at the unshifted watermark, holds for backward shifts but not for forward ones. Reading the code, the base branch evicted left rows at `lt <= watermark` and right rows at `rt + 10 s <= watermark`; this version evicts left rows at the watermark plus 10 seconds less 1 ms and right rows at the same cutoff as before, `getStateKeyOrdinalForLookup` gives both V4 sides the ordinal the old shared ordinal used, and the left V4 scan still starts after the late watermark. So the old state holds every row this version keeps and lacks only rows that no future right ro w can match. Only the right input's output-watermark bound changes, to the watermark less 10 seconds and 1 ms here and to 0 for a one-day shift, which matters only when a later stateful operator reads `rt`. `StreamingJoinCheckpointCompatibilitySuite` pins the rejection for `leftTime = rightTime + INTERVAL 1 SECOND`. **Recommended change:** In the stream-stream join checkpoint compatibility check, also accept an equality join whose inputs each have exactly one event-time column when, at one key ordinal, one input's key is its own event time and the other input's key is its own event time shifted forward (any constant shift with non-negative amounts that the existing shift classification marks as forward, exact or by whole days, months or years, including foldable-interval and timestampadd forms), no other equality key uses an event time, and no stateful operator after the join reads the shifted input's event time. Expose from StreamingJoinHelper a check that a key is a forward shift of the input's event time, built on the existing shift classification, so the restart check and eviction classify shifts the same way. Update the docstring that gives 'evicted at the unshifted watermark' as the reason to name backward shifts and consumed shifted inputs, the migration guide's restart paragraph, and the compatibility test that today expects 'interval with a shifted event-time key' to be rejected. The rejection rule comes from SPARK-61344's restart check; this PR's 963f9bb3a4b changed shifted-key eviction and restated the reason. **Why this works:** For a forward shift the base branch evicted the unshifted side at key <= watermark, at or below the new cutoff, and the shifted side at the same key cutoff as now, so old state holds every row the new eviction keeps and lacks only rows no future row can match; both V4 sides were stored at the shared ordinal that getStateKeyOrdinalForLookup still returns; the first batch after the restore scans V4 state from the start; and requiring the shifted input to be unread downstream keeps its changed output-watermark bound unobserved. **Scope:** Add one accepted shape, forward-shifted equality keys whose shifted input nothing downstream reads, to the restart compatibility check, sharing the shift classification with eviction. **Risks:** Accepting a shape whose old state is not a superset of what the new eviction keeps would drop matches or misread V4 state after the restart, so the branch must stay limited to one own event-time key paired with a forward shift of the other input's event time at the same ordinal. **Constraints:** Keep rejecting backward shifts, keys shifted on both inputs, one-watermark shapes, and shifted inputs that a later stateful operator reads, whose base-branch output watermark was too high. **Exclusions:** - Accepting shifted keys whose shifted input a later stateful operator reads, because the base branch advanced that input's output watermark past rows the join could still emit. - A forward shift onto an input without a watermark, such as lt = rt + INTERVAL 10 SECONDS with a watermark only on rt: V4 now stores that input's rows at the key instead of the random buckets older versions used, and accepting only its V1 to V3 checkpoints would need the state format, which the restart check no longer reads. **Success:** A checkpoint without the watermark-semantics marker of lk = rk AND lt = rt + INTERVAL 10 SECONDS, inner or left outer, with watermarks on both inputs and no stateful operator after the join, restarts and then produces the same rows as an uninterrupted run, in state formats V1 to V4. The same join with lt = rt + INTERVAL 1 DAY, and with the shift on the left key, restarts. Backward shifts, keys shifted on both inputs and shifted inputs read by a later stateful operator are still rejected before state is opened. **Verification:** - **Regression:** Restarting an older checkpoint of an equality join whose key is the other input's event time shifted forward by an exact sub-day interval, by whole days, months or years, or by a timestampadd or foldable interval expression, with both inputs watermarked and nothing stateful after the join, resumes and produces the rows of an uninterrupted run in V1 to V4, including V4 rows stored before the restart that later rows must match. - **Compatibility:** Older checkpoints of backward-shifted keys, of keys shifted on both inputs, and of forward-shifted keys whose shifted event time a later stateful operator reads are still rejected with STREAMING_JOIN_CHECKPOINT_INCOMPATIBLE and leave the state and commit files unchanged. ########## 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: **Nit (P3):** These tests, and the left outer and left semi runs in `StreamingJoinWatermarkAdmissionSuite`, all pass through the watermarked-key arm of `admittedBeforeFinalizationCheck`, because `leftTime === rightTime` has a watermarked key. The range-bound arm, which keeps runnable the joins that earlier versions admitted only through a range bound, never decides a test, and no right outer or full outer join runs with the conf false. Swapping the right outer arguments of `hasRangeBound`, requiring both directions for full outer joins, or returning false from that arm would leave every test green. Two analyzer cases would pin it: a full outer join on `lk = rk AND lt > rt - INTERVAL 5 SECONDS` with both inputs watermarked, which fails by default with an error that names the conf and runs with a warning when the conf is false, and a right outer join whose range bounds only the left input, which still fails with the conf false and whose error does not name it. This extends an [existing discussion](https://github.com/apache/spark/pull/60280#discussion_r4530212725). **Verification:** - **Regression:** Swapping the inputs of the right outer range check, or requiring both directions for full outer joins, in the earlier-versions floor makes a test fail. - **Behavior:** With the finalization check disabled, a full outer join bounded only in one direction by a range condition on two watermarked inputs passes analysis with a warning, and a right outer join whose range bounds only the left input still fails without suggesting the conf. ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala: ########## @@ -35,18 +35,253 @@ 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 or leftTime = timestampadd(HOUR, 1, rightTime), + * 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 => Review Comment: **Blocking (P1):** Only the input's first watermarked column counts as its event-time key here, and `shiftOfKey` gives a struct key, or a copy of that column, no bound. In legacy mode an input can keep its event time `t` and a window over it, both watermarked, because `TimeWindowResolution` copies `t`'s metadata onto the window, and `withColumn("w", window($"t", "10 seconds"))` leaves `t` first. For a left outer join on `lk = rk AND lw = rw` over two such inputs, the base branch admitted the join through `isWatermarkInJoinKeys` and evicted both sides at `w.end <= watermark`, which drops nothing that can still match: legacy mode filters late rows on `t` at the same batch watermark, and every window ends after its `t`. At this head `canEvictState` is false for both sides, so the join fails analysis by default, while the inner form gets no eviction predicate and, with the start-time check skipped in legacy mode, runs without any warning. The harm the migration guide names, a window o ver a different column, does arise through a union, whose columns take the first input's metadata, so a later input can place a window over another column at that position; that case should stay unbounded. The PR description defers restoring the bound to SPARK-61448, but these joins work correctly on the base branch, so they would stay broken until then. **Recommended change:** For an input with more than one watermarked column, which only legacy mode runs, let an equality key bound the other input's state at the watermark, as earlier versions did, when the input plan shows that the key is a copy of the input's late-filtered column, its first watermarked column, or a time window built directly from that column. Decide this from the plan rather than from the column metadata: follow the key and the late-filtered column down through projections and Expand, and to the same position in every input of a union, and accept the key only when every path builds it from the same column that the late filter compares there. Have getStateKeyWatermarkOrdinal and getStateKeyWatermark take the accepted key ordinals; the admission check computes them on the logical join, and the planner records them on StreamingSymmetricHashJoinExec, whose callers of getStateWatermarkPredicates pass them. Keep rejecting a plain event-time key or a shorter window whe n a window comes first, and a window that some union input builds from another column. Revise the legacy-mode migration-guide paragraph and the admission hint that 9c618562e01 added, and change the legacy-mode tests in UnsupportedOperationsSuite and StreamingJoinWatermarkAdmissionSuite, which assert the rejection that 963f9bb3a4b introduced with the first-watermarked-column rule, to expect windows after their event time to bound state. **Why this works:** The late filter keeps only rows whose late-filtered column is above the watermark. A copy of that column equals it, and a time window built directly from it ends after it, so on every row such a key is above the watermark too, the bound the base branch used. A union takes its columns' metadata from its first input, so a later input can place a window over another column at the position of the first input's watermarked window; checking how every input builds the key, instead of reading its metadata, keeps that window unbounded, as the PR intends. **Scope:** Restore, for legacy-mode inputs that keep their event time before a copy of it or a time window over it, the bound such a key gave the other input's state, deciding from the input plan which keys qualify. **Risks:** A path the plan check does not recognize leaves the key unbounded, as at head today, so a legacy window join built through such a node keeps failing analysis or keeping state; the check must at least follow the projections, Expand and unions that window() and withColumn produce. getEventTimeWatermarkFromKey still gives such a key no event-time bound, so the join's output watermark for that input stays held; legacy mode uses one global watermark, so no operator reads it. **Constraints:** Apply the rule only to inputs with more than one watermarked column, leaving the default mode and the V4 path unchanged. Pass the same accepted key ordinals to every caller that evaluates the join's state predicates, so admission, eviction and the output-watermark helper agree. **Exclusions:** - Bounding a plain event-time key or a shorter window when a window comes first, which the late filter does not bound and which stays rejected, as the PR intends. - Restarting older legacy-mode checkpoints whose inputs keep two watermarked columns: the restart check that SPARK-61344 added rejects them whatever this repair does, and that rule is outside this pull request's own commits. **Success:** With allowMultiple=false, left outer, right outer, full outer and left semi joins on lk = rk AND lw = rw, where each input keeps t before window(t), pass analysis, evict both sides at window end <= watermark, and emit unmatched rows as on the base branch. The inner form of that join evicts state in V1 to V3, and so does a join whose key is a copy of the late-filtered column placed after it. A legacy-mode join whose key is the plain event time while a window over it comes first, or whose window some union input builds from another column, still gets no bound. **Verification:** - **Regression:** With allowMultiple=false and each input keeping its event time before a window over it, or before a copy of it, an outer join on those keys passes analysis, keeps state bounded, and emits each unmatched row once the watermark passes its key, in state formats V1 to V3, also when the input is a union whose every branch builds the key from its own late-filtered column. - **Behavior:** A legacy-mode join whose window key a union input builds from another column, and one keyed on the plain event time with the window first, still get no bound, and their outer forms still fail analysis with the window hint. - **Compatibility:** In the default mode an input that keeps both its event time and a window over it still fails with MULTIPLE_EVENT_TIME_COLUMNS, and every other admission and eviction decision is unchanged. ########## 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: **Nit (P3):** This test emulates the old checkpoint with the current version, which emits NULL-key rows on arrival and never stores them; its own comment says the emulated checkpoint holds no NULL-key row. The restart variant therefore only has to match an uninterrupted run that has no such row either, and "V4 scan start in the first batch after a restart" checks only that `prevStateWatermark` is None. Accepting nullable old V4 checkpoints rests on the first-batch full scan evicting a row that Spark 4.3, which ships V4, stored at timestamp 0 with a NULL `lt`, and emitting it null-padded on the preserved side; if that scan or the V4 timestamp lookup regressed, the row would stay in state forever and no test would fail. A small V4 checkpoint written by Spark 4.3 that holds such a row, bundled next to the existing 2.4.0 and 3.5.1 streaming-join fixtures, with a restart test that expects the null-padded row in the first batch, would close the gap. This extends an [existing discussion](https://github.com/apache/spark/pull/60280#discussion_r4523185814). **Verification:** - **Regression:** Restoring a V4 checkpoint written before this change that holds a left row with a NULL event-time key in a left outer join emits that row null-padded in the first batch after the restart and removes it from state, and later rows produce the same output as an uninterrupted run. ########## common/utils/src/main/resources/error/error-conditions.json: ########## @@ -8165,6 +8165,20 @@ ], "sqlState" : "55019" }, + "STREAMING_JOIN_CHECKPOINT_INCOMPATIBLE" : { + "message" : [ + "Cannot reuse the checkpoint for the stream-stream join with condition <joinCondition>. Watermarked columns: left [<leftWatermarkColumns>], right [<rightWatermarkColumns>].", + "This Spark version changes how watermarks determine which rows can still match. Spark cannot verify that rows saved by the previous version can be reused safely for this join. Start the query with a new checkpoint and replay the required input, accounting for previously written results to avoid duplicates and correct any missing or incorrect output." + ], + "sqlState" : "0A000" + }, + "STREAMING_JOIN_UNBOUNDED_DOWNSTREAM_EVENT_TIME" : { + "message" : [ + "The append-mode aggregation after a stream-stream join uses the event time <eventTime> of the join's <side> input, but the join cannot bound the state of that input, so it holds back its output watermark and the aggregation would never emit results.", Review Comment: **Nit (P3):** `holdsOutputWatermark` treats an input as unbounded whenever `getStateWatermark` returns 0 for it, and that also happens for inputs the join does evict when the eviction predicate does not bound their event time. Take a left outer join on `lk = rk AND lt = rt + INTERVAL 1 DAY` with watermarks on both inputs, followed by an append-mode aggregation over `window(rt, "10 minutes")`: right rows are evicted at `rt + 1 day <= watermark`, but `getEventTimeWatermarkFromKey` accepts only exact shifts, so the query fails at start saying that the join cannot bound the right input's state and asking for a time constraint that limits how late a matching left row can arrive, which the equality already is. Adding a range condition does not help, because key eviction takes precedence. The Left Outer and Right Outer rows of the join support table and the migration guide also say that such a key lets a later stateful operator make progress. Describing this as a missing bound on the inp ut's event time, and naming what provides one, an equality with an exact shift (an interval under a day or a `timestampadd` in hours, minutes or seconds) or a range condition in place of a shifted equality, would make the error and the guides match the check. **Verification:** - **Regression:** Append-mode aggregations over the event time of an input the join evicts through a whole-day-shifted key or through a cutoff on another timestamp column fail at start with a message that does not claim the input's state is unbounded and whose requirement is not already present in the query. - **Inspection:** The join support table, the note below it and the migration guide state that an equality key shifted by whole days, months or years bounds state but not the event time a later stateful operator sees. -- 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]
