HeartSaVioR commented on code in PR #60713:
URL: https://github.com/apache/spark/pull/60713#discussion_r4661576417
##########
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:
> [!NOTE]
> **DISCLAIMER:** This comment was written by an LLM: Claude Opus 5.5
(`claude-opus-5-5`, 1M context), running as an SP2K agent on behalf of
@HeartSaVioR.
Fixed: an aggregation's trace now starts from the event-time columns of its
grouping expressions, so a window on `leftTime` that also computes
`max(rightTime)` runs. New test with `.agg(count("*"), max($"rightTime"))`: it
returns the batch answer, and with the window on `rightTime` it is rejected.
##########
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:
> [!NOTE]
> **DISCLAIMER:** This comment was written by an LLM: Claude Opus 5.5
(`claude-opus-5-5`, 1M context), running as an SP2K agent on behalf of
@HeartSaVioR.
Fixed with one rule instead of more node cases: any node that is not a
stateful operation is followed into the one child that outputs all the traced
columns, by exprId. That covers the repartition (also the one for a
MATERIALIZED CTE), the AppendColumns of a typed `groupByKey`, a join with a
static table, a union when the join is in its first input, and a generator. A
stateful operator on the path, a join in a later input of a union, or a node
where no single child outputs the columns, still rejects. New tests for a
repartition, a join with a static table, a MATERIALIZED CTE, a sliding window
and a typed `groupByKey` into `flatMapGroupsWithState` with an event-time
timeout: each runs with the bounded input's time and is rejected with the other
input's time.
##########
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:
> [!NOTE]
> **DISCLAIMER:** This comment was written by an LLM: Claude Opus 5.5
(`claude-opus-5-5`, 1M context), running as an SP2K agent on behalf of
@HeartSaVioR.
Added: the one-sided range join followed by a 10-second window sliding every
5 seconds runs on `leftTime` with the batch answer and is rejected on
`rightTime`.
##########
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:
> [!NOTE]
> **DISCLAIMER:** This comment was written by an LLM: Claude Opus 5.5
(`claude-opus-5-5`, 1M context), running as an SP2K agent on behalf of
@HeartSaVioR.
Added plan-level cases in UnsupportedOperationsSuite, each passing only
because of one condition: a left semi join bounded on its left input under a
union of the same child twice (a path the trace cannot follow), a deduplication
over an aggregation whose output has no event time (the rule that an operator
without such a column counts no input, which now replaces the `dropsLateRows`
condition), and a watermark above a join of unwatermarked inputs (the
event-time guard).
##########
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:
> [!NOTE]
> **DISCLAIMER:** This comment was written by an LLM: Claude Opus 5.5
(`claude-opus-5-5`, 1M context), running as an SP2K agent on behalf of
@HeartSaVioR.
Fixed: the migration entry and the conf doc now say the check fails a query
when the late-dropping operator's event time can come from an input without a
cutoff, or its path to the join passes another stateful operator, and the entry
limits warn-only restarts to checkpoints written before 4.5.
--
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]