spark-test commented on code in PR #60713: URL: https://github.com/apache/spark/pull/60713#discussion_r4662124500
########## docs/streaming/ss-migration-guide.md: ########## @@ -23,6 +23,18 @@ Note that this migration guide describes the items specific to Structured Stream Many items of SQL migration can be applied when migrating Structured Streaming to higher versions. Please refer [Migration Guide: SQL, Datasets and DataFrame](../sql-migration-guide.html). +## Upgrading from Structured Streaming 4.4 to 4.5 + +- Since Spark 4.5, a new streaming query in append mode fails when its first micro-batch is + planned if an operator that drops late rows, such as a window aggregation, follows a + stream-stream join and its event time can come from an input of the join whose state is never + evicted, for example an input of a join on a key without a watermark and without a time range + on that input. Such a query could drop joined rows as late. The check follows the event time + down to the join through projections and the operators that pass their input's columns + through, and also fails a query whose path to the join passes another stateful operator. Add a Review Comment: **Nit (P3):** Besides another stateful operator, the check also gives up, counting every input of the join, when the path reaches the join only through a later input of a union, because a union outputs its first input's attributes and the trace follows only that input, and when no single input of a node outputs all the traced columns. For example, a stream `o` with its own watermark, unioned with the one-sided range join narrowed to `leftKey` and `leftTime` and followed by a window count, has no stateful operator on the path and reads only the bounded input's time through the union, yet by the review's reading of the code it fails naming the right input. A user with such a query finds no matching case in this entry, and its only remedy, a range that bounds the right input, changes which rows the join matches. The entry also never names `spark.sql.streaming.statefulOperator.checkCorrectness.enabled`, which runs such a query unchanged with a warning; the PR description states it, an d the 3.1 entry for the chained-operator check that this check extends names the same switch. This extends an [existing discussion](https://github.com/apache/spark/pull/60713#discussion_r4644703725). **Verification:** - **Inspection:** The 4.5 migration entry lists every kind of path on which the shipped check gives up, lists a later input of a union only if the check still gives up there, and says that setting spark.sql.streaming.statefulOperator.checkCorrectness.enabled to false runs such a query with a warning and also turns the older chained-operator check into a warning. ########## sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationsSuite.scala: ########## @@ -1066,7 +1067,98 @@ class UnsupportedOperationsSuite extends SparkFunSuite with SQLHelper { Update ) - private def scalaTransformWithState(child: LogicalPlan): TransformWithState = { + // A key-only join of two watermarked inputs, so the state of either input has no cutoff. + private val (leftKey, rightKey, thirdKey) = ( + AttributeReference("lk", IntegerType)(), AttributeReference("rk", IntegerType)(), + AttributeReference("tk", IntegerType)()) + private val Seq(leftTime, rightTime, thirdTime) = Seq("lt", "rt", "tt").map( + AttributeReference(_, TimestampType, metadata = watermarkMetadata)()) + private def joinOf(left: Seq[Attribute], right: Seq[Attribute], condition: Expression) = + Join(TestStreamingRelation(left), TestStreamingRelation(right), Inner, Some(condition), + JoinHint.NONE) + private val keyOnlyJoin = + joinOf(Seq(leftKey, leftTime), Seq(rightKey, rightTime), leftKey === rightKey) + .select(leftKey, leftTime) + + // Each operator that drops late rows rejects the key-only join, naming its left input. + Seq[(String, LogicalPlan => LogicalPlan, Boolean)]( + ("flatMapGroupsWithState with an event-time timeout", child => TestFlatMapGroupsWithState( + null, att, att, Seq(att), Seq(att), att, null, Append, isMapGroupsWithState = false, + GroupStateTimeout.EventTimeTimeout, child), true), + ("flatMapGroupsWithState without a timeout", child => TestFlatMapGroupsWithState( + null, att, att, Seq(att), Seq(att), att, null, Append, isMapGroupsWithState = false, + GroupStateTimeout.NoTimeout, child), false), + ("applyInPandasWithState with an event-time timeout", FlatMapGroupsInPandasWithState( + Literal(1), Seq(leftKey), Seq(att), new StructType(), Append, + GroupStateTimeout.EventTimeTimeout, _), true), + ("applyInPandasWithState without a timeout", FlatMapGroupsInPandasWithState( + Literal(1), Seq(leftKey), Seq(att), new StructType(), Append, + GroupStateTimeout.NoTimeout, _), false), + ("transformWithState in event-time mode", scalaTransformWithState(_, EventTime), true), + ("transformWithState in processing-time mode", + scalaTransformWithState(_, ProcessingTime), false), + ("transformWithStateInPandas in event-time mode", pythonTransformWithState(_, EventTime), + true), + ("transformWithStateInPandas in processing-time mode", + pythonTransformWithState(_, ProcessingTime), false), + ("dropDuplicatesWithinWatermark", DeduplicateWithinWatermark(Seq(leftKey), _), true), + ("a stream-stream join", + Join(_, TestStreamingRelation(Seq(thirdKey, thirdTime)), Inner, + Some(leftKey === thirdKey), JoinHint.NONE), true) + ).foreach { case (name, operator, rejected) => + test(s"join output watermark: key-only join before $name") { + val check = () => UnsupportedOperationChecker.checkStreamStreamJoinOutputWatermark( + operator(keyOnlyJoin), Append) + if (rejected) { + val e = intercept[AnalysisException](check()) + assert(e.getMessage.contains( + "the state of the left input of a stream-stream join has no cutoff")) + } else { + check() + } + } + } + + // Each of these passes only because of one condition: the left semi join emits only its left + // input, an operator whose input has no event time filters no joined row, and a join input + // without an event time emits none. A union with the same child twice is a path that the trace + // cannot follow. + Seq[(String, LogicalPlan)]( + "a left semi join bounded on its left input" -> Aggregate(Seq(leftTime), Seq(leftTime), { + val semi = Join(TestStreamingRelation(Seq(leftKey, leftTime)), + TestStreamingRelation(Seq(rightKey, rightTime)), LeftSemi, + Some(leftKey === rightKey && leftTime > rightTime), JoinHint.NONE) + Union(Seq(semi, semi)) + }), + "an operator whose input has no event time" -> + Deduplicate(Seq(leftKey), Aggregate(Seq(leftKey), Seq(leftKey), keyOnlyJoin)), + "a watermark above a join of inputs without one" -> { + val (lt, rt) = (leftTime.withMetadata(Metadata.empty), rightTime.withMetadata(Metadata.empty)) + val watermarked = EventTimeWatermark(java.util.UUID.randomUUID(), lt, + new CalendarInterval(0, 0, 1000000L), + joinOf(Seq(leftKey, lt), Seq(rightKey, rt), leftKey === rightKey)) + val time = watermarked.output.find(_.semanticEquals(lt)).get + Aggregate(Seq(time), Seq(time), watermarked) + } + ).foreach { case (name, plan) => + test(s"join output watermark: accept $name") { + UnsupportedOperationChecker.checkStreamStreamJoinOutputWatermark(plan, Append) + } + } + + // Planning rejects this join with its own error. + test("join output watermark: a stream-stream join without an equality predicate") { + UnsupportedOperationChecker.checkStreamStreamJoinOutputWatermark(Aggregate(Seq(leftTime), + Seq(leftTime), joinOf(Seq(leftTime), Seq(rightTime), leftTime > rightTime)), Append) Review Comment: **Nit (P3):** Grouping on `leftTime` makes only the left input count, and `getStateValueWatermark` solves `leftTime > rightTime` for the left input (StreamingJoinHelper.scala:104), so the check accepts this plan whether or not the early return for joins without an equality predicate exists, and no end-to-end test covers such a join. Grouped on `rightTime`, the right input counts and has no cutoff, because the sign check at StreamingJoinHelper.scala:179 finds none, so without the early return the check rejects the plan with the correctness message, the error such a query would then get instead of 'Stream-stream join without equality predicate is not supported.': ```suggestion UnsupportedOperationChecker.checkStreamStreamJoinOutputWatermark(Aggregate(Seq(rightTime), Seq(rightTime), joinOf(Seq(leftTime), Seq(rightTime), leftTime > rightTime)), Append) ``` This extends an [existing discussion](https://github.com/apache/spark/pull/60713#discussion_r4639356352). **Verification:** - **Regression:** With the early return for plans that hold a stream-stream join without an equality predicate removed, the plan-level case for that early return fails, because its plan, grouped on the right input's time, is rejected naming the right input; with the early return in place it passes. ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala: ########## @@ -156,6 +157,118 @@ object UnsupportedOperationChecker extends Logging { } } + /** + * Checks, in append mode, for an operator that drops late rows after a stream-stream join, when + * its event time can come from an input of the join whose state has no cutoff, as + * [[checkStreamingQueryGlobalWatermarkLimit]] does for other operators. It takes the optimized + * plan, whose join conditions eviction uses, and in which the optimizer has replaced every CTE + * reference, MATERIALIZED ones included. A query from a checkpoint without + * `STATEFUL_OPERATOR_CHECK_JOIN_OUTPUT_WATERMARK` only logs a warning. + */ + def checkStreamStreamJoinOutputWatermark(plan: LogicalPlan, outputMode: OutputMode): Unit = { + // TODO: Update mode is not checked, although its aggregations also drop late rows. + if (outputMode != InternalOutputModes.Append) { + return + } + // A stream-stream join without an equality predicate fails in planning with its own error. + val hasJoinWithoutEquality = plan.exists { + case j @ Join(l, r, _, _, _) => l.isStreaming && r.isStreaming && + ExtractEquiJoinKeys.unapply(j).isEmpty + case _ => false + } + if (hasJoinWithoutEquality) { + return + } + val failWhenDetected = SQLConf.get.statefulOperatorCorrectnessCheckEnabled && + SQLConf.get.getConf(SQLConf.STATEFUL_OPERATOR_CHECK_JOIN_OUTPUT_WATERMARK) + try { + plan.foreach { subPlan => + if (dropsLateRows(subPlan)) { + subPlan.foreach { + case j: Join if j ne subPlan => + // An input counts unless the operator's event times come only from other inputs. + val sources = eventTimeSources(subPlan, j) + joinInputWithoutStateCutoff(j, + input => sources.forall(_.exists(input.outputSet.contains))).foreach { side => + throwError("Detected pattern of possible 'correctness' issue: the state of the " + + s"$side input of a stream-stream join has no cutoff, so the join can emit its " + + "old rows below its output watermark, and a later stateful operator drops them " + + "as late. Add a watermark in the join keys or a range condition that bounds " + + "that input by the other input's watermark, or set " + + "`spark.sql.streaming.statefulOperator.checkCorrectness.enabled` to false.")(j) + } + case _ => + } + } + } + } catch { + case e: AnalysisException if !failWhenDetected => + logWarning(log"${MDC(ANALYSIS_ERROR, e.message)};\n${MDC(QUERY_PLAN, plan)}", e) + } + } + + // An input of a stream-stream join with an event time but no state cutoff, as eviction derives + // it: no watermark in the join keys, and no range condition that bounds the input by the + // watermark of the other input. A left semi join only emits left rows. + // TODO: An input evicted by another column is not checked yet, such as the right input of + // `leftKey = rightKey AND leftTime = rightTs`, evicted by rightTs, not its event time. + private def joinInputWithoutStateCutoff( + join: Join, counts: LogicalPlan => Boolean): Option[String] = join match { + case Join(left, right, joinType, condition, _) if left.isStreaming && right.isStreaming && + !StreamingJoinHelper.isWatermarkInJoinKeys(join) => + Seq(("left", left, right), ("right", right, left)).take(if (joinType == LeftSemi) 1 else 2) + .filter { case (_, input, _) => counts(input) } + .collectFirst { + case (side, input, other) if input.output.exists(hasEventTimeCol) && + StreamingJoinHelper.getStateValueWatermark( + input.outputSet, other.outputSet, condition, Some(1000000)).isEmpty => side + } + case _ => None + } + + // The columns of `join`'s output that the event-time columns by which `operator` drops late rows + // are computed from: an aggregation's grouping columns, or else its input's columns. Projections + // and the expansion of a sliding window map their columns to the columns they read; any other + // node that is not stateful is followed into the one child that outputs all the traced columns. + // None for any other path, such as one through another stateful operator. + private def eventTimeSources(operator: LogicalPlan, join: Join): Option[AttributeSet] = { + def trace(plan: LogicalPlan, attrs: AttributeSet): Option[AttributeSet] = plan match { + case p if p eq join => Some(attrs) + case Project(list, child) => + trace(child, AttributeSet(list.filter(e => attrs.contains(e.toAttribute)) + .flatMap(_.references))) + case Expand(projections, output, child) => + trace(child, AttributeSet(output.indices.filter(i => attrs.contains(output(i))) + .flatMap(i => projections.flatMap(_(i).references)))) + case p if !isStatefulOperation(p) => + p.children.filter(c => attrs.subsetOf(c.outputSet)) match { + case Seq(child) => trace(child, attrs) Review Comment: **Non-blocking (P2):** At a union this follows the first input even when the join is in a later one, and that input's trace then gives up, counting every input of the join. In the optimized plan of the first micro-batch that the check reads, a source with no offset yet or no new data is an empty streaming `LocalRelation`, and `PropagateEmptyRelation` removes a union input that folds to it and aliases the rest, so whether the first input is still there depends on that batch's data. By the review's reading of the code, with `o` a file stream of `(key, ts)` read with a schema copied from a watermarked DataFrame, so that `ts` carries the watermark-delay metadata without a watermark of its own: ```scala o.union(l.join(r, expr("leftKey = rightKey AND rightTime <= leftTime + INTERVAL 10 SECONDS")) .select($"leftKey".as("key"), $"leftTime".as("ts"))) .groupBy(window($"ts", "10 seconds")).count() ``` runs on a new checkpoint whose first batch has no file in `o`: that input is removed, the trace follows the aliasing projection to `leftTime`, and the range gives the left input a cutoff. A restart whose first batch has new files in `o` keeps the union, follows `o` to its source and fails naming the right input, although every row the window reads from the join carries `leftTime`. Each later restart replays that logged batch and fails again until `spark.sql.streaming.statefulOperator.checkCorrectness.enabled` is set to false; setting the new internal conf to false does not help, because the restart restores the value true from the offset log. With `spark.sql.streaming.statefulOperator.allowMultiple` set to false, the same flip happens with a watermark defined after the union; in the default mode such a watermark above the watermarked join fails with 'Redefining watermark is disallowed' once the watermark advances, on the base branch too, and a first input with a watermark of its o wn is never removed, because `PropagateEmptyRelation` does not fold an `EventTimeWatermark`. Rejecting a join reached through a later union input is the PR's stated conservative fallback; the problem is that the rejection can first appear at an arbitrary restart of a query that has been running. See **Shared repair plan 1** in the review body. ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala: ########## @@ -156,6 +157,118 @@ object UnsupportedOperationChecker extends Logging { } } + /** + * Checks, in append mode, for an operator that drops late rows after a stream-stream join, when + * its event time can come from an input of the join whose state has no cutoff, as + * [[checkStreamingQueryGlobalWatermarkLimit]] does for other operators. It takes the optimized + * plan, whose join conditions eviction uses, and in which the optimizer has replaced every CTE + * reference, MATERIALIZED ones included. A query from a checkpoint without + * `STATEFUL_OPERATOR_CHECK_JOIN_OUTPUT_WATERMARK` only logs a warning. + */ + def checkStreamStreamJoinOutputWatermark(plan: LogicalPlan, outputMode: OutputMode): Unit = { + // TODO: Update mode is not checked, although its aggregations also drop late rows. + if (outputMode != InternalOutputModes.Append) { + return + } + // A stream-stream join without an equality predicate fails in planning with its own error. + val hasJoinWithoutEquality = plan.exists { + case j @ Join(l, r, _, _, _) => l.isStreaming && r.isStreaming && + ExtractEquiJoinKeys.unapply(j).isEmpty + case _ => false + } + if (hasJoinWithoutEquality) { + return + } + val failWhenDetected = SQLConf.get.statefulOperatorCorrectnessCheckEnabled && + SQLConf.get.getConf(SQLConf.STATEFUL_OPERATOR_CHECK_JOIN_OUTPUT_WATERMARK) + try { + plan.foreach { subPlan => + if (dropsLateRows(subPlan)) { + subPlan.foreach { + case j: Join if j ne subPlan => + // An input counts unless the operator's event times come only from other inputs. + val sources = eventTimeSources(subPlan, j) + joinInputWithoutStateCutoff(j, + input => sources.forall(_.exists(input.outputSet.contains))).foreach { side => + throwError("Detected pattern of possible 'correctness' issue: the state of the " + + s"$side input of a stream-stream join has no cutoff, so the join can emit its " + + "old rows below its output watermark, and a later stateful operator drops them " + + "as late. Add a watermark in the join keys or a range condition that bounds " + + "that input by the other input's watermark, or set " + + "`spark.sql.streaming.statefulOperator.checkCorrectness.enabled` to false.")(j) + } + case _ => + } + } + } + } catch { + case e: AnalysisException if !failWhenDetected => + logWarning(log"${MDC(ANALYSIS_ERROR, e.message)};\n${MDC(QUERY_PLAN, plan)}", e) + } + } + + // An input of a stream-stream join with an event time but no state cutoff, as eviction derives + // it: no watermark in the join keys, and no range condition that bounds the input by the + // watermark of the other input. A left semi join only emits left rows. + // TODO: An input evicted by another column is not checked yet, such as the right input of + // `leftKey = rightKey AND leftTime = rightTs`, evicted by rightTs, not its event time. + private def joinInputWithoutStateCutoff( + join: Join, counts: LogicalPlan => Boolean): Option[String] = join match { + case Join(left, right, joinType, condition, _) if left.isStreaming && right.isStreaming && + !StreamingJoinHelper.isWatermarkInJoinKeys(join) => + Seq(("left", left, right), ("right", right, left)).take(if (joinType == LeftSemi) 1 else 2) + .filter { case (_, input, _) => counts(input) } + .collectFirst { + case (side, input, other) if input.output.exists(hasEventTimeCol) && + StreamingJoinHelper.getStateValueWatermark( + input.outputSet, other.outputSet, condition, Some(1000000)).isEmpty => side + } + case _ => None + } + + // The columns of `join`'s output that the event-time columns by which `operator` drops late rows + // are computed from: an aggregation's grouping columns, or else its input's columns. Projections + // and the expansion of a sliding window map their columns to the columns they read; any other + // node that is not stateful is followed into the one child that outputs all the traced columns. + // None for any other path, such as one through another stateful operator. + private def eventTimeSources(operator: LogicalPlan, join: Join): Option[AttributeSet] = { + def trace(plan: LogicalPlan, attrs: AttributeSet): Option[AttributeSet] = plan match { + case p if p eq join => Some(attrs) + case Project(list, child) => + trace(child, AttributeSet(list.filter(e => attrs.contains(e.toAttribute)) + .flatMap(_.references))) + case Expand(projections, output, child) => + trace(child, AttributeSet(output.indices.filter(i => attrs.contains(output(i))) + .flatMap(i => projections.flatMap(_(i).references)))) + case p if !isStatefulOperation(p) => + p.children.filter(c => attrs.subsetOf(c.outputSet)) match { Review Comment: **Non-blocking (P2):** At a union this rule follows only the input that outputs the union's attributes, the first one, since `Union.mergeChildOutputs` keeps the first input's attributes, and `eventTimeSources` starts from the operator's first input that contains the join (line 250). When one join plan instance reaches the operator through several inputs, the later ones are never traced. The optimized plan shares the instance that way when a SQL CTE that defines the join is referenced more than once and is kept until `ReplaceCTERefWithRepartition`, as MATERIALIZED and non-deterministic CTEs are: that rule, like `InlineCTE.inlineReference`, puts the definition's plan, or a projection over that same plan, at each reference, and streaming references are not deduplicated. By the review's reading of the code, with the suite's two watermarked inputs registered as views `l` and `r`, this query starts on a new checkpoint: ```sql WITH j AS MATERIALIZED ( SELECT * FROM l JOIN r ON leftKey = rightKey AND rightTime <= leftTime + INTERVAL 10 SECONDS) SELECT CAST(w.start AS BIGINT), count(*) FROM (SELECT window(t, '10 seconds') AS w FROM (SELECT leftTime AS t FROM j UNION ALL SELECT rightTime AS t FROM j)) GROUP BY w ``` The window traces to `leftTime`, so only the left input counts, and the range gives it a cutoff. The second union input carries `rightTime` from the right input, whose state is never evicted: a right row (2, 5 s) that joins a left row (2, 51 s) after the watermark has passed 40 s reaches the aggregation below the join's output watermark of about 30 s and is dropped as late, while the batch query counts it. The base branch loses the same row. Written with DataFrames, `j.select($"leftTime".as("t")).union(j.select($"rightTime".as("t")))` gets one join copy per input from the per-batch source replacement and is rejected naming the right input. The same applies when a later stream-stream join reads one join instance through both of its inputs, because only its first input is traced. This extends existing discussions [1](https://github.com/apache/spark/pull/60713#issuecomment-7090920366), [2](https://github.com/apache/spark/pull/60713#discussion_r4644703743). See **Shared repair plan 1** in the review body. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
