spark-test commented on code in PR #60280: URL: https://github.com/apache/spark/pull/60280#discussion_r4587582037
########## docs/streaming/ss-migration-guide.md: ########## @@ -25,6 +25,136 @@ 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 with + months, years, or a day-time interval of 24 hours or more that can move a time backward. To + decide this without the session time zone, Spark counts each such day as at least 12 hours and Review Comment: **Nit (P3):** This rule gives only the shortest length of a day and of a month. The code (`Shift.days`, `Shift.months` and `negate` in `StreamingJoinHelper`) counts a day as 12 to 36 hours and a month as 28 to 31 such days, takes the longest length for a subtracted term, and counts a key only when the resulting smallest total is not negative. So `rightTime + INTERVAL 1 MONTH - INTERVAL 15 DAYS`, which a reader of this sentence would count as at least 336 - 180 = 156 hours forward, gets no bound (336 - 540 = -204 hours), and a reader would count `rightTime + INTERVAL 5 DAYS - INTERVAL 2 DAYS` as at least 36 hours forward, while the code counts it as possibly 12 hours backward (60 - 72 hours) and gives it no bound either. The note under the join support table in `apis-on-dataframes-and-datasets.md` states the same incomplete rule. This extends an [existing discussion](https://github.com/apache/spark/pull/60280#discussion_r4579272779). **Verification:** - **Inspection:** Every statement of the day and month counting rule in the migration guide and the join guide gives both the smallest and the largest length and says that a subtracted term counts at its largest. ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala: ########## @@ -17,36 +17,659 @@ package org.apache.spark.sql.catalyst.analysis +import java.util.Locale + +import scala.util.Try import scala.util.control.NonFatal import org.apache.spark.internal.Logging import org.apache.spark.internal.LogKeys._ +import org.apache.spark.sql.catalyst.InternalRow import org.apache.spark.sql.catalyst.expressions._ -import org.apache.spark.sql.catalyst.planning.ExtractEquiJoinKeys -import org.apache.spark.sql.catalyst.plans.logical.{EventTimeWatermark, LogicalPlan} +import org.apache.spark.sql.catalyst.plans.logical.{Expand, Join, LogicalPlan, Project, UnaryNode, Union} import org.apache.spark.sql.catalyst.plans.logical.EventTimeWatermark._ -import org.apache.spark.sql.catalyst.util.DateTimeConstants.MICROS_PER_DAY +import org.apache.spark.sql.catalyst.util.DateTimeConstants.{MICROS_PER_DAY, MICROS_PER_HOUR, MICROS_PER_MILLIS, MICROS_PER_MINUTE, MICROS_PER_SECOND} import org.apache.spark.sql.types._ import org.apache.spark.unsafe.types.CalendarInterval +/** + * How far below a column that can filter its stream-stream join input's late rows one of the + * input's watermarked columns can be, for an equality key or a range condition on it: at most + * `micros` where the plan relates the two columns; by an amount that the plan does not bound when + * `unbounded`; and by an amount that it does not show when `unrelated`, because it does not relate + * the two. A window column is compared by its end, as eviction and late filtering compare it. + */ +case class EventTimeLag(micros: Long, unrelated: Boolean, unbounded: Boolean) { + def max(other: EventTimeLag): EventTimeLag = EventTimeLag(math.max(micros, other.micros), + unrelated || other.unrelated, unbounded || other.unbounded) + + /** + * The cutoff for the other input's equality key when this input's watermark is `watermark`. + * A key that the plan does not relate keeps the Spark 4.3 cutoff. + */ + def keyWatermark(watermark: Long): Option[Long] = + if (unbounded) None else Some(watermark - EventTimeLag.ceilMillis(micros)) + + /** + * The watermark to substitute for the column in a range condition. Spark 4.3 substituted the + * watermark for every watermarked column; this does so only where the plan bounds the lag. + */ + def rangeWatermark(watermark: Long): Option[Long] = + if (unbounded || unrelated) None else Some(watermark - EventTimeLag.ceilMillis(micros)) +} + +object EventTimeLag { + val zero: EventTimeLag = EventTimeLag(0L, unrelated = false, unbounded = false) + val unrelated: EventTimeLag = EventTimeLag(0L, unrelated = true, unbounded = false) + val unbounded: EventTimeLag = EventTimeLag(0L, unrelated = false, unbounded = true) + + private def ceilMillis(micros: Long): Long = + micros / MICROS_PER_MILLIS + (if (micros % MICROS_PER_MILLIS == 0) 0 else 1) +} + +/** + * The [[EventTimeLag]] of the watermarked columns of stream-stream join inputs, by expression ID; + * see [[StreamingJoinHelper.findEventTimeLags]]. A column missing from `lags` has lag zero, so + * `EventTimeLags(Map.empty)` gives every watermarked column lag zero. That is right when multiple + * stateful operators are allowed: execution then fails at start for a planned input with two + * distinct watermarked columns, so the only one left filters late rows itself. + */ +case class EventTimeLags(lags: Map[ExprId, EventTimeLag]) { + /** + * The lag of `column` in a join input with output `inputAttributes`, if it carries a watermark. + * The input's first watermarked column filters its late rows itself. + */ + def lagOf(column: NamedExpression, inputAttributes: Seq[Attribute]): Option[EventTimeLag] = + if (!column.metadata.contains(delayKey)) { + None + } else if (inputAttributes.find(_.metadata.contains(delayKey)) + .exists(_.exprId == column.exprId)) { + Some(EventTimeLag.zero) + } else { + Some(lags.getOrElse(column.exprId, EventTimeLag.zero)) + } +} + +object EventTimeLags { + val none: EventTimeLags = EventTimeLags(Map.empty) +} + /** * Helper object for stream joins. See [[StreamingSymmetricHashJoinExec]] in SQL for more details. */ 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. Without `lags`, only the input's first watermarked + * column counts as its event time; with them, every watermarked column that they bound does. + */ + def getStateKeyWatermarkOrdinal( + keys: Seq[Expression], + inputAttributes: Seq[Attribute], + lags: Option[EventTimeLags] = None): Option[Int] = { + getEventTimeKeyOrdinal(keys, inputAttributes, lags).orElse { + keys.indices.find(getStateKeyWatermark(keys, inputAttributes, _, Some(0L), lags).isDefined) + } + } + + /** + * Find the equality key that is this input's first watermarked column, or else, with `lags`, + * the watermarked key with the smallest lag that bounds it; see [[findEventTimeLags]]. + */ + def getEventTimeKeyOrdinal( + keys: Seq[Expression], + inputAttributes: Seq[Attribute], + lags: Option[EventTimeLags] = None): 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 => + Some(keys.indexWhere(_.semanticEquals(eventTime))).filter(_ >= 0).orElse { + lags.flatMap { l => + keys.indices.flatMap { i => + keyLag(keys(i), inputAttributes, l).filterNot(_.unbounded).map(i -> _.micros) + }.sortBy(_._2).headOption.map(_._1) + } + } + } + } + + /** The lag of a key that is a watermarked column of the input. */ + private def keyLag( + key: Expression, + inputAttributes: Seq[Attribute], + lags: EventTimeLags): Option[EventTimeLag] = key match { + case n: NamedExpression => lags.lagOf(n, inputAttributes) + case _ => None + } + + /** + * The lag of every watermarked column of each stream-stream join input in `plan`, combined + * over the inputs by [[EventTimeLag.max]]. This is for + * spark.sql.streaming.statefulOperator.allowMultiple=false, where an input can keep several + * watermarked columns, such as its event time and a copy of it or a time window over it, and + * filters late rows by the first of them. When `planned`, `plan` is the optimized plan that runs, + * so each input filters late rows by its first watermarked column, and a column's lag is taken + * against that one. Otherwise the optimizer can prune any watermarked column before a column, so + * its lag is the largest against all of them. Spark 4.3 bounded state by every watermarked + * column at the watermark. A lag lowers that cutoff; see [[EventTimeLag]]. + */ + def findEventTimeLags(plan: LogicalPlan, planned: Boolean): EventTimeLags = { + val lags = plan.collect { + case j: Join if j.left.isStreaming && j.right.isStreaming => Seq(j.left, j.right) + }.flatten.flatMap { input => + val watermarked = input.output.filter(_.metadata.contains(delayKey)).map(_.exprId).distinct + watermarked.indices.map { i => + val lateFiltered = if (planned) watermarked.take(1) else watermarked.take(i) + watermarked(i) -> lateFiltered.filter(_ != watermarked(i)).map { eventTime => + lagBelow(input, watermarked(i), eventTime, Some(0L), Some(0L)) + }.foldLeft(EventTimeLag.zero)(_ max _) + } + } + EventTimeLags(lags.groupMapReduce(_._1)(_._2)(_ max _)) + } + + /** How a column relates to the column of a node's child that [[lagBelow]] follows for it. */ + private case class Step(column: ExprId, offset: Option[Long]) + + /** + * How far `key` of `plan` can be below its column `eventTime`, which late filtering compares + * with the watermark. Both are compared by their bounds: a time, or a window's end. `keyLow` is + * the smallest that the join input's key is above `key`, and `eventTimeHigh` the largest that the + * join input's late-filtered column is above `eventTime`; None means without bound. The walk + * follows both columns down by expression ID: through a projection or an expansion that passes + * them on, builds a time or session window from a single column, or, for the key, shifts a + * timestamp by constant intervals; through any other node with one input that outputs both, as + * such a node keeps an expression ID only for an unchanged value; into the input of a join that + * outputs both; and into every input of a union, at the same positions. A union input that does + * not watermark a column that the union, which takes its first input's metadata, watermarks + * builds it some other way. Where both reach the same column, the lag is the difference of the Review Comment: **Nit (P3):** For a union input that does not watermark the column, the code returns `EventTimeLag.unbounded` (the `Union` case below), but this sentence states no result, and the closing "Everything else leaves the columns unrelated" reads as covering it. The difference matters: a key with an unrelated lag keeps the Spark 4.3 cutoff, while an unbounded one gets none, so an outer join on a key built by such a union fails analysis. Stating the unbounded result here would match the code. **Verification:** - **Inspection:** Each case named in lagBelow's scaladoc states the result the code returns for it. ########## sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelperSuite.scala: ########## @@ -48,6 +52,185 @@ class StreamingJoinHelperSuite extends AnalysisTest { } } + test("state watermark extraction ignores columns outside both attribute sets") { + val leftTime = AttributeReference("leftTime", TimestampType)() + val leftOffset = AttributeReference("leftOffset", LongType)() + val metadata = new MetadataBuilder().putLong(EventTimeWatermark.delayKey, 1000).build() + val rightTime = AttributeReference("rightTime", TimestampType, metadata = metadata)() + val rightDelay = AttributeReference("rightDelay", DayTimeIntervalType())() + val conditions = Seq( + leftTime > TimestampAddInterval(rightTime, rightDelay), + leftTime.cast(LongType) + leftOffset > rightTime.cast(LongType)) + val logAppender = new LogAppender("state watermark extraction") + withLogAppender(logAppender, level = Some(Level.WARN)) { + conditions.foreach { condition => + withClue(condition.sql) { + // The first condition reaches the references check through the V4 range scan and the Review Comment: **Nit (P3):** At this head eviction's range path, `getStateValueWatermarkForLags`, calls the solver with one watermarked column of the other input at a time, so the first condition passes the occurrence check and reaches the references check through eviction as well as through the V4 range scan. `getLeftSemiExactRightCutoffs` keeps only conjuncts shifted by literal intervals, so neither condition reaches the solver there. The comment should say that both conditions reach the check through eviction's range path and the V4 range scan. **Verification:** - **Inspection:** The comment's account of which callers reach the references check matches eviction's range path, the V4 range scan and the left semi exact cutoff. ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala: ########## @@ -17,36 +17,659 @@ package org.apache.spark.sql.catalyst.analysis +import java.util.Locale + +import scala.util.Try import scala.util.control.NonFatal import org.apache.spark.internal.Logging import org.apache.spark.internal.LogKeys._ +import org.apache.spark.sql.catalyst.InternalRow import org.apache.spark.sql.catalyst.expressions._ -import org.apache.spark.sql.catalyst.planning.ExtractEquiJoinKeys -import org.apache.spark.sql.catalyst.plans.logical.{EventTimeWatermark, LogicalPlan} +import org.apache.spark.sql.catalyst.plans.logical.{Expand, Join, LogicalPlan, Project, UnaryNode, Union} import org.apache.spark.sql.catalyst.plans.logical.EventTimeWatermark._ -import org.apache.spark.sql.catalyst.util.DateTimeConstants.MICROS_PER_DAY +import org.apache.spark.sql.catalyst.util.DateTimeConstants.{MICROS_PER_DAY, MICROS_PER_HOUR, MICROS_PER_MILLIS, MICROS_PER_MINUTE, MICROS_PER_SECOND} import org.apache.spark.sql.types._ import org.apache.spark.unsafe.types.CalendarInterval +/** + * How far below a column that can filter its stream-stream join input's late rows one of the + * input's watermarked columns can be, for an equality key or a range condition on it: at most + * `micros` where the plan relates the two columns; by an amount that the plan does not bound when + * `unbounded`; and by an amount that it does not show when `unrelated`, because it does not relate + * the two. A window column is compared by its end, as eviction and late filtering compare it. + */ +case class EventTimeLag(micros: Long, unrelated: Boolean, unbounded: Boolean) { + def max(other: EventTimeLag): EventTimeLag = EventTimeLag(math.max(micros, other.micros), + unrelated || other.unrelated, unbounded || other.unbounded) + + /** + * The cutoff for the other input's equality key when this input's watermark is `watermark`. + * A key that the plan does not relate keeps the Spark 4.3 cutoff. + */ + def keyWatermark(watermark: Long): Option[Long] = + if (unbounded) None else Some(watermark - EventTimeLag.ceilMillis(micros)) + + /** + * The watermark to substitute for the column in a range condition. Spark 4.3 substituted the + * watermark for every watermarked column; this does so only where the plan bounds the lag. + */ + def rangeWatermark(watermark: Long): Option[Long] = Review Comment: **Nit (P3):** The suites run range conditions only on columns with a finite lag, a copy of the event time and a copy shifted back 20 seconds in `StreamingJoinPlanRobustBoundSuite`; `StreamingJoinLegacyEventTimeKeySuite` asserts unbounded and unrelated lags but never runs a range condition on such a column. Treating an unbounded lag as zero here would evict state that later rows can still match and still pass every suite, and the unrelated branch, on which the chained-join finding on `lagBelow` turns, is just as unobserved. See **Shared repair plan 1** in the review body. ########## sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala: ########## @@ -721,14 +945,74 @@ class IncrementalExecution( override def apply(plan: SparkPlan): SparkPlan = { val planWithStateOpId = plan transform composedRule + // Validate the checkpoint-pinned semantics before writing state metadata or opening state, + // including a restart retrying an incomplete batch zero. + if (isFirstBatchWithOlderJoinWatermarkSemantics) { + def watermarkColumns(input: SparkPlan): String = { + val columns = input.output.filter( + _.metadata.contains(EventTimeWatermark.delayKey)) + if (columns.isEmpty) "none" else columns.map(_.name).mkString(", ") + } + // A join's output watermark reaches every stateful operator above it. One that uses its + // input watermark reads the inputs that the tracer names, or both inputs when it cannot + // be traced. An operator uses it when an input carries an event-time column, when it + // fires event-time timeouts, or when it passes the watermark to user code, as + // transformWithState does in every time mode. The join's output watermark changes + // nothing for any other operator, such as an update-mode count on a key. + def usesInputWatermark(operator: StatefulOperator): Boolean = operator match { + case _: TransformWithStateExec | _: TransformWithStateInPySparkExec => true + case f: FlatMapGroupsWithStateExec if f.timeoutConf == EventTimeTimeout => true Review Comment: **Nit (P3):** These two cases are the only reason a timeout operator over columns without a watermark counts as a consumer, and `StreamingJoinCheckpointCompatibilitySuite` has no `flatMapGroupsWithState` or `applyInPandasWithState` case; its only downstream user-code case is a processing-time `transformWithState`, which the line above covers. Without these cases, an older checkpoint of a key-only join followed by such an operator would be accepted, although its timeouts fire on the join's output watermark, which this version holds at 0, and every suite would still pass. **Verification:** - **Regression:** In the default mode, restarting a checkpoint without the semantics marker of a key-only join followed by flatMapGroupsWithState with EventTimeTimeout, whose input keeps no watermarked column, fails with STREAMING_JOIN_CHECKPOINT_INCOMPATIBLE before any state is opened. ########## sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala: ########## @@ -721,14 +945,74 @@ class IncrementalExecution( override def apply(plan: SparkPlan): SparkPlan = { val planWithStateOpId = plan transform composedRule + // Validate the checkpoint-pinned semantics before writing state metadata or opening state, + // including a restart retrying an incomplete batch zero. + if (isFirstBatchWithOlderJoinWatermarkSemantics) { + def watermarkColumns(input: SparkPlan): String = { + val columns = input.output.filter( + _.metadata.contains(EventTimeWatermark.delayKey)) + if (columns.isEmpty) "none" else columns.map(_.name).mkString(", ") + } + // A join's output watermark reaches every stateful operator above it. One that uses its + // input watermark reads the inputs that the tracer names, or both inputs when it cannot + // be traced. An operator uses it when an input carries an event-time column, when it + // fires event-time timeouts, or when it passes the watermark to user code, as + // transformWithState does in every time mode. The join's output watermark changes + // nothing for any other operator, such as an update-mode count on a key. + def usesInputWatermark(operator: StatefulOperator): Boolean = operator match { + case _: TransformWithStateExec | _: TransformWithStateInPySparkExec => true + case f: FlatMapGroupsWithStateExec if f.timeoutConf == EventTimeTimeout => true + case f: FlatMapGroupsInPandasWithStateExec if f.timeoutConf == EventTimeTimeout => true + case _ => operator.children.exists( + _.output.exists(_.metadata.contains(EventTimeWatermark.delayKey))) + } + val joinsBelowStatefulOperators = planWithStateOpId.collect { + case s: StatefulOperator if usesInputWatermark(s) => s.children.flatMap(_.collect { + case j: StreamingSymmetricHashJoinExec => j.stateInfo.map(_.operatorId) + }.flatten) + }.flatten.toSet + val tracedSides = joinWatermarkConsumers(planWithStateOpId) + .groupMap(_.joinOperatorId)(_.side) + def consumedSides(j: StreamingSymmetricHashJoinExec): Set[JoinSide] = Review Comment: **Blocking (P1):** Reading the code, a Spark 4.3 checkpoint of `left.withWatermark("lt", "10 seconds").join(right.withWatermark("rt", "10 seconds"), "key")` followed by `groupBy(window($"lt", "1 minute")).count()` in append mode, restarted with `spark.sql.streaming.statefulOperator.allowMultiple=false`, fails here: its offset log has no semantics version, the tracer follows the window back to `lt`, so `consumedSides` names the left input, and the key-only branch of `isWatermarkCheckpointCompatible` needs an empty set. In legacy mode, though, `UseSingleWatermarkPropagator` gives every operator the batch watermark and never calls `produceOutputWatermark`, which is why the start-time consumer check below is skipped there, and neither version evicts a key-only join, so this checkpoint would resume with unchanged semantics. The same holds for one-directional interval joins and forward-shifted keys in legacy mode, and in the default mode for the right input of a left semi join whose con sumer the tracer cannot follow, since a left semi join's output watermark reads only the left state watermark. The base branch had no restart check, so these restarts worked there; now the only way forward is a new checkpoint and a replay. **Recommended change:** Make consumedSides return no inputs when spark.sql.streaming.statefulOperator.allowMultiple is false, and leave out the right input of a left semi join, matching what the propagator and the join's output watermark read. Add restart tests with an older-semantics checkpoint of a legacy-mode key-only join followed by an append window aggregation, and of a left semi interval join that bounds only its left input, followed by an aggregation whose event time the tracer cannot follow. **Why this works:** The restart check then counts an input only where this version's output watermark for it reaches a later operator, which is where the semantics changed, so shapes whose output-watermark bound nobody reads resume as before. **Scope:** Inputs that the restart check counts as read after a stream-stream join **Compatibility:** Default-mode restarts whose consumer reads an input whose bound changed are still rejected, as are joins whose own eviction changed. **Risks:** Legacy-mode restarts of key-only and one-sided joins with an event-time consumer, and left semi joins with an untraced consumer, are accepted where they are rejected today; their eviction and the use of their output watermark are unchanged, so results match the older version. **Constraints:** The eviction-based rejections of the compatibility rule stay as they are. **Success:** A legacy-mode restart of an older checkpoint of a key-only join followed by an append window aggregation resumes and produces the results it produced before. A left semi join whose consumer the tracer cannot see is not rejected because of its right input. Default-mode restarts whose consumer reads an input whose bound changed are still rejected. **Verification:** - **Regression:** Restarting with allowMultiple=false a checkpoint without the semantics marker of a key-only inner join followed by an append window aggregation over the left event time resumes and emits the expected windows. - **Regression:** Restarting a checkpoint without the marker of a left semi interval join that bounds only its left input, followed by an aggregation whose event time the tracer cannot follow, is not rejected because of the right input. - **Compatibility:** Default-mode restarts of key-only joins whose consumer reads an event time still fail with STREAMING_JOIN_CHECKPOINT_INCOMPATIBLE before any state is opened. ########## sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinPlanRobustBoundSuite.scala: ########## @@ -0,0 +1,341 @@ +/* + * 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.sql.Timestamp + +import org.apache.spark.sql.{AnalysisException, Column, DataFrame, Row} +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 + +/** + * Stream-stream joins whose bound must hold whatever column pruning leaves in the planned + * inputs: keys and range conditions on a watermarked column that follows the input's event time, + * and keys that shift the event time by several intervals. + */ +class StreamingJoinPlanRobustBoundSuite extends StreamTest { + import testImplicits._ + + private val legacyMode = SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key -> "false" + private val defaultMode = SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key -> "true" + + /** An input of (key, seconds) with the event time `<side>t` and a watermark delay of 1 s. */ + private def eventTimeInput(memory: MemoryStream[(Int, Int)], side: String): DataFrame = + memory.toDF().toDF(s"${side}k", "time") + .select(col(s"${side}k"), timestamp_seconds($"time").as(s"${side}t")) + .withWatermark(s"${side}t", "1 second") + + /** Adds `<side>w`, a 10-second window over the event time. */ + private def windowed(memory: MemoryStream[(Int, Int)], side: String): DataFrame = + eventTimeInput(memory, side).withColumn(s"${side}w", window(col(s"${side}t"), "10 seconds")) + + /** Adds a watermarked column `<side>s` that holds the event time shifted by `shift`. */ + private def withShifted(df: DataFrame, side: String, shift: String): DataFrame = { + val time = s"${side}t" + df.select(col("*"), (col(time) + expr(shift)).as(s"${side}s", df.schema(time).metadata)) + } + + private def testJoin(conf: (String, String)*)(result: DataFrame)( + actions: StreamAction*): Unit = { + withSQLConf(Seq( + SQLConf.STATE_STORE_PROVIDER_CLASS.key -> classOf[RocksDBStateStoreProvider].getName, + SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> "false") ++ conf: _*) { + testStream(result)(StartStream() +: actions: _*) + } + } + + private def restartActions(restart: Boolean): Seq[StreamAction] = + if (restart) Seq(StopStream, StartStream()) else Nil + + private def assertStateRows(rows: Long): StreamAction = Execute { query => + assert(query.lastProgress.stateOperators.head.numRowsTotal === rows) + } + + /** Checks the state rows of a join that keeps every row until eviction, as all but semi do. */ + private def assertStateRows(joinType: String, rows: Long): Seq[StreamAction] = + if (joinType == "left_semi") Nil else Seq(assertStateRows(rows)) + + private def version(v: Int): (String, String) = + SQLConf.STREAMING_JOIN_STATE_FORMAT_VERSION.key -> v.toString + + /** The window of `seconds` seconds that starts at `start` seconds. */ + private def windowRow(start: Int, seconds: Int = 10): Row = + Row(new Timestamp(start * 1000L), new Timestamp((start + seconds) * 1000L)) + + // With multiple stateful operators allowed, the planned input keeps one watermarked column or + // the query fails at start. Here pruning removes the event time, so the window filters late + // rows, and the base branch evicted both inputs at the window end. Review Comment: **Nit (P3):** After merge, "the base branch" no longer names anything; the same suite says "Spark 4.3" for the earlier behavior at line 306. ```suggestion // rows, and Spark 4.3 evicted both inputs at the window end. ``` **Verification:** - **Inspection:** No comment in the plan-robust bound tests refers to the base branch. ########## sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala: ########## @@ -717,21 +738,111 @@ case class StreamingSymmetricHashJoinExec( Predicate.create(Literal(false), Seq.empty).eval _ // false = do not remove if no predicate } + // A NULL in the column that the state watermark predicate tests makes the predicate unknown, + // so eviction never removes the row. The row cannot match either: that column is an equality + // key, or a comparison in the join condition bounds it. Handle the row like one that fails + // the pre-join filter. + // The check takes the generated key and the input row, so the key is computed only once. + private[this] val isEvictionColumnNull: (UnsafeRow, UnsafeRow) => Boolean = + stateWatermarkPredicate match { + case Some(JoinStateKeyWatermarkPredicate(expr, _, _)) => + // Only a NULL key fails equality. A struct key with a NULL field can still be equal. + val ordinal = expr.collectFirst { case b: BoundReference => b.ordinal }.get + (key, _) => key.isNullAt(ordinal) + case Some(JoinStateValueWatermarkPredicate(LessThanOrEqual(column, _), _, _)) => + // Test the compared column, not the predicate: the predicate holds the cutoff, which + // changes every batch and would generate and compile new code each time. + val isNull = Predicate.create(IsNull(column), inputAttributes) + (_, row) => isNull.eval(row) + case _ => + (_, _) => false + } + + // V1 to V3 eviction tests every stored row each batch, so it also removes a row whose + // eviction column is NULL. This version never stores such a row, but an older version did, + // and the row can never match. isEvictionColumnNull reads only the key for a key predicate + // and only the row for a value predicate. + private[this] val stateKeyEvictionFunc: UnsafeRow => Boolean = + key => stateKeyWatermarkPredicateFunc(key) || isEvictionColumnNull(key, null) Review Comment: **Nit (P3):** This `|| isEvictionColumnNull(key, null)` matters only for state restored from an older version, because this version outputs a NULL-key row on arrival; Spark 4.3 stored such rows for aligned event-time keys, which the restart check accepts. The compatibility suite restores a NULL only under a value predicate in V2 and V3 and through the 4.3.0 fixtures in V4, so removing this branch would leave every suite green while a restored left outer join on `lk = rk AND lt = rt` would keep the NULL-key row in state and never output it. **Verification:** - **Regression:** For state formats 2 and 3, a left outer join on an aligned event-time key restored with a stored NULL-key left row outputs that row padded with nulls after the restart and keeps no state row for it. ########## sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala: ########## @@ -630,6 +674,186 @@ class IncrementalExecution( watermarkPropagator.propagate(currentBatchId, plan, watermarkForCurrBatch) } + /** + * Find, for each stateful operator that applies its input watermark to an event-time column, + * which stream-stream join inputs' event times that column carries. The walk follows the + * column down through nodes that pass it on unchanged, to the same position in every input + * of a union, and through windows built from it, which end after it. It stops at a join, at + * another operator that writes state or sets an event time, and at any node it does not + * recognize; a join that no traced column reaches holds back for both inputs. + */ + private def joinWatermarkConsumers(plan: SparkPlan): Seq[JoinWatermarkConsumer] = { + def eventTime(output: Seq[Attribute]): Option[Attribute] = + output.find(_.metadata.contains(EventTimeWatermark.delayKey)) + + // A time or session window built from one column, plus constants, ends after that column. + def windowSource(window: Attribute, expression: Expression): Option[Attribute] = { + val isWindow = window.metadata.contains(TimeWindow.marker) || + window.metadata.contains(SessionWindow.marker) + expression.references.toSeq match { + case Seq(source) if isWindow => Some(source) + case _ => None + } + } + + def passThrough(child: SparkPlan, attribute: Attribute): Seq[(Long, JoinSide, Attribute)] = + child.output.find(_.exprId == attribute.exprId).toSeq.flatMap(findJoinSides(child, _)) + + def findJoinSides( + node: SparkPlan, + attribute: Attribute): Seq[(Long, JoinSide, Attribute)] = { + node match { + case j: StreamingSymmetricHashJoinExec => + val side = if (eventTime(j.left.output).exists(_.exprId == attribute.exprId)) { + Some(LeftSide) + } else if (eventTime(j.right.output).exists(_.exprId == attribute.exprId)) { + Some(RightSide) + } else { + None + } + j.stateInfo.map(_.operatorId).zip(side).map { case (id, s) => (id, s, attribute) } + .toSeq + case p: ProjectExec => + p.projectList.find(_.exprId == attribute.exprId).toSeq.flatMap { + case a: Attribute => passThrough(p.child, a) + case Alias(a: Attribute, _) => passThrough(p.child, a) + case alias: Alias => + windowSource(alias.toAttribute, alias.child).toSeq.flatMap(passThrough(p.child, _)) + case _ => Nil + } + case e: ExpandExec => + // A sliding window is one projection per window; each must carry the same column. + val index = e.output.indexWhere(_.exprId == attribute.exprId) + val traced = e.projections.map { projection => + projection.lift(index).toSeq.flatMap { + case a: Attribute => passThrough(e.child, a) + case expression => + windowSource(e.output(index), expression).toSeq.flatMap(passThrough(e.child, _)) + } + } + if (traced.nonEmpty && traced.forall(_.nonEmpty) && traced.distinct.size == 1) { + traced.head + } else { + Nil + } + case u: UnionExec => + val index = u.output.indexWhere(_.exprId == attribute.exprId) + if (index < 0) Nil else u.children.flatMap(c => findJoinSides(c, c.output(index))) + case _: StateStoreWriter | _: EventTimeWatermarkExec | _: UpdateEventTimeColumnExec => + Nil + case u: UnaryExecNode if u.output.exists(_.exprId == attribute.exprId) => + passThrough(u.child, attribute) + case _ => Nil Review Comment: **Blocking (P1):** Reading the code, take impressions inner-joined with clicks on the key and `clickTime <= impressionTime + INTERVAL 1 HOUR`, which bounds the impression state but not the click state, then a left outer join with a static DataFrame and `groupBy(window($"impressionTime", "10 minutes")).count()` in append mode. The trace from the aggregation reaches the `BroadcastHashJoinExec` or `SortMergeJoinExec` of the stream-static join, which this case does not follow because it has two children, so the trace ends at `case _ => Nil` below and the stream-stream join keeps `outputWatermarkSides = None` and takes the minimum over both state watermarks. `getStateWatermark` now returns 0 for the click input, so the output watermark, and with it the aggregation's input watermark, stays 0 and no window is ever emitted. On the base branch the click input contributed no state watermark and the windows were emitted, and without the stream-static join they are emitted here too. The resta rt check reads the same tracer, so older checkpoints of such queries are judged on both inputs as well, and the test "V4 chained joins scan from the start after the plan between them changes" in `StreamingJoinCheckpointCompatibilitySuite` asserts this hold at 0 as expected. **Recommended change:** In findJoinSides, follow a binary node, such as the broadcast hash, sort merge or nested loop join of a stream-static join, into the one child whose output carries the traced attribute's expression ID, as lagBelow already does for a logical join child that outputs both columns, and keep the empty result when no child or more than one child carries it. Update the chained-join compatibility test, which now expects the upstream join to hold back at 0 behind a stream-static join, and add join tests with an append-mode window aggregation behind a stream-static join over the bounded and over the unbounded input's event time. **Why this works:** A stream-static join passes each streaming column through with its expression ID, so following the child that outputs it reaches the stream-stream join input exactly as for a unary node; the join then holds back only for the traced input, and a consumer of the bounded input sees that input's state watermark again. **Scope:** Tracing of the join's output-watermark consumers through binary physical nodes **Compatibility:** A consumer whose event time the tracer still cannot follow keeps the both-inputs rule, and legacy mode is unchanged. **Risks:** A consumer behind a stream-static join that reads the unbounded input's event time is now traced, so the start-time check rejects a query that before ran without emitting; the finalization conf still turns that into a warning. Restarts of older checkpoints of such queries are judged on the traced input only, so some that are rejected today are accepted. **Constraints:** Nodes the tracer still cannot follow keep the both-inputs rule. **Success:** An append-mode window aggregation over the bounded input's event time behind a stream-static join emits its windows as the watermark passes them. The same aggregation over the unbounded input's event time fails at start with STREAMING_JOIN_UNBOUNDED_DOWNSTREAM_EVENT_TIME. In the chained-join compatibility test, the upstream join's output watermark follows the impression input behind the stream-static join. **Verification:** - **Regression:** A default-mode inner join of impressions and clicks on the key and clickTime <= impressionTime + INTERVAL 1 HOUR, followed by a projection of the key and impressionTime, a left outer join with a static DataFrame and an append-mode window count over impressionTime, emits each window after the watermark passes it. - **Behavior:** The same query counting windows over clickTime fails at start with the downstream event-time error, and runs with a warning when the finalization check is disabled. - **Compatibility:** Queries without a binary node between the join and its consumer keep their output watermarks, start-time decisions and restart decisions. ########## sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/SymmetricHashJoinStateManager.scala: ########## @@ -253,54 +254,63 @@ class SymmetricHashJoinStateManagerV4( protected val keySchema = StructType( joinKeys.zipWithIndex.map { case (k, i) => StructField(s"field$i", k.dataType, k.nullable) }) protected val keyAttributes = toAttributes(keySchema) - private val eventTimeColIdxOpt = WatermarkSupport.findEventTimeColumnIndex( - inputValueAttributes, - // NOTE: This does not accept multiple event time columns. This is not the same with the - // operator which we offer the backward compatibility, but it involves too many layers to - // pass the information. The information is in SQLConf. - allowMultipleEventTimeColumns = false) - - // When there is no event time column in the value and no watermark ordinal in the key, + private val valueTimestampColumnOrdinal = { + val eventTimeColIdx = WatermarkSupport.findEventTimeColumnIndex( + inputValueAttributes, + // NOTE: This does not accept multiple event time columns. This is not the same with the + // operator which we offer the backward compatibility, but it involves too many layers to + // pass the information. The information is in SQLConf. + allowMultipleEventTimeColumns = false) + // Validate event-time columns above even when eviction indexes a different timestamp. + stateValueWatermarkColumnOrdinal.orElse(eventTimeColIdx) + } + + // When there is no indexed timestamp column in the value and no watermark ordinal in the key, // the secondary index (TsWithKey) will never be used for eviction. Skip writing to it // to avoid unnecessary RocksDB merge overhead. // TODO(SPARK-56536): This could be further optimized by also considering whether the state - // watermark predicate is defined. Even when an event time column exists, the secondary index - // is unused if eviction is not possible (e.g., only one side defines a watermark in a time - // interval join). That would require propagating the predicate information here. - private val hasEventTime: Boolean = - eventTimeColIdxOpt.isDefined || joinKeyOrdinalForWatermark.isDefined + // watermark predicate is defined. Even when an indexed timestamp column exists, the secondary + // index is unused if eviction is not possible (e.g., only one side defines a watermark in a + // time interval join). That would require propagating the predicate information here. + private val hasTimestampForEviction: Boolean = + valueTimestampColumnOrdinal.isDefined || joinKeyOrdinalForWatermark.isDefined private val random = new scala.util.Random(System.currentTimeMillis()) - private val bucketCountForNoEventTime = 1024 - private val extractEventTimeFn: UnsafeRow => Long = { row => - eventTimeColIdxOpt match { - case Some(idx) => - val attr = inputValueAttributes(idx) + private val bucketCountWithoutTimestamp = 1024 + // A null indexed timestamp makes the value-eviction predicate SQL-unknown, so V2 and V3 never + // evict such a row. Return None for it, so it is kept out of the timestamp eviction index. Review Comment: **Nit (P3):** The V1 to V3 eviction functions in `StreamingSymmetricHashJoinExec`, `stateKeyEvictionFunc` and `stateValueEvictionFunc`, OR `isEvictionColumnNull` into the watermark predicate, so V2 and V3 do remove such a row; what still holds for V4 is that its value-eviction predicate is SQL-unknown for the row. ```suggestion // A null indexed timestamp makes the value-eviction predicate SQL-unknown; V1 to V3 remove such // a row by a separate NULL check. Return None for it, so it is kept out of the timestamp index. ``` **Verification:** - **Inspection:** No comment in the join state manager or the join operator says that V2 or V3 keep a row whose eviction column is NULL. ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala: ########## @@ -17,36 +17,659 @@ package org.apache.spark.sql.catalyst.analysis +import java.util.Locale + +import scala.util.Try import scala.util.control.NonFatal import org.apache.spark.internal.Logging import org.apache.spark.internal.LogKeys._ +import org.apache.spark.sql.catalyst.InternalRow import org.apache.spark.sql.catalyst.expressions._ -import org.apache.spark.sql.catalyst.planning.ExtractEquiJoinKeys -import org.apache.spark.sql.catalyst.plans.logical.{EventTimeWatermark, LogicalPlan} +import org.apache.spark.sql.catalyst.plans.logical.{Expand, Join, LogicalPlan, Project, UnaryNode, Union} import org.apache.spark.sql.catalyst.plans.logical.EventTimeWatermark._ -import org.apache.spark.sql.catalyst.util.DateTimeConstants.MICROS_PER_DAY +import org.apache.spark.sql.catalyst.util.DateTimeConstants.{MICROS_PER_DAY, MICROS_PER_HOUR, MICROS_PER_MILLIS, MICROS_PER_MINUTE, MICROS_PER_SECOND} import org.apache.spark.sql.types._ import org.apache.spark.unsafe.types.CalendarInterval +/** + * How far below a column that can filter its stream-stream join input's late rows one of the + * input's watermarked columns can be, for an equality key or a range condition on it: at most + * `micros` where the plan relates the two columns; by an amount that the plan does not bound when + * `unbounded`; and by an amount that it does not show when `unrelated`, because it does not relate + * the two. A window column is compared by its end, as eviction and late filtering compare it. + */ +case class EventTimeLag(micros: Long, unrelated: Boolean, unbounded: Boolean) { + def max(other: EventTimeLag): EventTimeLag = EventTimeLag(math.max(micros, other.micros), + unrelated || other.unrelated, unbounded || other.unbounded) + + /** + * The cutoff for the other input's equality key when this input's watermark is `watermark`. + * A key that the plan does not relate keeps the Spark 4.3 cutoff. + */ + def keyWatermark(watermark: Long): Option[Long] = + if (unbounded) None else Some(watermark - EventTimeLag.ceilMillis(micros)) + + /** + * The watermark to substitute for the column in a range condition. Spark 4.3 substituted the + * watermark for every watermarked column; this does so only where the plan bounds the lag. + */ + def rangeWatermark(watermark: Long): Option[Long] = + if (unbounded || unrelated) None else Some(watermark - EventTimeLag.ceilMillis(micros)) +} + +object EventTimeLag { + val zero: EventTimeLag = EventTimeLag(0L, unrelated = false, unbounded = false) + val unrelated: EventTimeLag = EventTimeLag(0L, unrelated = true, unbounded = false) + val unbounded: EventTimeLag = EventTimeLag(0L, unrelated = false, unbounded = true) + + private def ceilMillis(micros: Long): Long = + micros / MICROS_PER_MILLIS + (if (micros % MICROS_PER_MILLIS == 0) 0 else 1) +} + +/** + * The [[EventTimeLag]] of the watermarked columns of stream-stream join inputs, by expression ID; + * see [[StreamingJoinHelper.findEventTimeLags]]. A column missing from `lags` has lag zero, so + * `EventTimeLags(Map.empty)` gives every watermarked column lag zero. That is right when multiple + * stateful operators are allowed: execution then fails at start for a planned input with two + * distinct watermarked columns, so the only one left filters late rows itself. + */ +case class EventTimeLags(lags: Map[ExprId, EventTimeLag]) { + /** + * The lag of `column` in a join input with output `inputAttributes`, if it carries a watermark. + * The input's first watermarked column filters its late rows itself. + */ + def lagOf(column: NamedExpression, inputAttributes: Seq[Attribute]): Option[EventTimeLag] = + if (!column.metadata.contains(delayKey)) { + None + } else if (inputAttributes.find(_.metadata.contains(delayKey)) + .exists(_.exprId == column.exprId)) { + Some(EventTimeLag.zero) + } else { + Some(lags.getOrElse(column.exprId, EventTimeLag.zero)) + } +} + +object EventTimeLags { + val none: EventTimeLags = EventTimeLags(Map.empty) +} + /** * Helper object for stream joins. See [[StreamingSymmetricHashJoinExec]] in SQL for more details. */ 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. Without `lags`, only the input's first watermarked + * column counts as its event time; with them, every watermarked column that they bound does. + */ + def getStateKeyWatermarkOrdinal( + keys: Seq[Expression], + inputAttributes: Seq[Attribute], + lags: Option[EventTimeLags] = None): Option[Int] = { + getEventTimeKeyOrdinal(keys, inputAttributes, lags).orElse { + keys.indices.find(getStateKeyWatermark(keys, inputAttributes, _, Some(0L), lags).isDefined) + } + } + + /** + * Find the equality key that is this input's first watermarked column, or else, with `lags`, + * the watermarked key with the smallest lag that bounds it; see [[findEventTimeLags]]. + */ + def getEventTimeKeyOrdinal( + keys: Seq[Expression], + inputAttributes: Seq[Attribute], + lags: Option[EventTimeLags] = None): 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 => + Some(keys.indexWhere(_.semanticEquals(eventTime))).filter(_ >= 0).orElse { + lags.flatMap { l => + keys.indices.flatMap { i => + keyLag(keys(i), inputAttributes, l).filterNot(_.unbounded).map(i -> _.micros) + }.sortBy(_._2).headOption.map(_._1) + } + } + } + } + + /** The lag of a key that is a watermarked column of the input. */ + private def keyLag( + key: Expression, + inputAttributes: Seq[Attribute], + lags: EventTimeLags): Option[EventTimeLag] = key match { + case n: NamedExpression => lags.lagOf(n, inputAttributes) + case _ => None + } + + /** + * The lag of every watermarked column of each stream-stream join input in `plan`, combined + * over the inputs by [[EventTimeLag.max]]. This is for + * spark.sql.streaming.statefulOperator.allowMultiple=false, where an input can keep several + * watermarked columns, such as its event time and a copy of it or a time window over it, and + * filters late rows by the first of them. When `planned`, `plan` is the optimized plan that runs, + * so each input filters late rows by its first watermarked column, and a column's lag is taken + * against that one. Otherwise the optimizer can prune any watermarked column before a column, so + * its lag is the largest against all of them. Spark 4.3 bounded state by every watermarked + * column at the watermark. A lag lowers that cutoff; see [[EventTimeLag]]. + */ + def findEventTimeLags(plan: LogicalPlan, planned: Boolean): EventTimeLags = { + val lags = plan.collect { + case j: Join if j.left.isStreaming && j.right.isStreaming => Seq(j.left, j.right) + }.flatten.flatMap { input => + val watermarked = input.output.filter(_.metadata.contains(delayKey)).map(_.exprId).distinct + watermarked.indices.map { i => + val lateFiltered = if (planned) watermarked.take(1) else watermarked.take(i) + watermarked(i) -> lateFiltered.filter(_ != watermarked(i)).map { eventTime => + lagBelow(input, watermarked(i), eventTime, Some(0L), Some(0L)) + }.foldLeft(EventTimeLag.zero)(_ max _) + } + } + EventTimeLags(lags.groupMapReduce(_._1)(_._2)(_ max _)) + } + + /** How a column relates to the column of a node's child that [[lagBelow]] follows for it. */ + private case class Step(column: ExprId, offset: Option[Long]) + + /** + * How far `key` of `plan` can be below its column `eventTime`, which late filtering compares + * with the watermark. Both are compared by their bounds: a time, or a window's end. `keyLow` is + * the smallest that the join input's key is above `key`, and `eventTimeHigh` the largest that the + * join input's late-filtered column is above `eventTime`; None means without bound. The walk + * follows both columns down by expression ID: through a projection or an expansion that passes + * them on, builds a time or session window from a single column, or, for the key, shifts a + * timestamp by constant intervals; through any other node with one input that outputs both, as + * such a node keeps an expression ID only for an unchanged value; into the input of a join that + * outputs both; and into every input of a union, at the same positions. A union input that does + * not watermark a column that the union, which takes its first input's metadata, watermarks + * builds it some other way. Where both reach the same column, the lag is the difference of the + * two offsets. Everything else leaves the columns unrelated. + */ + private def lagBelow( + plan: LogicalPlan, + key: ExprId, + eventTime: ExprId, + keyLow: Option[Long], + eventTimeHigh: Option[Long]): EventTimeLag = { + def outputsBoth(p: LogicalPlan): Boolean = + p.output.exists(_.exprId == key) && p.output.exists(_.exprId == eventTime) + def follow(child: LogicalPlan, keyStep: Option[Step], eventTimeStep: Option[Step]) = + (keyStep, eventTimeStep) match { + case (Some(k), Some(t)) => lagBelow(child, k.column, t.column, + addOffsets(keyLow, k.offset), addOffsets(eventTimeHigh, t.offset)) + case _ => EventTimeLag.unrelated + } + if (key == eventTime) { + (keyLow, eventTimeHigh) match { + case (Some(low), Some(high)) => Try(Math.subtractExact(high, low)).toOption match { + case Some(lag) => EventTimeLag(math.max(0L, lag), unrelated = false, unbounded = false) + case None => EventTimeLag.unbounded + } + case _ => EventTimeLag.unbounded + } + } else { + plan match { + case p: Project => + def entry(id: ExprId): Option[NamedExpression] = p.projectList.find(_.exprId == id) + follow(p.child, entry(key).flatMap(keyStep), entry(eventTime).flatMap(eventTimeStep)) + case e: Expand => + // The rewrite of a sliding window puts one window per projection beside the child's + // columns, which every projection passes on. + def step(id: ExprId, window: (Seq[Expression], Attribute) => Option[Long]) = { + val entries = e.output.indexWhere(_.exprId == id) match { + case -1 => Nil + case index => e.projections.map(_(index)) + } + entries.map { + case a: Attribute => Some(a.exprId) + case _ => None + }.distinct match { + case Seq(Some(passedOn)) => Some(Step(passedOn, Some(0L))) + case _ if e.output.exists(a => a.exprId == id && + a.metadata.contains(TimeWindow.marker)) => + entries.map(timeWindowSource).distinct match { + case Seq(Some(source)) => Some(Step(source.exprId, window(entries, source))) + case _ => None + } + case _ => None + } + } + // A window ends after its time column, and at most its length after it. + follow(e.child, step(key, (_, _) => Some(0L)), step(eventTime, (entries, source) => + entries.map(timeWindowLength(_, source)).reduceOption((a, b) => + for (x <- a; y <- b) yield math.max(x, y)).flatten)) + case u: Union => + val keyIndex = u.output.indexWhere(_.exprId == key) + val eventTimeIndex = u.output.indexWhere(_.exprId == eventTime) + def unwatermarked(child: LogicalPlan, index: Int): Boolean = + u.output(index).metadata.contains(delayKey) && + !child.output(index).metadata.contains(delayKey) + if (keyIndex < 0 || eventTimeIndex < 0) { + EventTimeLag.unrelated + } else { + u.children.map { child => + if (unwatermarked(child, keyIndex) || unwatermarked(child, eventTimeIndex)) { + EventTimeLag.unbounded + } else { + lagBelow(child, child.output(keyIndex).exprId, + child.output(eventTimeIndex).exprId, keyLow, eventTimeHigh) + } + }.reduce(_ max _) + } + case j: Join => + j.children.find(outputsBoth).map(lagBelow(_, key, eventTime, keyLow, eventTimeHigh)) + .getOrElse(EventTimeLag.unrelated) Review Comment: **Blocking (P1):** Reading the code in legacy mode, take `AB = A.join(B, ak = bk AND at = bt)` followed by `AB.join(C, ak = ck AND ct BETWEEN bt AND bt + INTERVAL 1 HOUR, "right_outer")`. AB outputs `at` before `bt` and filters its late rows by `at`, so `bt` gets a lag against `at`. This `Join` case finds no child that outputs both columns and returns `EventTimeLag.unrelated`, although the join's own condition makes `bt = at` on every row. `rangeWatermark` then gives `bt` no range bound, `at` does not occur in the range condition, and the right outer join fails analysis; with `spark.sql.streaming.join.checkFinalization.enabled=false` it runs but never outputs C's unmatched rows, and the inner form never evicts C while the query keeps `at`. The base branch substituted the watermark for every watermarked column and evicted C below the watermark less 1 ms, which is exact here because every AB row that passes late filtering has `bt = at` above the watermark. Leaving a column without a range bound is right only where the plan leaves it free of the late-filtered column. After a key-only earlier join on `ak = bk`, an old B row that the first join keeps can meet a new A row, so `bt` can be far below `at`, and the base branch's cutoff drops matches there. Giving every unrelated column the Spark 4.3 cutoff would bring those dropped matches back, so the bound has to come from relating the two columns through the join's condition. This extends an [existing discussion](https://github.com/apache/spark/pull/60280#discussion_r4579272762). See **Shared repair plan 1** in the review body. ########## sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinPlanRobustBoundSuite.scala: ########## @@ -0,0 +1,341 @@ +/* + * 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.sql.Timestamp + +import org.apache.spark.sql.{AnalysisException, Column, DataFrame, Row} +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 + +/** + * Stream-stream joins whose bound must hold whatever column pruning leaves in the planned + * inputs: keys and range conditions on a watermarked column that follows the input's event time, + * and keys that shift the event time by several intervals. + */ +class StreamingJoinPlanRobustBoundSuite extends StreamTest { + import testImplicits._ + + private val legacyMode = SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key -> "false" + private val defaultMode = SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key -> "true" + + /** An input of (key, seconds) with the event time `<side>t` and a watermark delay of 1 s. */ + private def eventTimeInput(memory: MemoryStream[(Int, Int)], side: String): DataFrame = + memory.toDF().toDF(s"${side}k", "time") + .select(col(s"${side}k"), timestamp_seconds($"time").as(s"${side}t")) + .withWatermark(s"${side}t", "1 second") + + /** Adds `<side>w`, a 10-second window over the event time. */ + private def windowed(memory: MemoryStream[(Int, Int)], side: String): DataFrame = + eventTimeInput(memory, side).withColumn(s"${side}w", window(col(s"${side}t"), "10 seconds")) + + /** Adds a watermarked column `<side>s` that holds the event time shifted by `shift`. */ + private def withShifted(df: DataFrame, side: String, shift: String): DataFrame = { + val time = s"${side}t" + df.select(col("*"), (col(time) + expr(shift)).as(s"${side}s", df.schema(time).metadata)) + } + + private def testJoin(conf: (String, String)*)(result: DataFrame)( + actions: StreamAction*): Unit = { + withSQLConf(Seq( + SQLConf.STATE_STORE_PROVIDER_CLASS.key -> classOf[RocksDBStateStoreProvider].getName, + SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> "false") ++ conf: _*) { + testStream(result)(StartStream() +: actions: _*) + } + } + + private def restartActions(restart: Boolean): Seq[StreamAction] = + if (restart) Seq(StopStream, StartStream()) else Nil + + private def assertStateRows(rows: Long): StreamAction = Execute { query => + assert(query.lastProgress.stateOperators.head.numRowsTotal === rows) + } + + /** Checks the state rows of a join that keeps every row until eviction, as all but semi do. */ + private def assertStateRows(joinType: String, rows: Long): Seq[StreamAction] = + if (joinType == "left_semi") Nil else Seq(assertStateRows(rows)) + + private def version(v: Int): (String, String) = + SQLConf.STREAMING_JOIN_STATE_FORMAT_VERSION.key -> v.toString + + /** The window of `seconds` seconds that starts at `start` seconds. */ + private def windowRow(start: Int, seconds: Int = 10): Row = + Row(new Timestamp(start * 1000L), new Timestamp((start + seconds) * 1000L)) + + // With multiple stateful operators allowed, the planned input keeps one watermarked column or + // the query fails at start. Here pruning removes the event time, so the window filters late + // rows, and the base branch evicted both inputs at the window end. + for { + joinType <- Seq("left_outer", "left_semi", "full_outer") + v <- Seq(2, 3, 4) + restart <- Seq(false, true) + } { + test(s"default-mode $joinType join on a window after the event time, with the event time " + + s"pruned, evicts at the window end, V$v${if (restart) ", restart" else ""}") { + val leftInput = MemoryStream[(Int, Int)] + val rightInput = MemoryStream[(Int, Int)] + val joined = windowed(leftInput, "l") + .join(windowed(rightInput, "r"), expr("lk = rk AND lw = rw"), joinType) + val result = if (joinType == "left_semi") { + joined.select($"lk", $"lw.start".cast("int")) + } else { + joined.select($"lk", $"lw.start".cast("int"), $"rk", $"rw.start".cast("int")) + } + val (matched, unmatched) = joinType match { + case "left_semi" => (Row(1, 0), Nil) + case _ => (Row(1, 0, 1, 0), Seq(Row(2, 0, null, null))) + } + testJoin(defaultMode, version(v))(result)(Seq( + MultiAddData(leftInput, (1, 5), (2, 6))(rightInput, (1, 5)), + CheckNewAnswer(matched), + // The watermark is 30 seconds from the next batch on. + MultiAddData(leftInput, (3, 31))(rightInput, (9, 31)), + CheckNewAnswer()) ++ restartActions(restart) ++ Seq( + AddData(rightInput, (9, 40)), + // The windows [0, 10) end below the watermark, so their unmatched rows are output. + CheckNewAnswer(unmatched: _*)) ++ assertStateRows(joinType, 3): _*) + } + } + + // A range condition on a copy of the right event time placed after it. Without rt in the + // output, the planned right input keeps only the copy, which then filters late rows itself. + for { + (modeName, mode) <- Seq("default" -> defaultMode, "legacy" -> legacyMode) + joinType <- Seq("left_outer", "left_semi") + v <- Seq(2, 3) + } { + test(s"$modeName-mode $joinType join with a range on a copy of the event time evicts by " + + s"it, V$v") { + val leftInput = MemoryStream[(Int, Int)] + val rightInput = MemoryStream[(Int, Int)] + val right = eventTimeInput(rightInput, "r").withColumn("rc", $"rt") + val joined = eventTimeInput(leftInput, "l").join(right, + expr("lk = rk AND lt BETWEEN rc - INTERVAL 5 SECONDS AND rc + INTERVAL 5 SECONDS"), + joinType) + val result = if (joinType == "left_semi") { + joined.select($"lk", $"lt".cast("int")) + } else { + joined.select($"lk", $"lt".cast("int"), $"rk") + } + val (matched, unmatched) = if (joinType == "left_semi") { + (Row(1, 10), Nil) + } else { + (Row(1, 10, 1), Seq(Row(2, 12, null))) + } + testJoin(mode, version(v))(result)(Seq( + MultiAddData(leftInput, (1, 10), (2, 12))(rightInput, (1, 12)), + CheckNewAnswer(matched), + MultiAddData(leftInput, (3, 40))(rightInput, (9, 40)), + CheckNewAnswer(), + // At the watermark of 39 seconds, a right row has rc above 39 seconds, so left rows + // below 34 seconds can no longer match. + AddData(rightInput, (9, 41)), + CheckNewAnswer(unmatched: _*)) ++ assertStateRows(joinType, 3): _*) + } + } + + // Legacy mode: a copy of the event time placed after a window over it. The planned input + // filters late rows by the event time when the query reads it after the join, and by the + // window otherwise, so a row's copy is above the watermark less the window's 10 seconds. + for { + joinType <- Seq("inner", "left_outer", "right_outer", "full_outer", "left_semi") + v <- Seq(2, 3) + } { + def withCopy(memory: MemoryStream[(Int, Int)], side: String): DataFrame = + windowed(memory, side).withColumn(s"${side}c", col(s"${side}t")) + def expected(joinType: String, rows: Row*): Seq[Row] = joinType match { + case "left_semi" => rows.map(r => Row(r.get(0), r.get(1))) + case _ => rows + } + def project(joined: DataFrame, joinType: String, time: String => Column): DataFrame = + if (joinType == "left_semi") { + joined.select($"lk", time("l")) + } else { + joined.select($"lk", time("l"), $"rk", time("r")) + } + val outer = joinType == "left_outer" || joinType == "full_outer" + + test(s"legacy-mode $joinType join on a copy of the event time after a window over it, " + + s"with the event time kept, evicts at the watermark, V$v") { + val leftInput = MemoryStream[(Int, Int)] + val rightInput = MemoryStream[(Int, Int)] + val joined = withCopy(leftInput, "l") + .join(withCopy(rightInput, "r"), expr("lk = rk AND lc = rc"), joinType) + val result = project(joined, joinType, side => col(s"${side}t").cast("int")) + testJoin(legacyMode, version(v))(result)(Seq( + MultiAddData(leftInput, (1, 5), (2, 25))(rightInput, (1, 5)), + CheckNewAnswer(expected(joinType, Row(1, 5, 1, 5)): _*), + MultiAddData(leftInput, (9, 31))(rightInput, (9, 31)), + CheckNewAnswer(expected(joinType, Row(9, 31, 9, 31)): _*), + // The planned inputs filter late rows by their event times, so at the watermark of 30 + // seconds no later row matches the left row at 25 seconds or the right row at 5 seconds. + AddData(rightInput, (8, 32)), + CheckNewAnswer((if (outer) Seq(Row(2, 25, null, null)) else Nil): _*)) ++ + assertStateRows(joinType, 3): _*) + } + + test(s"legacy-mode $joinType join on a copy of the event time after a window over it, " + + s"with the event time pruned, evicts at the watermark less the window, V$v") { + val leftInput = MemoryStream[(Int, Int)] + val rightInput = MemoryStream[(Int, Int)] + val joined = withCopy(leftInput, "l") + .join(withCopy(rightInput, "r"), expr("lk = rk AND lc = rc"), joinType) + // The query reads the whole windows: reading only a field of one lets the optimizer prune + // the watermarked window, and the copy then filters late rows itself. + val result = project(joined, joinType, side => col(s"${side}w")) + testJoin(legacyMode, version(v))(result)(Seq( + MultiAddData(leftInput, (1, 5), (2, 25))(rightInput, (1, 5)), + CheckNewAnswer(expected(joinType, Row(1, windowRow(0), 1, windowRow(0))): _*), + MultiAddData(leftInput, (9, 31))(rightInput, (9, 31)), + CheckNewAnswer(expected(joinType, Row(9, windowRow(30), 9, windowRow(30))): _*), + // A later left row at 25 seconds passes late filtering by its window, which ends at 30 + // seconds, so the right state keeps rows above 20 seconds. Review Comment: **Nit (P3):** At this batch the watermark is 30 seconds, the 31-second rows of the previous batch less the 1-second delay, and late filtering on a window drops a row whose window ends at or below it, so a left row at 25 seconds, in `[20, 30)`, is dropped as late. The 20-second bound follows from the window length instead: ```suggestion // A left row passes late filtering only when its window ends after the 30-second // watermark, so its copy lc is above 20 seconds and the right state keeps rows above that. ``` **Verification:** - **Inspection:** Each late-filtering example in the comments of the plan-robust bound tests is consistent with the watermark at that step. ########## common/utils/src/main/resources/error/error-conditions.json: ########## @@ -8165,6 +8165,31 @@ ], "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 has no bound on that event time for the state of that input, so it holds back its output watermark and the aggregation would never emit results." + ], + "subClass" : { + "TIME_CONSTRAINT" : { + "message" : [ + "Add a time constraint that limits how late a matching <otherSide> row can arrive, aggregate the event time of an input whose state the join can bound, or use the update output mode. A bound on the event time comes from an equality key that shifts the other input's event time by an exact interval (under one day, or timestampadd in hours, minutes or seconds), or from a range condition used in place of a shifted equality. To run the query anyway, set <config> to false." Review Comment: **Nit (P3):** The start-time check raises this error for outer joins too, such as a left outer join on `lt = rt` with a watermark only on `rt` followed by an append-mode aggregation over `rt`. For those joins, switching to the update output mode fails analysis with "LeftOuter join between two streaming DataFrames/Datasets is not supported in Update output mode, only in Append output mode". The `WATERMARK_AND_TIME_CONSTRAINT` sub-condition below ends with the same remedy; both should offer it only for inner and left semi joins. **Verification:** - **Behavior:** The downstream event-time error for a left outer join on lt = rt with a watermark only on rt, followed by an append aggregation over rt, names the update output mode only for inner and left semi joins. ########## sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinCheckpointCompatibilitySuite.scala: ########## @@ -0,0 +1,1228 @@ +/* + * 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 scala.util.matching.Regex + +import org.apache.hadoop.fs.Path + +import org.apache.spark.sql.{AnalysisException, DataFrame, Row} +import org.apache.spark.sql.catalyst.expressions.{Add, Alias, And, Attribute, AttributeReference, Between, Cast, Expression, GreaterThan, GreaterThanOrEqual, LessThan, LessThanOrEqual, Literal, TimestampAddInterval} +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.{JoinSide, JoinStateKeyWatermarkPredicate, JoinStateValueWatermarkPredicate, LeftSide, RightSide} +import org.apache.spark.sql.execution.streaming.runtime.{MemoryStream, StreamExecution} +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.{DayTimeIntervalType, IntegerType, LongType, MetadataBuilder, + StructField, StructType, TimestampType} +import org.apache.spark.tags.SlowSQLTest +import org.apache.spark.unsafe.types.CalendarInterval +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 + } + } + + // Copies a bundled checkpoint and points the copied operator metadata at the state schema files + // of the copy. The bundled metadata names them under a placeholder directory, and a restart that + // follows that name would find no schema file, treat the restart as a first run and compare + // nothing. The checksum file of a rewritten metadata file no longer matches, so it goes. + private def copyCheckpointFixture(name: String, checkpointDir: File): Unit = { + val resource = getClass.getResource(s"/structured-streaming/$name/").toURI + val checkpoint = checkpointDir.getCanonicalFile + Utils.copyDirectory(new File(resource), checkpoint) + val schemaFile = "\"[^\"]*/state/(\\d+)/_stateSchema/([^/\"]+)/([^/\"]+)\"".r + val metadataFiles = Files.walk(new File(checkpoint, "state").toPath) + val rewritten = Using.resource(metadataFiles) { paths => + paths.iterator().asScala.filter { path => + Files.isRegularFile(path) && path.getParent.endsWith("_metadata/v2") && + !path.getFileName.toString.startsWith(".") + }.toList + } + assert(rewritten.nonEmpty, s"No operator metadata in the fixture $name") + rewritten.foreach { path => + val metadata = new String(Files.readAllBytes(path), "UTF-8") + val updated = schemaFile.replaceAllIn(metadata, m => { + val copy = new File(checkpoint, + s"state/${m.group(1)}/_stateSchema/${m.group(2)}/${m.group(3)}") + assert(copy.isFile, s"The fixture $name has no state schema file $copy") + Regex.quoteReplacement("\"" + new Path(copy.toURI).toString + "\"") + }) + assert(updated != metadata, s"No state schema file is named in $path") + Files.write(path, updated.getBytes("UTF-8")) + Files.deleteIfExists(path.resolveSibling("." + path.getFileName + ".crc")) + } + } + + 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 the left input's event time. + joined.select($"leftKey", $"rightKey", $"leftTime", $"rightTime".cast("long")) + .dropDuplicates() + .select($"leftKey", $"rightKey", $"leftTime".cast("long"), $"rightTime") + } 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. A key that uses an event time makes it not key-only; another condition that + // gives no bound in either version keeps both inputs unbounded. + 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), Seq(rightId), + Some(GreaterThan(leftId, Literal(1))))) + 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: this + // version still derives the older bound for whole windows, but SPARK-61348 later removes it + // for windows shorter than the other input's. + 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))) + } + + test("checkpoint compatibility ignores conjuncts that no version derives a bound from") { + val watermarkMetadata = new MetadataBuilder() + .putLong(EventTimeWatermark.delayKey, 0L).build() + val leftKey = AttributeReference("leftKey", IntegerType)() + val rightKey = AttributeReference("rightKey", IntegerType)() + val leftPrice = AttributeReference("leftPrice", IntegerType)() + val rightPrice = AttributeReference("rightPrice", IntegerType)() + val leftOther = AttributeReference("leftOther", TimestampType)() + val leftTime = AttributeReference("leftTime", TimestampType, + metadata = watermarkMetadata)() + val rightTime = AttributeReference("rightTime", TimestampType, + metadata = watermarkMetadata)() + def plus(time: Expression, micros: Long): Expression = + TimestampAddInterval(time, Literal(micros, DayTimeIntervalType())) + val interval = And(GreaterThanOrEqual(rightTime, leftTime), + LessThanOrEqual(rightTime, plus(leftTime, 5000000L))) + def compatible(condition: Expression, consumedSides: Set[JoinSide]): Boolean = + StreamingSymmetricHashJoinHelper.isWatermarkCheckpointCompatible( + Seq(leftKey, leftPrice, leftOther, leftTime), Seq(rightKey, rightPrice, rightTime), + Seq(leftKey), Seq(rightKey), Some(condition), consumedSides) + val both = Set[JoinSide](LeftSide, RightSide) + + // A comparison of columns of both inputs that have no watermark gives no bound. + assert(compatible(And(interval, GreaterThanOrEqual(leftPrice, rightPrice)), both)) + assert(compatible(And(interval, LessThan(Add(leftPrice, Literal(1)), rightPrice)), both)) + // Each half of a BETWEEN is judged on its own: a month interval gives no bound, so the left + // input has none, which is accepted only when nothing after the join reads its event time. + val monthBetween = Between(rightTime, leftTime, + TimestampAddInterval(leftTime, Literal(new CalendarInterval(1, 0, 0L)))) + assert(compatible(monthBetween, Set(RightSide))) + assert(!compatible(monthBetween, Set(LeftSide))) + // A comparison of one input's column with a constant gives a bound in older versions, and so + // does a BETWEEN half that bounds a column other than the event time. + assert(!compatible(And(interval, GreaterThan(leftPrice, Literal(10))), both)) + assert(!compatible(And(interval, GreaterThan(leftTime, Literal(1000000L, TimestampType))), + both)) + assert(!compatible(Between(rightTime, leftTime, leftOther), both)) + assert(!compatible(And(interval, LessThanOrEqual(rightTime, leftOther)), both)) + } + + 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") { + // A run restarted from an emulated old checkpoint produces the same rows as an uninterrupted + // run. The emulated checkpoint holds no NULL-key row, because this version emits such a row + // on arrival; a real older checkpoint can hold one at timestamp 0, which the first batch after + // the restart evicts. The Spark 4.3.0 checkpoint test below covers that stored row. + Seq(false, true).foreach { restart => + withJoinConf(version = 4, logVersion = 2) { + val (leftInput, rightInput, joined) = nullableAlignedJoinInputs() + withTempDir { checkpointDir => + val checkpoint = checkpointDir.getCanonicalPath + val firstBatch: Seq[StreamAction] = Seq( + StartStream(checkpointLocation = checkpoint), + MultiAddData(leftInput, -1, 10)(rightInput, 20), + // A NULL leftTime can never match, so it is emitted at once. + CheckNewAnswer(Row(null, null))) + val laterBatches: Seq[StreamAction] = Seq( + MultiAddData(leftInput, 30)(rightInput, 30), + CheckNewAnswer(Row(30L, 30L)), + MultiAddData(leftInput, 200)(rightInput, 200), + CheckNewAnswer(Row(200L, 200L)), + // The eviction watermark 100 emits the unmatched rows of the first batch. + MultiAddData(leftInput, 300)(rightInput, 300), + CheckNewAnswer(Row(300L, 300L), Row(10L, null), Row(null, 20L)), + StopStream) + if (restart) { + testStream(joined)(firstBatch :+ StopStream: _*) + setMarker(checkpoint, None) + withSQLConf(markerKey -> "0") { + testStream(joined)(StartStream(checkpointLocation = checkpoint) +: laterBatches: _*) + } + assert(pinnedMarker(checkpoint).contains("0")) + } else { + testStream(joined)(firstBatch ++ laterBatches: _*) + } + } + } + } + } + + // Written by Spark 4.3.0 in state format 4 for the full outer join of nullableAlignedJoinInputs. + // Batch 0 added 150 on both inputs, batch 1 added NULL and 160 on the left and 170 on the + // right, and batch 2 added 220 on both inputs. Spark 4.3.0 stored the NULL key at timestamp 0 + // in batch 1, after the scan start had passed it, and never evicted that row. + test("resume a Spark 4.3.0 V4 checkpoint that holds a NULL equality key") { + withJoinConf(version = 4, logVersion = 1) { + val (leftInput, rightInput, joined) = nullableAlignedJoinInputs() + withTempDir { checkpointDir => + copyCheckpointFixture("checkpoint-version-4.3.0-streaming-join-null-equality-key", + checkpointDir) + // One call per batch of the fixture, because a memory stream's offset counts the calls. + Seq(Seq(150), Seq(-1, 160), Seq(220)).foreach(leftInput.addData(_: _*)) + Seq(Seq(150), Seq(170), Seq(220)).foreach(rightInput.addData(_: _*)) + testStream(joined)( + StartStream(checkpointLocation = checkpointDir.getCanonicalPath), + // The watermark of the last batch is 120 seconds, past the timestamp 0 of the NULL key, + // and the first batch of this version scans the index from the start. + MultiAddData(leftInput, 400)(rightInput, 400), + CheckNewAnswer(Row(400L, 400L), Row(null, null)), + // The eviction watermark 300 emits the unmatched rows of batch 1, and not the NULL row + // again. + MultiAddData(leftInput, 600)(rightInput, 600), + CheckNewAnswer(Row(600L, 600L), Row(160L, null), Row(null, 170L)), + StopStream) + assert(pinnedMarker(checkpointDir.getCanonicalPath).contains("0")) + } + } + } + + test("resume old V4 aligned checkpoint when own equality keys are non-null") { + withJoinConf(version = 4, logVersion = 2) { + val (leftInput, rightInput, joined) = nonNullableAlignedJoinInputs() + withTempDir { checkpointDir => + val checkpoint = checkpointDir.getCanonicalPath + testStream(joined)( + StartStream(checkpointLocation = checkpoint), + MultiAddData(leftInput, 10L)(rightInput, 20L), + CheckNewAnswer(), + StopStream) + setMarker(checkpoint, None) + withSQLConf(markerKey -> "0") { + testStream(joined)( + StartStream(checkpointLocation = checkpoint), + MultiAddData(leftInput, 30L)(rightInput, 30L), + CheckNewAnswer(Row(30L, 30L)), + Execute { query => + val join = query.lastExecution.executedPlan.collect { + case j: StreamingSymmetricHashJoinExec => j + }.head + val leftEventTime = join.left.output + .filter(_.metadata.contains(EventTimeWatermark.delayKey)).head + val rightEventTime = join.right.output + .filter(_.metadata.contains(EventTimeWatermark.delayKey)).head + assert(!leftEventTime.nullable, s"Expected non-null left event time: $join") + assert(!rightEventTime.nullable, s"Expected non-null right event time: $join") + assert(join.leftKeys.head.nullable, s"Expected nullable physical left key: $join") + assert(join.rightKeys.head.nullable, s"Expected nullable physical right key: $join") + }, + StopStream) + } + assert(pinnedMarker(checkpoint).contains("0")) + } + } + } + + test("resume old V4 window equality checkpoint") { + withJoinConf(version = 4, logVersion = 2) { + val leftInput = MemoryStream[Int] + val rightInput = MemoryStream[Int] + def windowed(input: MemoryStream[Int]): DataFrame = input.toDF() + .select($"value".as("key"), timestamp_seconds($"value").as("time")) + .withWatermark("time", "10 seconds") + .select($"key", window($"time", "10 seconds")) + // TimeWindow declares the window end nullable, but window() computes it from a non-null + // event time, so old V4 state cannot contain a null selected key timestamp. + val joined = windowed(leftInput).join(windowed(rightInput), Seq("key", "window")) + .select($"key", $"window.end".cast("long")) + withTempDir { checkpointDir => + val checkpoint = checkpointDir.getCanonicalPath + testStream(joined)( + StartStream(checkpointLocation = checkpoint), + MultiAddData(leftInput, 1)(rightInput, 2), + CheckNewAnswer(), + StopStream) + setMarker(checkpoint, None) + withSQLConf(markerKey -> "0") { + testStream(joined)( + StartStream(checkpointLocation = checkpoint), + MultiAddData(leftInput, 30)(rightInput, 30), + CheckNewAnswer(Row(30, 40L)), + StopStream) + } + assert(pinnedMarker(checkpoint).contains("0")) + } + } + } + + Seq(2, 4).foreach { version => + test(s"reject an incompatible checkpoint retrying batch zero, V$version") { + withJoinConf(version, logVersion = 1) { + val (leftInput, rightInput, joined) = joinInputs("range") + withTempDir { checkpointDir => + val checkpoint = checkpointDir.getCanonicalPath + testStream(joined)( + StartStream(checkpointLocation = checkpoint), + MultiAddData(leftInput, (1, 10))(rightInput, (1, 10)), + CheckNewAnswer(Row(1, 1)), + StopStream) + val offsets = new OffsetSeqLog(spark, checkpoint + "/offsets") + assert(offsets.getLatest().get._1 == 0L) + setMarker(checkpoint, None) + // Emulate a crash after state was written but before the first batch committed. + val commit = new Path(checkpoint, "commits/0") + assert(commit.getFileSystem(spark.sessionState.newHadoopConf()).delete(commit, false)) + val before = snapshot(new File(checkpoint, "state")) + val commitsBefore = snapshot(new File(checkpoint, "commits")) + testStream(joined)( + StartStream(checkpointLocation = checkpoint), + ExpectFailure[AnalysisException](assertFailure = error => { + checkError(error.asInstanceOf[AnalysisException], + condition = "STREAMING_JOIN_CHECKPOINT_INCOMPATIBLE", + parameters = Map( + "joinCondition" -> ".*leftKey.*rightKey.*leftTime.*rightTime.*", + "leftWatermarkColumns" -> "none", + "rightWatermarkColumns" -> "rightTime"), + matchPVals = true) + })) + assert(snapshot(new File(checkpoint, "state")) == before) + assert(snapshot(new File(checkpoint, "commits")) == commitsBefore) + } + } + } + } + + private val intervalCondition = + "leftKey = rightKey AND rightTime >= leftTime AND rightTime <= leftTime + INTERVAL 5 SECONDS" + + // Old state of a two-sided time-interval join on the inputs' own event times is reusable, and + // so is that of a join whose unbounded input's event time no later stateful operator reads, + // such as a one-directional interval join or a key-only join; shapes that only resemble them + // are not. + Seq( + // (shape, join condition, state format versions, session time zone, join type, accepted) + ("two-sided interval", intervalCondition, Seq(1, 2, 3, 4), "America/Los_Angeles", + "inner", true), + ("two-sided interval with the shift on the stored side", + "leftKey = rightKey AND leftTime + INTERVAL 5 SECONDS >= rightTime AND " + + "leftTime <= rightTime", Seq(2), "America/Los_Angeles", "inner", true), + ("BETWEEN interval", + "leftKey = rightKey AND rightTime BETWEEN leftTime AND leftTime + INTERVAL 5 SECONDS", + Seq(2, 4), "America/Los_Angeles", "left_outer", true), + // Both versions count a day as 24 hours in every time zone, so whole days keep their cutoffs. + ("whole-day interval in a fixed-offset time zone", + "leftKey = rightKey AND rightTime >= leftTime AND rightTime <= leftTime + INTERVAL 1 DAY", + Seq(2, 4), "UTC", "inner", true), + ("whole-day interval in a daylight saving time zone", + "leftKey = rightKey AND rightTime >= leftTime AND rightTime <= leftTime + INTERVAL 1 DAY", + Seq(2, 4), "America/Los_Angeles", "inner", true), + ("24-hour interval in a daylight saving time zone", + "leftKey = rightKey AND rightTime >= leftTime AND rightTime <= leftTime + INTERVAL 24 HOURS", + Seq(2), "America/Los_Angeles", "left_outer", true), + // An inner join evaluates a one-input conjunct below the join, so it is not in the condition. + ("interval with a constant conjunct below an inner join", + intervalCondition + " AND leftTime > timestamp_seconds(1)", Seq(2), + "America/Los_Angeles", "inner", true), + // Neither version bounds the right input; nothing after this join reads its event time. + ("one-directional interval", + "leftKey = rightKey AND rightTime <= leftTime + INTERVAL 5 SECONDS", Seq(2, 4), + "America/Los_Angeles", "inner", true), + // A month has no fixed length, so neither version reads that conjunct, and neither bounds + // the left input. Nothing after this join reads its event time. + ("month interval", + "leftKey = rightKey AND rightTime >= leftTime AND rightTime <= leftTime + INTERVAL 1 MONTH", + Seq(2), "UTC", "inner", true), + // Neither version derives a bound from a comparison of columns without a watermark. + ("interval with a comparison of other columns of both inputs", + intervalCondition + " AND leftKey <= rightKey + 1", Seq(2, 4), "America/Los_Angeles", + "left_outer", true), + // Both versions read a cast of an event time with its own watermark as the event time. + ("interval with a cast", + "leftKey = rightKey AND CAST(rightTime AS BIGINT) >= CAST(leftTime AS BIGINT) AND " + + "rightTime <= leftTime + INTERVAL 5 SECONDS", Seq(2, 4), "America/Los_Angeles", "inner", + true), + ("interval with casts and numeric constants", + "leftKey = rightKey AND CAST(rightTime AS BIGINT) >= CAST(leftTime AS BIGINT) - 1 AND " + + "CAST(rightTime AS BIGINT) <= CAST(leftTime AS BIGINT) + 5", Seq(2), "UTC", "inner", + true), + ("interval with a negated event time", + "leftKey = rightKey AND CAST(rightTime AS BIGINT) >= 20 - CAST(leftTime AS BIGINT) AND " + + "rightTime <= leftTime + INTERVAL 5 SECONDS", Seq(2), "UTC", "inner", false), + ("interval with a constant conjunct in a left outer join", + intervalCondition + " AND leftTime > timestamp_seconds(1)", Seq(2), + "America/Los_Angeles", "left_outer", false), + // Older versions evicted the left input at the unshifted watermark, too early for a key + // shifted backward on the right. + ("interval with a backward-shifted event-time key", + "leftKey = rightKey AND leftTime = rightTime - INTERVAL 4 SECONDS AND " + + "rightTime >= leftTime - INTERVAL 5 SECONDS", Seq(2), "America/Los_Angeles", "inner", + false), + // A forward shift keeps old state reusable; nothing after this join reads leftTime. + ("interval with a forward-shifted event-time key", + "leftKey = rightKey AND leftTime + INTERVAL 4 SECONDS = rightTime AND " + + "rightTime >= leftTime", Seq(2, 4), "America/Los_Angeles", "inner", true), + // Neither version evicts a key-only join; nothing after this one reads its output watermark. + ("key-only join keeping both event times", "leftKey = rightKey", Seq(2, 4), + "America/Los_Angeles", "inner", true) + ).foreach { case (shape, condition, versions, timeZone, joinType, accepted) => + versions.foreach { version => + val action = if (accepted) "resume" else "reject" + test(s"$action old $shape checkpoint, V$version") { + withJoinConf(version, logVersion = 1) { + withSQLConf(SQLConf.SESSION_LOCAL_TIMEZONE.key -> timeZone) { + val leftInput = MemoryStream[(Int, Int)] + val rightInput = MemoryStream[(Int, Int)] + // A negative time is a null event time, so the event times are nullable. + val left = leftInput.toDF().toDF("leftKey", "time") + .select($"leftKey", when($"time" < 0, lit(null).cast(TimestampType)) + .otherwise(timestamp_seconds($"time")).as("leftTime")) + .withWatermark("leftTime", "5 seconds") + val right = rightInput.toDF().toDF("rightKey", "time") + .select($"rightKey", timestamp_seconds($"time").as("rightTime")) + .withWatermark("rightTime", "5 seconds") + val joined = left.join(right, expr(condition), joinType) + .select($"leftKey", $"rightKey", $"leftTime".cast("long"), + $"rightTime".cast("long")) + withTempDir { checkpointDir => + val checkpoint = checkpointDir.getCanonicalPath + testStream(joined)( + StartStream(checkpointLocation = checkpoint), + MultiAddData(leftInput, (1, 10), (2, -1))(rightInput, (3, 12)), + ProcessAllAvailable(), + StopStream) + setMarker(checkpoint, None) + if (accepted) { + testStream(joined)( + StartStream(checkpointLocation = checkpoint), + AddData(rightInput, (1, 14)), + CheckNewAnswer(Row(1, 1, 10L, 14L)), + StopStream) + assert(pinnedMarker(checkpoint).contains("0")) + } else { + val stateBefore = snapshot(new File(checkpoint, "state")) + testStream(joined)( + StartStream(checkpointLocation = checkpoint), + AddData(rightInput, (1, 14)), + ExpectFailure[AnalysisException](assertFailure = error => { + checkError(error.asInstanceOf[AnalysisException], + condition = "STREAMING_JOIN_CHECKPOINT_INCOMPATIBLE", + parameters = Map( + "joinCondition" -> ".*leftKey.*rightKey.*", + "leftWatermarkColumns" -> "leftTime", + "rightWatermarkColumns" -> "rightTime"), + matchPVals = true) + })) + assert(snapshot(new File(checkpoint, "state")) == stateBefore) + } + } + } + } + } + } + } + + // The scan start of each side of a V4 join, in left, right order. + private def scanStarts(join: StreamingSymmetricHashJoinExec): Seq[Option[Long]] = { + Seq(join.stateWatermarkPredicates.left, join.stateWatermarkPredicates.right).map { + case Some(p: JoinStateKeyWatermarkPredicate) => p.prevStateWatermark + case Some(p: JoinStateValueWatermarkPredicate) => p.prevStateWatermark + case _ => None + } + } + + private def joinsOf(query: StreamExecution): Seq[StreamingSymmetricHashJoinExec] = { + query.lastExecution.executedPlan.collect { case j: StreamingSymmetricHashJoinExec => j } + } + + // The first batch of every run of an older-generation checkpoint re-simulates the previous + // batch with this version's output watermarks, which the older version may not have evicted + // with, so that batch scans V4 join state from the start. The pinned marker does not advance, + // so a second run does the same. Later batches use scan starts again. + Seq(true, false).foreach { olderGeneration => + test(s"V4 scan start in the first batch after a restart, older generation=$olderGeneration") { + withJoinConf(version = 4, logVersion = 2) { + val leftInput = MemoryStream[(Int, Int)] + val rightInput = MemoryStream[(Int, Int)] + val left = leftInput.toDF().toDF("leftKey", "time") + .select($"leftKey", timestamp_seconds($"time").as("leftTime")) + .withWatermark("leftTime", "5 seconds") + val right = rightInput.toDF().toDF("rightKey", "time") + .select($"rightKey", timestamp_seconds($"time").as("rightTime")) + .withWatermark("rightTime", "5 seconds") + val joined = left.join(right, expr(intervalCondition), "left_outer") + .select($"leftKey", $"rightKey", $"leftTime".cast("long"), $"rightTime".cast("long")) + def assertScanStarts(defined: Boolean): AssertOnQuery = Execute { query => + val join = joinsOf(query).head + assert(scanStarts(join).forall(_.isDefined == defined), s"Unexpected scan starts: $join") + } + withTempDir { checkpointDir => + val checkpoint = checkpointDir.getCanonicalPath + testStream(joined)( + StartStream(checkpointLocation = checkpoint), + MultiAddData(leftInput, (1, 10), (2, 20))(rightInput, (3, 30)), + ProcessAllAvailable(), + MultiAddData(leftInput, (4, 40))(rightInput, (5, 40)), + ProcessAllAvailable(), + assertScanStarts(defined = true), + StopStream) + if (olderGeneration) { + setMarker(checkpoint, None) + } + Seq(50, 70).foreach { time => + testStream(joined)( + StartStream(checkpointLocation = checkpoint), + AddData(rightInput, (6, time)), + ProcessAllAvailable(), + assertScanStarts(defined = !olderGeneration), + AddData(rightInput, (7, time + 10)), + ProcessAllAvailable(), + assertScanStarts(defined = true), + StopStream) + assert(pinnedMarker(checkpoint).contains(if (olderGeneration) "0" else currentMarker)) + } + } + } + } + } + + // An upstream join's output watermark depends on the plan above it. Here a stream-static left + // outer join between the two joins hides the downstream join from the tracer, so the upstream + // join holds back its output watermark for its unbounded click input, at 0, and the downstream + // left outer join evicts nothing. Removing the stream-static join between runs lets the tracer + // reach the impression time, which raises the re-simulated watermark of the previous batch. + // The downstream join must then scan from the start in the first batch, or it would never emit + // impressions buffered below that watermark. The upstream join has no join below it and keeps + // its scan start. + test("V4 chained joins scan from the start after the plan between them changes") { + withJoinConf(version = 4, logVersion = 2) { + val impressionInput = MemoryStream[(Int, Int)] + val clickInput = MemoryStream[(Int, Int)] + val conversionInput = MemoryStream[(Int, Int)] + val impressions = impressionInput.toDF().toDF("impressionKey", "time") + .select($"impressionKey", timestamp_seconds($"time").as("impressionTime")) + .withWatermark("impressionTime", "0 seconds") + val clicks = clickInput.toDF().toDF("clickKey", "time") + .select($"clickKey", timestamp_seconds($"time").as("clickTime")) + .withWatermark("clickTime", "0 seconds") + val conversions = conversionInput.toDF().toDF("conversionKey", "time") + .select($"conversionKey", timestamp_seconds($"time").as("conversionTime")) + .withWatermark("conversionTime", "0 seconds") + val clicked = impressions.join(clicks, expr("impressionKey = clickKey AND " + + "clickTime <= impressionTime + INTERVAL 10 SECONDS")) + .select($"impressionKey", $"impressionTime") + // A left anti join here would be pushed below the upstream join; an outer join is not. + val campaigns = Seq(-1).toDF("campaignKey") + def converted(withCampaigns: Boolean): DataFrame = { + val upstream = if (withCampaigns) { + clicked.join(campaigns, $"impressionKey" === $"campaignKey", "left_outer") + .drop("campaignKey") + } else { + clicked + } + upstream.join(conversions, expr("impressionKey = conversionKey AND " + + "conversionTime BETWEEN impressionTime AND impressionTime + INTERVAL 5 SECONDS"), + "left_outer") + .select($"impressionKey", $"impressionTime".cast("long"), $"conversionKey", + $"conversionTime".cast("long")) + } + def addAll( + impression: (Int, Int), + click: (Int, Int), + conversion: (Int, Int)): StreamAction = + MultiAddData((impressionInput, Seq(impression)), (clickInput, Seq(click)), + (conversionInput, Seq(conversion))) + def assertScanStarts(upstream: Boolean, downstream: Boolean): AssertOnQuery = + Execute { query => + val Seq(downstreamJoin, upstreamJoin) = joinsOf(query) + // The click side of the upstream join has no bound and no scan start. + assert(scanStarts(upstreamJoin).head.isDefined == upstream, s"$upstreamJoin") + assert(scanStarts(downstreamJoin).forall(_.isDefined == downstream), s"$downstreamJoin") + } + withTempDir { checkpointDir => + val checkpoint = checkpointDir.getCanonicalPath + testStream(converted(withCampaigns = true))( + StartStream(checkpointLocation = checkpoint), + addAll((1, 10), (1, 10), (5, 10)), + CheckNewAnswer(), + addAll((2, 100), (2, 100), (6, 100)), + CheckNewAnswer(), + AddData(conversionInput, (7, 101)), + // The upstream join holds the downstream input watermark at 0, so nothing is evicted. + CheckNewAnswer(), + StopStream) + testStream(converted(withCampaigns = false))( + StartStream(checkpointLocation = checkpoint), + addAll((3, 200), (3, 200), (8, 200)), + // The re-simulated watermark of the previous batch is 100 seconds less 10 seconds and + // 1 ms. The impression at 10 seconds lies below the scan start it would give. + CheckNewAnswer(Row(1, 10L, null, null)), + assertScanStarts(upstream = true, downstream = false), + AddData(conversionInput, (9, 201)), + CheckNewAnswer(Row(2, 100L, null, null)), + assertScanStarts(upstream = true, downstream = true), + StopStream) + } + } + } + + // Written by Spark 4.3.0 in state format 4: the left outer join below on a left input whose + // event time can be NULL. Batch 0 added (key 1, 100 s) on the left and (key 1, 102 s) on the + // right, batch 1 added (key 3, 150 s) and (key 3, 152 s), and batch 2 added (key 2, NULL) and + // (key 4, 300 s) on the left and (key 4, 302 s) on the right. Spark 4.3.0 stored the NULL event + // time at timestamp 0 in batch 2, after its scan start had passed 0, and never evicted that row. + // The first batch of this version scans the index from the start and emits it. + test("resume a Spark 4.3.0 V4 checkpoint that holds a row with a NULL event time") { + withJoinConf(version = 4, logVersion = 1) { + val leftInput = MemoryStream[(Int, Int)] + val rightInput = MemoryStream[(Int, Int)] + val left = leftInput.toDF().toDF("leftKey", "time") + .select($"leftKey", when($"time" >= 0, timestamp_seconds($"time")).as("leftTime")) + .withWatermark("leftTime", "5 seconds") + val right = rightInput.toDF().toDF("rightKey", "time") + .select($"rightKey", timestamp_seconds($"time").as("rightTime")) + .withWatermark("rightTime", "5 seconds") + val joined = left.join(right, expr(intervalCondition), "left_outer") + .select($"leftKey", $"rightKey", $"leftTime".cast("long"), $"rightTime".cast("long")) + withTempDir { checkpointDir => + copyCheckpointFixture("checkpoint-version-4.3.0-streaming-join-null-event-time", + checkpointDir) + // One call per batch of the fixture, because a memory stream's offset counts the calls. + Seq(Seq((1, 100)), Seq((3, 150)), Seq((2, -1), (4, 300))) + .foreach(leftInput.addData(_: _*)) + Seq(Seq((1, 102)), Seq((3, 152)), Seq((4, 302))).foreach(rightInput.addData(_: _*)) + testStream(joined)( + StartStream(checkpointLocation = checkpointDir.getCanonicalPath), + // The watermark of the last batch is 295 seconds, past the timestamp 0 of the NULL row. + AddData(rightInput, (5, 400)), + CheckNewAnswer(Row(2, null, null, null)), + AddData(rightInput, (6, 500)), + CheckNewAnswer(), + StopStream) + assert(pinnedMarker(checkpointDir.getCanonicalPath).contains("0")) + } + } + } + + // A one-directional interval join leaves the right input unbounded in both versions, and a + // month interval leaves the left input unbounded, so the checkpoint is reusable only when no + // stateful operator after the join reads the unbounded input's event time. + Seq( + ("one-directional interval", "rightTime <= leftTime + INTERVAL 5 SECONDS", "leftTime", true), + ("one-directional interval", "rightTime <= leftTime + INTERVAL 5 SECONDS", "rightTime", + false), + ("month interval", "rightTime BETWEEN leftTime AND leftTime + INTERVAL 1 MONTH", + "rightTime", true), + ("month interval", "rightTime BETWEEN leftTime AND leftTime + INTERVAL 1 MONTH", + "leftTime", false) + ).foreach { case (shape, timeCondition, timeColumn, accepted) => + val action = if (accepted) "resume" else "reject" + test(s"$action old $shape checkpoint deduplicated on $timeColumn") { + withJoinConf(version = 4, logVersion = 1) { + val leftInput = MemoryStream[(Int, Int)] + val rightInput = MemoryStream[(Int, Int)] + val left = leftInput.toDF().toDF("leftKey", "time") + .select($"leftKey", timestamp_seconds($"time").as("leftTime")) + .withWatermark("leftTime", "5 seconds") + val right = rightInput.toDF().toDF("rightKey", "time") + .select($"rightKey", timestamp_seconds($"time").as("rightTime")) + .withWatermark("rightTime", "5 seconds") + val deduplicated = left.join(right, expr(s"leftKey = rightKey AND $timeCondition")) + .select($"leftKey", col(timeColumn).as("t")) + .dropDuplicates("leftKey", "t") + .select($"leftKey", $"t".cast("long")) + withTempDir { checkpointDir => + val checkpoint = checkpointDir.getCanonicalPath + testStream(deduplicated)( + StartStream(checkpointLocation = checkpoint), + MultiAddData(leftInput, (1, 10))(rightInput, (3, 12)), + ProcessAllAvailable(), + StopStream) + setMarker(checkpoint, None) + if (accepted) { + testStream(deduplicated)( + StartStream(checkpointLocation = checkpoint), + AddData(rightInput, (1, 14)), + CheckNewAnswer(Row(1, if (timeColumn == "leftTime") 10L else 14L)), + StopStream) + assert(pinnedMarker(checkpoint).contains("0")) + } else { + val stateBefore = snapshot(new File(checkpoint, "state")) + testStream(deduplicated)( + StartStream(checkpointLocation = checkpoint), + AddData(rightInput, (1, 14)), + ExpectFailure[AnalysisException](assertFailure = error => { + assert(error.asInstanceOf[AnalysisException].getCondition == + "STREAMING_JOIN_CHECKPOINT_INCOMPATIBLE") + })) + assert(snapshot(new File(checkpoint, "state")) == stateBefore) + } + } + } + } + } + + // A join that neither version bounds on one input keeps its checkpoint when no stateful + // operator after it uses its watermark: one with no event-time column in its input, no + // event-time timeouts and no user code that can read the watermark. + Seq( + ("key-only join", "leftKey = rightKey", "count", true), + ("one-directional interval", + "leftKey = rightKey AND rightTime <= leftTime + INTERVAL 5 SECONDS", "count", true), + ("key-only join", "leftKey = rightKey", "window count", false), + ("key-only join", "leftKey = rightKey", "processing-time transformWithState", false) + ).foreach { case (shape, condition, downstream, accepted) => + val action = if (accepted) "resume" else "reject" + test(s"$action old $shape checkpoint followed by an update-mode $downstream") { + withJoinConf(version = 4, logVersion = 1) { + val leftInput = MemoryStream[(Int, Int)] + val rightInput = MemoryStream[(Int, Int)] + val left = leftInput.toDF().toDF("leftKey", "time") + .select($"leftKey", timestamp_seconds($"time").as("leftTime")) + .withWatermark("leftTime", "5 seconds") + val right = rightInput.toDF().toDF("rightKey", "time") + .select($"rightKey", timestamp_seconds($"time").as("rightTime")) + .withWatermark("rightTime", "5 seconds") + val joined = left.join(right, expr(condition)) + // Each operator reads leftTime, so the join keeps its event-time columns, but only the + // window count reads it as an event time. + val counted = downstream match { + case "count" => + joined.groupBy($"leftKey").agg(count($"leftTime".cast("long")).as("count")) + case "window count" => + joined.groupBy(window($"leftTime", "10 seconds"), $"leftKey").count() + .select($"leftKey", $"count") + case _ => + joined.select(concat_ws(":", $"leftKey", $"leftTime".cast("long"))).as[String] + .groupByKey(identity) + .transformWithState(new RunningCountStatefulProcessor(), TimeMode.ProcessingTime(), + OutputMode.Update()) + .toDF("key", "count") + .select(split($"key", ":")(0).cast("int"), $"count".cast("long")) + } + withTempDir { checkpointDir => + val checkpoint = checkpointDir.getCanonicalPath + testStream(counted, OutputMode.Update())( + StartStream(checkpointLocation = checkpoint), + MultiAddData(leftInput, (1, 10))(rightInput, (1, 10)), + CheckNewAnswer(Row(1, 1L)), + StopStream) + setMarker(checkpoint, None) + if (accepted) { + testStream(counted, OutputMode.Update())( + StartStream(checkpointLocation = checkpoint), + AddData(rightInput, (1, 14)), + CheckNewAnswer(Row(1, 2L)), + StopStream) + assert(pinnedMarker(checkpoint).contains("0")) + } else { + val stateBefore = snapshot(new File(checkpoint, "state")) + testStream(counted, OutputMode.Update())( + StartStream(checkpointLocation = checkpoint), + AddData(rightInput, (1, 14)), + ExpectFailure[AnalysisException](assertFailure = error => { + assert(error.asInstanceOf[AnalysisException].getCondition == + "STREAMING_JOIN_CHECKPOINT_INCOMPATIBLE") + })) + assert(snapshot(new File(checkpoint, "state")) == stateBefore) + } + } + } + } + } + + // For an equality key that shifts one input's event time forward, older versions evicted both + // sides at the unshifted watermark: the cutoff this version uses for the shifted side, and at + // or below the one it uses for the other side. Old state is reusable when no stateful operator + // after the join reads the shifted input's event time, whose output watermark bound changed. + Seq( + // (shape, join condition, left time, right time, deduplicated column, versions, accepted) + ("forward shift", "leftTime = rightTime + INTERVAL 10 SECONDS", 20, 10, None, + Seq(1, 2, 3, 4), true), + ("forward timestampadd shift", "leftTime = timestampadd(SECOND, 10, rightTime)", 20, 10, + None, Seq(2, 4), true), + ("forward whole-day shift", "leftTime = rightTime + INTERVAL 1 DAY", 86410, 10, None, + Seq(2, 4), true), + ("forward shift on the left key", "leftTime + INTERVAL 10 SECONDS = rightTime", 10, 20, + None, Seq(2, 4), true), + ("forward shift deduplicated on the unshifted time", + "leftTime = rightTime + INTERVAL 10 SECONDS", 20, 10, Some("leftTime"), Seq(2, 4), true), + ("forward shift deduplicated on the shifted time", + "leftTime = rightTime + INTERVAL 10 SECONDS", 20, 10, Some("rightTime"), Seq(2, 4), false), + ("backward shift", "leftTime = rightTime - INTERVAL 10 SECONDS", 10, 20, None, Seq(2, 4), + false), + ("shift on both keys", "leftTime + INTERVAL 1 SECOND = rightTime + INTERVAL 11 SECONDS", 20, + 10, None, Seq(2, 4), false) + ).foreach { case (shape, timeCondition, leftTime, rightTime, deduplicated, versions, + accepted) => + for { + version <- versions + joinType <- if (version == 1) Seq("inner") else Seq("inner", "left_outer") + } { + val action = if (accepted) "resume" else "reject" + test(s"$action old $shape equality checkpoint, $joinType, V$version") { + withJoinConf(version, logVersion = 1) { + val leftInput = MemoryStream[(Int, Int)] + val rightInput = MemoryStream[(Int, Int)] + val left = leftInput.toDF().toDF("leftKey", "time") + .select($"leftKey", timestamp_seconds($"time").as("leftTime")) + .withWatermark("leftTime", "5 seconds") + val right = rightInput.toDF().toDF("rightKey", "time") + .select($"rightKey", timestamp_seconds($"time").as("rightTime")) + .withWatermark("rightTime", "5 seconds") + val joined = left.join(right, expr(s"leftKey = rightKey AND $timeCondition"), joinType) + val result = deduplicated match { + case Some(column) => + joined.select($"leftKey", col(column).as("t")).dropDuplicates("leftKey", "t") + .select($"leftKey", $"t".cast("long")) + case None => + joined.select($"leftKey", $"rightKey", $"leftTime".cast("long"), + $"rightTime".cast("long")) + } + def expected(key: Int): Row = deduplicated match { + case Some("leftTime") => Row(key, leftTime.toLong) + case Some(_) => Row(key, rightTime.toLong) + case None => Row(key, key, leftTime.toLong, rightTime.toLong) + } + withTempDir { checkpointDir => + val checkpoint = checkpointDir.getCanonicalPath + // Each row waits in state for its match, which arrives after the restart. + testStream(result)( + StartStream(checkpointLocation = checkpoint), + MultiAddData(leftInput, (1, leftTime))(rightInput, (2, rightTime)), + CheckNewAnswer(), + StopStream) + setMarker(checkpoint, None) + if (accepted) { + testStream(result)( + StartStream(checkpointLocation = checkpoint), + MultiAddData(leftInput, (2, leftTime))(rightInput, (1, rightTime)), + CheckNewAnswer(expected(1), expected(2)), + StopStream) + assert(pinnedMarker(checkpoint).contains("0")) + } else { + val stateBefore = snapshot(new File(checkpoint, "state")) + testStream(result)( + StartStream(checkpointLocation = checkpoint), + MultiAddData(leftInput, (2, leftTime))(rightInput, (1, rightTime)), + ExpectFailure[AnalysisException](assertFailure = error => { + assert(error.asInstanceOf[AnalysisException].getCondition == + "STREAMING_JOIN_CHECKPOINT_INCOMPATIBLE") + })) + assert(snapshot(new File(checkpoint, "state")) == stateBefore) + } + } + } + } + } + } + + // Earlier versions stored a row whose eviction column is NULL and never evicted it from V1 to + // V3 state. Here the first run has no watermark on the left input, so nothing bounds the left + // state and this version stores the NULL-time left row the same way. After the restart with + // the watermark, V1 to V3 eviction must remove that row and emit it padded with nulls. + Seq(2, 3).foreach { version => + test(s"evict a restored left row with a NULL event time, V$version") { + withJoinConf(version, logVersion = 1) { + val leftInput = MemoryStream[(Int, Int)] + val rightInput = MemoryStream[(Int, Int)] + def joined(leftWatermark: Boolean): DataFrame = { + // A negative time is a null event time. + val leftData = leftInput.toDF().toDF("leftKey", "time") + .select($"leftKey", when($"time" < 0, lit(null).cast(TimestampType)) + .otherwise(timestamp_seconds($"time")).as("leftTime")) + val left = + if (leftWatermark) leftData.withWatermark("leftTime", "5 seconds") else leftData + val right = rightInput.toDF().toDF("rightKey", "time") + .select($"rightKey", timestamp_seconds($"time").as("rightTime")) + .withWatermark("rightTime", "5 seconds") + left.join(right, expr(intervalCondition), "left_outer") + .select($"leftKey", $"rightKey", $"leftTime".cast("long"), $"rightTime".cast("long")) + } + withTempDir { checkpointDir => + val checkpoint = checkpointDir.getCanonicalPath + testStream(joined(leftWatermark = false))( + StartStream(checkpointLocation = checkpoint), + MultiAddData(leftInput, (1, -1), (2, 10))(rightInput, (2, 12)), + CheckNewAnswer(Row(2, 2, 10L, 12L)), + StopStream) + testStream(joined(leftWatermark = true))( + StartStream(checkpointLocation = checkpoint), + AddData(rightInput, (3, 30)), + CheckNewAnswer(Row(1, null, null, null)), + StopStream) + } + } + } + } + + // Both bundled historical join checkpoints are two-sided time-interval joins on the inputs' + // own event times, so they resume. No historical equality-join checkpoint is bundled. Review Comment: **Nit (P3):** This suite also restores two bundled Spark 4.3.0 checkpoints: `checkpoint-version-4.3.0-streaming-join-null-equality-key`, a full outer join on `leftTime = rightTime` restored at line 507, and `checkpoint-version-4.3.0-streaming-join-null-event-time` at line 925. The second sentence is therefore no longer true, and the first covers only the two checkpoints that these tests restore. ```suggestion // The bundled Spark 2.4.0 and 3.5.1 join checkpoints are two-sided time-interval joins on the // inputs' own event times, so they resume. ``` **Verification:** - **Inspection:** Every statement in the compatibility suite about which historical checkpoints are bundled matches the checkpoint fixtures it copies. -- 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]
