spark-test commented on code in PR #60713:
URL: https://github.com/apache/spark/pull/60713#discussion_r4644704200
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -156,6 +156,52 @@ object UnsupportedOperationChecker extends Logging {
}
}
+ /**
+ * Checks for a stateful operator after a stream-stream join whose state of
an input has no
+ * cutoff, as [[checkStreamingQueryGlobalWatermarkLimit]] does for other
operators. A query from
+ * a checkpoint without `STATEFUL_OPERATOR_CHECK_JOIN_OUTPUT_WATERMARK` only
logs a warning.
+ */
+ def checkStreamStreamJoinOutputWatermark(plan: LogicalPlan, outputMode:
OutputMode): Unit = {
+ val failWhenDetected = SQLConf.get.statefulOperatorCorrectnessCheckEnabled
&&
+
SQLConf.get.getConf(SQLConf.STATEFUL_OPERATOR_CHECK_JOIN_OUTPUT_WATERMARK)
+ try {
+ plan.foreach { subPlan =>
+ if (outputMode == InternalOutputModes.Append &&
isStatefulOperation(subPlan)) {
+ subPlan.foreach {
+ case j: Join if j ne subPlan =>
+ joinInputWithoutStateCutoff(j).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 stored left
rows.
+ private def joinInputWithoutStateCutoff(join: Join): 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)
+ .collectFirst {
+ case (side, input, other) if input.output.exists(hasEventTimeCol) &&
Review Comment:
Thanks, the trace fixes the case this thread started from: with the window
on leftTime, the one-sided range join now runs with the batch answer. One case
from this thread's verification list is still rejected: the same window on
leftTime that also aggregates the other input's time, for example
.agg(max($"rightTime")). The trace starts from every event-time column of the
aggregation's input, so rightTime, which only an aggregate function reads,
makes the right input count, although the aggregation's state store operators
receive only its grouping attributes and aggregate buffers and so drop late
rows by the window alone. Starting an aggregation's trace from the event-time
attributes of its grouping keys fixes it, and an end-to-end case with
max(rightTime) would pin it. This review also raises, as a separate finding,
the rejection that remains when the path to the join passes a node that keeps
its input's columns unchanged, such as a repartition, a typed groupByKey or a
join with a
static table.
<!-- SPARK_DEV_REVIEW_REPLY
{"feedback_id":"inline:4627142767","thread_id":"inline:4627142767","verdict_sha256":"aa956e2e229700211ba5d2b241d2279a6cb1993935f120c3610d5f7ee373c849"}
-->
##########
docs/streaming/ss-migration-guide.md:
##########
@@ -23,6 +23,16 @@ 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 that emits the rows of an input whose state is never
evicted, for example a
Review Comment:
**Nit (P3):** Since the last commit this sentence names queries that run. A
one-sided range join such as `leftKey = rightKey AND rightTime <= leftTime +
INTERVAL 10 SECONDS` emits the rows of its never-evicted right input, yet by
the review's reading of the code a window aggregation on `leftTime` after it is
accepted, as the suite's test 'accept a range join bounded on one side only
before a window on the bounded side' expects. The check now fails a query only
when the late-dropping operator's event time can come from such an input, or
when its path to the join has a node the check does not follow.
The last sentence of the entry also reads as covering a restart from the
checkpoint of a new query that was rejected. That query's first micro-batch has
already recorded true for the new conf in the offset log, so the restart is
checked again; only checkpoints written by earlier versions just log a warning.
The coverage sentence of the
`spark.sql.streaming.statefulOperator.checkJoinOutputWatermark` doc in
SQLConf.scala (lines 4460-4462) needs the same narrowing.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60713#discussion_r4639356371).
**Verification:**
- **Inspection:** The 4.5 migration entry and the conf doc describe the
rejected queries by whether the late-dropping operator's event time can come
from an input without a cutoff or passes a node the check does not follow, so a
one-sided range join before a window on the bounded input's time is not
described as failing, and the entry limits warn-only restarts to checkpoints
written before 4.5.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -156,6 +157,106 @@ object UnsupportedOperationChecker extends Logging {
}
}
+ /**
+ * Checks, in append mode, for an operator that drops late rows after a
stream-stream join that
+ * emits the rows of an input whose state has no cutoff, as
+ * [[checkStreamingQueryGlobalWatermarkLimit]] does for other operators. It
takes the optimized
+ * plan, whose join conditions eviction uses, with its CTE references
inlined: the optimizer
+ * keeps some CTE definitions, such as MATERIALIZED ones, whose joins would
be missed. A query
+ * from a checkpoint without `STATEFUL_OPERATOR_CHECK_JOIN_OUTPUT_WATERMARK`
only logs a warning.
+ */
+ def checkStreamStreamJoinOutputWatermark(plan: LogicalPlan, outputMode:
OutputMode): Unit = {
+ // 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 =>
+ // TODO: Update mode is not checked, although its aggregations also
drop late rows.
+ if (outputMode == InternalOutputModes.Append &&
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)
Review Comment:
**Nit (P3):** Since the trace commit the left semi test no longer pins this
restriction: a left semi join outputs no right column, so on a traced path its
right input never counts, and the test, which windows on `leftTime` through a
projection, passes without it. By the review's reading of the code, the
restriction now decides only on a path through a node the trace does not
follow, such as a left semi join bounded on its left input followed by
`.repartition(2)` and a window count on `leftTime`, which fails naming the
right input once the restriction is removed.
The same holds for the event-time condition of `dropsLateRows` (line 250),
which matters only on such a path, for example the one-sided range join
followed by `.select("leftKey").repartition(2).dropDuplicates()`, and for the
event-time guard of `joinInputWithoutStateCutoff` (line 219), which matters
only when the operator's event time gets its watermark above a join of
unwatermarked inputs. No test of the PR fails when any of the three is removed.
Once the trace follows repartitions, as the comment on its fallback asks, the
cases for the restriction need a node it still does not follow, such as a
union, and a rule that counts no input for an operator input without event-time
columns would decide what the `dropsLateRows` condition decides now.
This extends existing discussions
[1](https://github.com/apache/spark/pull/60713#discussion_r4627142824),
[2](https://github.com/apache/spark/pull/60713#discussion_r4643327957).
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,106 @@ object UnsupportedOperationChecker extends Logging {
}
}
+ /**
+ * Checks, in append mode, for an operator that drops late rows after a
stream-stream join that
+ * emits the rows of an input whose state has no cutoff, as
+ * [[checkStreamingQueryGlobalWatermarkLimit]] does for other operators. It
takes the optimized
+ * plan, whose join conditions eviction uses, with its CTE references
inlined: the optimizer
+ * keeps some CTE definitions, such as MATERIALIZED ones, whose joins would
be missed. A query
+ * from a checkpoint without `STATEFUL_OPERATOR_CHECK_JOIN_OUTPUT_WATERMARK`
only logs a warning.
+ */
+ def checkStreamStreamJoinOutputWatermark(plan: LogicalPlan, outputMode:
OutputMode): Unit = {
+ // 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 =>
+ // TODO: Update mode is not checked, although its aggregations also
drop late rows.
+ if (outputMode == InternalOutputModes.Append &&
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 of
`operator`'s input are computed
+ // from, or None when the path from the operator down to the join has a node
other than a
+ // projection, a filter, a watermark or an expansion, such as the one of a
sliding window.
+ 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 Filter(_, child) => trace(child, attrs)
+ case w: EventTimeWatermark => trace(w.child, attrs)
+ case Expand(projections, output, child) =>
+ trace(child, AttributeSet(output.indices.filter(i =>
attrs.contains(output(i)))
+ .flatMap(i => projections.flatMap(_(i).references))))
+ case _ => None
Review Comment:
**Blocking (P1):** This fallback also rejects queries whose path to the join
passes a node that keeps its child's columns and its rows' event times: a
`Repartition`, `RepartitionByExpression` or `RebalancePartitions`, whose output
is its child's output, including the repartition the optimizer plans for a
`WITH ... AS MATERIALIZED` CTE; the `AppendColumns` that a typed `groupByKey`
always puts under `flatMapGroupsWithState` and `transformWithState`, whose
output is its child's output followed by the key columns; and a join with a
static table, whose rows carry its streaming input's columns. The suite's test
'reject a range join bounded on one side only before a node that the check does
not follow' is one such query: by the review's reading of the code, it returns
the batch answer on master, like the query without `.repartition(2)` in the
test 'accept a range join bounded on one side only before a window on the
bounded side', since the repartition changes no row. The same happens to
`.as[(Int,
Timestamp)].groupByKey(_._1).flatMapGroupsWithState(OutputMode.Append(),
GroupStateTimeout.EventTimeTimeout())(...)` over the one-sided range join
narrowed to `leftKey` and `leftTime`, while the same function over
`groupBy($"leftKey").as[Int, (Int, Timestamp)]` is traced and accepted.
The fallback also counts every input when the operator's input on the join's
side has no event-time column, as for a later stream-stream join that keeps
only `leftKey` of this join, although that input filters none of the join's
rows. Following these nodes keeps every query whose event time can come from an
input without a cutoff rejected, since they change no event time, while a
union, a generator or another stateful operator can keep the conservative
fallback.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60713#discussion_r4627142767).
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,106 @@ object UnsupportedOperationChecker extends Logging {
}
}
+ /**
+ * Checks, in append mode, for an operator that drops late rows after a
stream-stream join that
+ * emits the rows of an input whose state has no cutoff, as
+ * [[checkStreamingQueryGlobalWatermarkLimit]] does for other operators. It
takes the optimized
+ * plan, whose join conditions eviction uses, with its CTE references
inlined: the optimizer
+ * keeps some CTE definitions, such as MATERIALIZED ones, whose joins would
be missed. A query
+ * from a checkpoint without `STATEFUL_OPERATOR_CHECK_JOIN_OUTPUT_WATERMARK`
only logs a warning.
+ */
+ def checkStreamStreamJoinOutputWatermark(plan: LogicalPlan, outputMode:
OutputMode): Unit = {
+ // 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 =>
+ // TODO: Update mode is not checked, although its aggregations also
drop late rows.
+ if (outputMode == InternalOutputModes.Append &&
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 of
`operator`'s input are computed
+ // from, or None when the path from the operator down to the join has a node
other than a
+ // projection, a filter, a watermark or an expansion, such as the one of a
sliding window.
+ 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 Filter(_, child) => trace(child, attrs)
+ case w: EventTimeWatermark => trace(w.child, attrs)
+ case Expand(projections, output, child) =>
Review Comment:
**Non-blocking (P2):** Every window in StreamingJoinOutputWatermarkSuite is
a tumbling 10-second window, which the window rewrite plans as a projection
over a filter, so no test takes this branch. By the review's reading of the
code, replacing it with a case that passes the traced columns through unchanged
keeps every test green, yet the one-sided range join followed by
`.groupBy(window($"rightTime", "10 seconds", "5 seconds")).count()` would then
be accepted: column pruning leaves only the window in the aggregation's input,
no join input outputs it, so no input counts, and the query would drop stored
right rows as late. Removing the case instead would reject the same join before
a sliding window on `leftTime`, which runs correctly on master, again with
every test green.
**Verification:**
- **Regression:** A one-sided range join of two 10-second-watermarked
streams followed in append mode by a 10-second window sliding every 5 seconds
on leftTime runs through enough batches to emit windows with the batch answer,
and the same join followed by such a window on rightTime is rejected when its
first micro-batch is planned, naming the right input.
--
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]