spark-test commented on code in PR #60705:
URL: https://github.com/apache/spark/pull/60705#discussion_r4642281328
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -156,6 +156,73 @@ object UnsupportedOperationChecker extends Logging {
}
}
+ /**
+ * Checks, in append mode, for an operator that drops late rows after a
stream-stream join whose
+ * state of an input has no cutoff, as
[[checkStreamingQueryGlobalWatermarkLimit]] does for other
+ * operators. It takes the optimized plan, whose join conditions eviction
uses. 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 =>
+ // 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 =>
+ 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 " +
Review Comment:
**Non-blocking (P2):** For an input flagged through the other-column branch
at lines 205-207, such as the left input of `rightTime BETWEEN leftTime AND
expiry` before a window aggregation on `leftTime`, this message says its state
'has no cutoff' and asks for 'a range condition that bounds that input by the
other input's watermark'. The state does have a cutoff, on `expiry`, and the
condition already bounds the input by `rightTime`'s watermark; what clears the
check is bounding `leftTime` as well, for example `rightTime <= leftTime +
INTERVAL 1 DAY`. A named error condition with one sub-condition per reason
could give this case a message that names the column the state is evicted by
and that remedy; the scaladoc at lines 159-164 and the doc of
`spark.sql.streaming.statefulOperator.checkJoinOutputWatermark` in
SQLConf.scala need the same update.
See **Shared repair plan 2** in the review body.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -117,6 +117,35 @@ object StreamingJoinHelper extends PredicateHelper with
Logging {
allStateWatermarks.reduceOption((x, y) => Math.min(x, y))
}
+ /**
+ * Get the column that evicts the state of an input with its own watermark,
with its state value
+ * watermark. That is the event time if the condition bounds it, then the
first other TIMESTAMP
+ * column in input order that the condition bounds, and then the first cast
of another column
+ * to TIMESTAMP, such as a DATE column, that the condition bounds. Each
column is solved on its
+ * own, so the cutoff applies to the column that the condition bounds. A
cast is returned as it
+ * is in the condition, so eviction evaluates it with the same time zone.
+ */
+ def getStateValueWatermarkColumn(
+ inputAttributes: Seq[Attribute],
+ attributesWithEventWatermark: AttributeSet,
+ joinCondition: Option[Expression],
+ eventWatermark: Option[Long]): Option[(Expression, Long)] = {
+ val eventTime = inputAttributes.find(_.metadata.contains(delayKey))
+ val references =
joinCondition.map(_.references).getOrElse(AttributeSet.empty)
+ val candidates = eventTime.toSeq ++ inputAttributes.filter { a =>
+ a.dataType == TimestampType && !eventTime.exists(_.semanticEquals(a)) &&
+ references.contains(a)
+ }
+ val casts = joinCondition.toSeq.flatMap(_.collect {
+ case c @ Cast(a: Attribute, TimestampType, _, _)
Review Comment:
**Non-blocking (P2):** This matches only `Cast(a: Attribute, TimestampType,
_, _)`, but `collectTerms` unwraps a cast to TIMESTAMP and collects the
additions and literals inside it, so the solver bounds `CAST(leftExpirySec +
3600 AS TIMESTAMP)` while the pick returns nothing for it. For `rightTime
BETWEEN leftTime AND CAST(leftExpirySec + 3600 AS TIMESTAMP)` with a BIGINT
`leftExpirySec`, the left input then falls back to eviction by `leftTime` with
the cutoff solved for the cast (`StreamingSymmetricHashJoinHelper.scala` lines
286-288), so a right row that arrives after the watermark passed `leftTime` but
before the cast value finds no match, and the left row is emitted unmatched too
early. That is the problem this PR fixes for `CAST(leftExpirySec AS TIMESTAMP)
+ INTERVAL 1 HOUR`, which is picked because the inner cast is a cast of a
column. The solver's cutoff applies to the column's own value cast to
TIMESTAMP, so evicting such an input by `CAST(leftExpirySec AS TIMESTAMP)` woul
d be correct; the fallback comment at lines 277-280 of that file does not
mention these casts either.
**Recommended change:** Extend the cast pick in
StreamingJoinHelper.getStateValueWatermarkColumn to a cast to TIMESTAMP whose
child is an addition or subtraction of literals and one numeric input column,
and evict such an input by that column cast to TIMESTAMP with the original
cast's eval mode; leave a cast of interval arithmetic over a TIMESTAMP_NTZ
column on the event-time fallback, with a TODO at the fallback comment in
StreamingSymmetricHashJoinHelper.scala (lines 277-280) naming it. Add
column-pick tests and range eviction tests with CAST(leftExpirySec + 3600 AS
TIMESTAMP).
**Why this works:** For a numeric column c and literal k, CAST(c + k AS
TIMESTAMP) equals CAST(c AS TIMESTAMP) plus k seconds, so the cutoff the solver
derives for c bounds the column's cast exactly, and every consumer of the pick
then treats the input like one bounded through a direct cast.
**Risks:** State format 4 orders these inputs by the cast instead of the
event time, which changes what index version 2 means; that is safe only while
index version 2 is unreleased, so the repair must land with this change.
**Constraints:** The new pick comes after the event time, other TIMESTAMP
columns and direct casts, so inputs those already pick keep their eviction. A
newly picked cast that can fail under ANSI mode, such as over a DOUBLE column,
goes through the same non-failing evaluation as a direct cast.
**Exclusions:**
- A cast of interval arithmetic over a TIMESTAMP_NTZ column stays on the
event-time fallback with a TODO, because its conversion through the session
time zone is not linear across daylight-saving transitions.
**Verification:**
- **Regression:** With state formats 2, 3 and 4, run a left outer join on
leftKey = rightKey AND rightTime BETWEEN leftTime AND CAST(leftExpirySec + 3600
AS TIMESTAMP) where a right row arrives after the watermark has passed leftTime
but before the cast value, and check that it is matched and that the unmatched
row is emitted only after the cast value passes the cutoff.
- **Behavior:** Check that the column pick returns CAST(leftExpirySec AS
TIMESTAMP) for that condition, keeps preferring the event time, other TIMESTAMP
columns and direct casts, and returns nothing for interval arithmetic over a
TIMESTAMP_NTZ column.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -156,6 +156,73 @@ object UnsupportedOperationChecker extends Logging {
}
}
+ /**
+ * Checks, in append mode, for an operator that drops late rows after a
stream-stream join whose
+ * state of an input has no cutoff, as
[[checkStreamingQueryGlobalWatermarkLimit]] does for other
+ * operators. It takes the optimized plan, whose join conditions eviction
uses. 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 =>
+ // 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 =>
+ joinInputWithoutStateCutoff(j).foreach { side =>
+ throwError("Detected pattern of possible 'correctness' issue:
the state of the " +
Review Comment:
**Nit (P3):** `throwError` wraps this message in `_LEGACY_ERROR_TEMP_3102`
(message `<msg>`, no SQLSTATE), so the failure that the 4.5 migration guide
documents surfaces with the same condition as every other
UnsupportedOperationChecker message, and the affected side appears only inside
the text. `common/utils/src/main/resources/error/README.md` asks new code not
to add uncategorized errors, and the PR already follows that for
`STREAMING_JOIN_STATE_V4_CHECKPOINT_INCOMPATIBLE`. Raising a named condition
with an SQLSTATE and side and column parameters from
`checkStreamStreamJoinOutputWatermark`, while keeping the warning path, fixes
it before the error ships.
See **Shared repair plan 2** in the review body.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -117,6 +117,35 @@ object StreamingJoinHelper extends PredicateHelper with
Logging {
allStateWatermarks.reduceOption((x, y) => Math.min(x, y))
}
+ /**
+ * Get the column that evicts the state of an input with its own watermark,
with its state value
+ * watermark. That is the event time if the condition bounds it, then the
first other TIMESTAMP
+ * column in input order that the condition bounds, and then the first cast
of another column
+ * to TIMESTAMP, such as a DATE column, that the condition bounds. Each
column is solved on its
+ * own, so the cutoff applies to the column that the condition bounds. A
cast is returned as it
+ * is in the condition, so eviction evaluates it with the same time zone.
+ */
+ def getStateValueWatermarkColumn(
+ inputAttributes: Seq[Attribute],
+ attributesWithEventWatermark: AttributeSet,
+ joinCondition: Option[Expression],
+ eventWatermark: Option[Long]): Option[(Expression, Long)] = {
+ val eventTime = inputAttributes.find(_.metadata.contains(delayKey))
+ val references =
joinCondition.map(_.references).getOrElse(AttributeSet.empty)
+ val candidates = eventTime.toSeq ++ inputAttributes.filter { a =>
+ a.dataType == TimestampType && !eventTime.exists(_.semanticEquals(a)) &&
+ references.contains(a)
+ }
+ val casts = joinCondition.toSeq.flatMap(_.collect {
+ case c @ Cast(a: Attribute, TimestampType, _, _)
Review Comment:
**Blocking (P1):** This accepts a cast to TIMESTAMP of a column of any type
and keeps the condition's eval mode, and once the cast is picked it is
evaluated outside the join condition: by the NULL test on every arriving row
that passes the pre-join filter (`StreamingSymmetricHashJoinExec.scala` lines
762-766 and 918), by the state format 1 to 3 eviction predicate on every stored
row (lines 769-772 of that file), and by the state format 4 ordering on every
append (`SymmetricHashJoinStateManager.scala` lines 283-288). With ANSI mode
on, the default, a cast from STRING, FLOAT or DOUBLE throws for a value it
cannot convert. For `rightTime BETWEEN leftTime AND CAST(leftExpiry AS
TIMESTAMP)` with a STRING `leftExpiry`, a left row whose `leftExpiry` is 'n/a'
and whose key no right row has now fails the batch with CAST_INVALID_INPUT on
arrival and on every retry. On the base branch the cast is evaluated only
against a right row with the same key, so that row is stored, evicted by
`leftTim
e` and emitted as unmatched. A query on state format 1, 2 or 3 restarted from
an earlier checkpoint that holds such a row fails in every batch, since the
failing eviction never removes it. Integral, decimal, DATE and TIMESTAMP_NTZ
sources are not affected.
**Recommended change:** For a picked cast that can fail, an ANSI-mode cast
to TIMESTAMP from STRING, FLOAT or DOUBLE, test NULL on arrival on the cast's
source column, evaluate the eviction predicate and the state format 4 ordering
with a copy of the cast that returns NULL instead of failing, and treat a row
whose non-NULL value does not cast as the base branch does: keep it, evict it
by its event time with the cutoff solved over the whole input, and index it in
state format 4 by its event time. Leave the join condition's own cast
unchanged, and add range eviction tests with a STRING column, and with a DOUBLE
column holding NaN, cast to TIMESTAMP under ANSI mode on and off.
**Why this works:** Rows whose value casts keep the new eviction by the
cast, and rows whose source is NULL keep being emitted on arrival. A row whose
value does not cast is never evaluated through the failing cast outside the
condition, so it fails the batch only when it meets a row of the other input
with the same key, as on the base branch, and it leaves state once its event
time passes the cutoff, as the base branch evicts it.
**Risks:** State format 4 then orders such an input's rows by two values,
the cast for castable rows and the event time for the others; both are
TIMESTAMP microseconds and one range scan evicts both, but later changes to the
ordering must keep the two in step.
**Constraints:** The join condition keeps its own ANSI cast, so a row that
does not cast still fails the batch when a row of the other input with the same
key meets it. Casts that cannot fail keep the current evaluation, and the
restart and index-version behavior of state format 4 stays as it is.
**Verification:**
- **Regression:** With ANSI mode on and state formats 2, 3 and 4, run a left
outer join bounded only through a STRING column cast to TIMESTAMP, add a left
row whose string does not cast and has no matching key, and check that the
query keeps running and emits the row as unmatched once its event time passes
the cutoff, while castable rows keep their matches; repeat it with a DOUBLE
column whose value is NaN in place of the STRING column.
- **Behavior:** Check that the same row fails the batch when a right row
with its key and a time at or after the row's event time arrives while the row
is in state, as on the base branch, and that with ANSI mode off the row is
emitted when it arrives.
- **Compatibility:** Store such a row with state format 2 in the legacy
mode, which stores it without evaluating the cast, restart in the default mode,
and check that the query keeps running and evicts the row by its event time.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -362,6 +364,39 @@ case class StreamingSymmetricHashJoinExec(
}
protected override def doExecute(): RDD[InternalRow] = {
+ // Older versions and the legacy mode order the V4 state of an input by
its event time (index
+ // version 0), so their checkpoints cannot evict that state by another
column. Index version 1
+ // orders it by the column that the default mode picks, which the legacy
mode cannot evict,
+ // except a column cast to TIMESTAMP, by which version 2 also orders it.
+ val indexVersion =
conf.getConf(SQLConf.STREAMING_JOIN_STATE_V4_INDEX_VERSION)
+ if (stateFormatVersion == 4 && (indexVersion < 2 ||
!allowMultipleStatefulOperators)) {
+ Seq((LeftSide, stateWatermarkPredicates.left, left.output, right.output),
+ (RightSide, stateWatermarkPredicates.right, right.output,
left.output)).foreach {
+ case (side, predicate, attributes, otherAttributes) =>
+ val eventTime = WatermarkSupport.findEventTimeColumnIndex(
+ attributes, allowMultipleEventTimeColumns = false)
+ val column = if (indexVersion == 0) {
+ stateValueWatermarkColumnOrdinal(predicate, attributes)
+ } else {
+ predicate.collect { case _: JoinStateValueWatermarkPredicate =>
+ StreamingJoinHelper.getStateValueWatermarkColumn(attributes,
+ AttributeSet(otherAttributes), condition.full, Some(0L))
+ }.flatten.collect {
+ // With version 1, the default mode orders only by a cast, and
the legacy mode by
+ // anything else. With version 2, only the legacy mode gets here.
Review Comment:
**Nit (P3):** The default mode orders the state format 4 index by whatever
column it picks, `expiry` included (lines 736-739), so, read as a statement of
how each mode orders the state, this comment is false. What the guard below
keeps for version 1 are the picked columns whose order differs from the
checkpoint's: a cast in the default mode and any other column in the legacy
mode. Suggested wording:
```suggestion
// With version 1, the checkpoint's order differs from the
default mode's only for
// a cast, and from the legacy mode's for any other column.
With version 2, only the
// legacy mode gets here.
```
**Verification:**
- **Inspection:** Check that the comment above the guard describes, for
version 1, a difference from the default mode only for a cast and from the
legacy mode for any other column.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/checkpointing/OffsetSeq.scala:
##########
@@ -273,9 +275,11 @@ object OffsetSeqMetadata extends Logging {
StreamingAggregationStateManager.legacyVersion.toString,
STREAMING_JOIN_STATE_FORMAT_VERSION.key ->
SymmetricHashJoinStateManager.legacyVersion.toString,
+ STREAMING_JOIN_STATE_V4_INDEX_VERSION.key -> "0",
STATE_STORE_COMPRESSION_CODEC.key -> CompressionCodec.LZ4,
STATEFUL_OPERATOR_USE_STRICT_DISTRIBUTION.key -> "false",
PRUNE_FILTERS_CAN_PRUNE_STREAMING_SUBPLAN.key -> "true",
+ STATEFUL_OPERATOR_CHECK_JOIN_OUTPUT_WATERMARK.key -> "false",
Review Comment:
**Blocking (P1):** With this default, a query restarted from a checkpoint
written before this change runs the late-row check in warn-only mode, but on
state formats 1 to 3 it also adopts the new eviction, since only state format 4
compares orderings (`StreamingSymmetricHashJoinExec.scala` lines 371-372). Take
`l LEFT OUTER JOIN r ON leftKey = rightKey AND rightTime BETWEEN leftTime AND
expiry` with 10-minute watermarks, followed in append mode by
`groupBy(window(leftTime, '1 hour')).count()`, where `expiry` is a day after
`leftTime`, and a left row at 10:00 that never matches. On the base branch the
row is evicted once the watermark passes 10:00 and counted in the 10:00 window.
After an upgrade and restart, the check only warns, the row stays in state
until `expiry` passes the cutoff a day later, and the join emits it with
`leftTime` 10:00, a day below its output watermark, which still comes from the
whole-input cutoffs (lines 1196-1211 of that file), so the aggregation drops it
a
s late. The same holds with `CAST(leftDate AS TIMESTAMP)` in place of `expiry`
and for right and full outer joins. The migration guide says restarted queries
only log a warning, not that their results change.
**Recommended change:** Make the late-row check fail, also for a query
restarted from a checkpoint written before this change, when it flags an input
that the default mode evicts by another TIMESTAMP column or a cast and whose
unmatched rows the join emits, that is the left input of a left outer join, the
right input of a right outer join, or either input of a full outer join, and
make it examine every input it flags rather than only the first. Keep only
logging a warning on such a restart for every other flagged input: one whose
state has no cutoff, whose old rows the base branch already drops, and one
whose unmatched rows the join does not emit, whose extra late matches the base
branch never produced. Setting
spark.sql.streaming.statefulOperator.checkCorrectness.enabled to false still
turns all of them into a warning. Update the 4.5 entries of
docs/streaming/ss-migration-guide.md, which now say that restarted queries only
log a warning, and the doc of spark.sql.streaming.statefu
lOperator.checkJoinOutputWatermark in SQLConf.scala, to say which restarted
queries fail and why, and add streaming join output watermark tests for each
kind of restart.
**Why this works:** joinInputWithoutStateCutoff reports every input it flags
and why, and checkStreamStreamJoinOutputWatermark applies the restored false
value of checkJoinOutputWatermark to all of them except an input evicted by
another column whose unmatched rows the join emits; for that input it fails
whenever the correctness check is enabled. A restarted format 1 to 3 query
whose new eviction would emit such unmatched rows below the join's output
watermark into a late-dropping operator then stops at its first batch with an
explicit error instead of silently losing those rows, while a restarted query
whose extra rows are only late matches keeps running as it does today.
**Compatibility:** Restarted queries with no late-dropping operator after
such a join keep adopting the new eviction, and restarted queries whose flagged
input has no state cutoff, or is evicted by another column without the join
emitting its unmatched rows, keep only logging a warning.
**Risks:** Append-mode queries with an outer join of this shape that started
on an earlier version and kept running fail at their first batch after the
upgrade; to run them, users bound the input's event time in the join condition,
or set spark.sql.streaming.statefulOperator.checkCorrectness.enabled to false,
which runs them as the change does today and drops those rows downstream.
**Constraints:** A restart whose flagged input has no state cutoff must keep
only logging a warning, because the base branch already drops that input's old
rows. A restart whose flagged input is evicted by another column but whose
unmatched rows the join does not emit, as in an inner or left semi join or on
the null-supplying side of an outer join, must keep only logging a warning,
because the joined rows the base branch emitted are still emitted in the same
batch with the same event times, and the extra late matches are ones the base
branch never produced. The check examines every input it flags, not only the
first one it finds today, so a restart still fails for an outer input evicted
by another column when the other input has no state cutoff. The restart
decision applies to whatever inputs the check flags, also after the check is
narrowed to the operators that can read the flagged input's event time.
**Exclusions:**
- Keeping the base branch's eviction for restarted queries is left out,
because the check's verdict would have to reach the predicate building of every
batch.
**Verification:**
- **Regression:** Restart, from a checkpoint whose offset log lacks
spark.sql.streaming.statefulOperator.checkJoinOutputWatermark, a left outer
join on leftKey = rightKey AND rightTime BETWEEN leftTime AND expiry followed
by a window aggregation on leftTime in append mode, with state formats 2 and 3,
and again with CAST(leftDate AS TIMESTAMP) in place of expiry, and check that
each restart fails at its first batch with the late-row rejection instead of
running.
- **Regression:** Restart from such a checkpoint a right outer join on
leftKey = rightKey AND leftTime <= rightExpiry, in which the left input has no
state cutoff and the right input is evicted by rightExpiry, followed by a
window aggregation on rightTime, and check that it also fails at its first
batch.
- **Compatibility:** Restart from such a checkpoint a key-only inner join
followed by a window aggregation, and an inner join on leftKey = rightKey AND
rightTime BETWEEN leftTime AND expiry followed by a window aggregation on
leftTime, and check that both only log the warning and keep running; then
restart the left outer join on expiry from such a checkpoint with
spark.sql.streaming.statefulOperator.checkCorrectness.enabled set to false and
check that it also only logs the warning.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -362,6 +364,39 @@ case class StreamingSymmetricHashJoinExec(
}
protected override def doExecute(): RDD[InternalRow] = {
+ // Older versions and the legacy mode order the V4 state of an input by
its event time (index
+ // version 0), so their checkpoints cannot evict that state by another
column. Index version 1
+ // orders it by the column that the default mode picks, which the legacy
mode cannot evict,
+ // except a column cast to TIMESTAMP, by which version 2 also orders it.
+ val indexVersion =
conf.getConf(SQLConf.STREAMING_JOIN_STATE_V4_INDEX_VERSION)
+ if (stateFormatVersion == 4 && (indexVersion < 2 ||
!allowMultipleStatefulOperators)) {
+ Seq((LeftSide, stateWatermarkPredicates.left, left.output, right.output),
+ (RightSide, stateWatermarkPredicates.right, right.output,
left.output)).foreach {
+ case (side, predicate, attributes, otherAttributes) =>
+ val eventTime = WatermarkSupport.findEventTimeColumnIndex(
+ attributes, allowMultipleEventTimeColumns = false)
+ val column = if (indexVersion == 0) {
+ stateValueWatermarkColumnOrdinal(predicate, attributes)
+ } else {
+ predicate.collect { case _: JoinStateValueWatermarkPredicate =>
+ StreamingJoinHelper.getStateValueWatermarkColumn(attributes,
+ AttributeSet(otherAttributes), condition.full, Some(0L))
+ }.flatten.collect {
+ // With version 1, the default mode orders only by a cast, and
the legacy mode by
+ // anything else. With version 2, only the legacy mode gets here.
+ case (c, _) if indexVersion == 2 ||
Review Comment:
**Nit (P3):** Two regressions of this condition pass the suite. Without
`indexVersion == 2 ||`, a legacy-mode restart of a default-mode checkpoint
whose cast-bounded input is ordered by the cast runs and evicts by the event
time through that index, because the suite's version 2 legacy restarts use only
`expiry` or the event time. With the `c.isInstanceOf[Cast] ==
allowMultipleStatefulOperators` test replaced by `true`, version 1 checkpoints
of a join evicted by `expiry` fail to restart in the default mode, the case
version 1 exists for, because the suite sets version 1 only for a cast-bounded
new query. A test that restarts a default-mode `CAST(leftDate AS TIMESTAMP)`
checkpoint in the legacy mode and expects the incompatible-checkpoint error
naming `leftDate`, and one that restarts a version 1 checkpoint of a join
bounded through `expiry` in the default mode and expects it to run, cover both.
**Verification:**
- **Regression:** Start a state format 4 left outer join bounded through
CAST(leftDate AS TIMESTAMP) in the default mode, restart it with
spark.sql.streaming.statefulOperator.allowMultiple set to false, and check that
it fails with the incompatible-checkpoint error naming leftDate.
- **Compatibility:** Record index version 1 in the offset log of a state
format 4 join bounded through expiry, restart it in the default mode, and check
that it keeps running and returns the expected rows.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -156,6 +156,73 @@ object UnsupportedOperationChecker extends Logging {
}
}
+ /**
+ * Checks, in append mode, for an operator that drops late rows after a
stream-stream join whose
+ * state of an input has no cutoff, as
[[checkStreamingQueryGlobalWatermarkLimit]] does for other
+ * operators. It takes the optimized plan, whose join conditions eviction
uses. 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 =>
+ // 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 =>
+ joinInputWithoutStateCutoff(j).foreach { side =>
Review Comment:
**Blocking (P1):** The flagged input becomes a rejection here without being
related to the event-time column that the late-dropping operator filters by.
For `leftKey = rightKey AND rightTime <= leftTime + INTERVAL 10 SECONDS`, inner
or left outer, followed by `groupBy(window($"leftTime", "10
seconds")).count()`, the right input has no state cutoff and is flagged, so the
query fails when its first batch is planned. Yet, by our reading of the code,
no joined row can be late for that aggregation: the left input is evicted by
`leftTime` with its own cutoff, the join's output watermark is the minimum of
that left state watermark and the input watermark, and every `leftTime` the
join emits is above the previous batch's output watermark, which is the
aggregation's late-event watermark. The base branch runs this query and returns
these counts. The same over-rejection happens when the late-dropping operator
is a later stream-stream join whose input from this join carries no event-time
colu
mn. The migration guide justifies the rule with 'Such a query could drop
joined rows as late', which does not hold here, and without changing the query
it runs only with
`spark.sql.streaming.statefulOperator.checkJoinOutputWatermark` or
`spark.sql.streaming.statefulOperator.checkCorrectness.enabled` set to false.
**Recommended change:** Flag a join input below a late-dropping operator
only when an event-time column that the operator filters by can carry that
input's event time: an aggregation's event-time grouping key, the event-time
column of the input that contains the flagged join for a later stream-stream
join, and the event-time column of the operator's input otherwise, each traced
through the projections and expansions between the operator and the join to the
columns it is computed from. Keep flagging when the trace cannot follow a
column. Add streaming join output watermark tests that accept an inner and a
left outer join on leftKey = rightKey AND rightTime <= leftTime + INTERVAL 10
SECONDS followed by a window aggregation on leftTime, next to the existing
rejection of that join when the aggregation groups by rightTime.
**Why this works:** The check already applies this reasoning to a left semi
join, whose right input it ignores because the join emits only left rows.
Applying it per operator removes the rejections in which the operator's late
filter reads only event times that the join keeps at or above its output
watermark, while every pattern whose filter can read the flagged input's event
time is still rejected.
**Risks:** A trace that follows a column to the wrong input would accept a
query that drops rows; keeping the rejection whenever the trace cannot follow a
column limits this to bugs in the trace itself, which the acceptance and
rejection tests cover.
**Constraints:** Every query that the check rejects today and whose operator
can read the flagged input's event time must still be rejected, for inputs
without a cutoff and for inputs evicted by another column. The trace must read
the optimized, CTE-inlined plan that the check already reads. Every input that
the check flags is traced, not only the first one it finds today, so a key-only
join counted by a window on rightTime is still rejected through its right input.
**Verification:**
- **Regression:** Run a new append-mode inner join and a left outer join on
leftKey = rightKey AND rightTime <= leftTime + INTERVAL 10 SECONDS, each
followed by a window count on leftTime, over several batches, and check that
each starts and returns the expected counts.
- **Behavior:** Check that the same join counted by a window on rightTime, a
key-only join counted by a window on leftTime and by a window on rightTime, and
a join evicted by another column before an aggregation on that input's event
time are still rejected, and that a later stream-stream join that reads no
event-time column from the flagged join is accepted.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -73,12 +73,16 @@ object StreamingSymmetricHashJoinHelper extends Logging {
}
/**
* Predicate for watermark on state values. See
[[JoinStateKeyWatermarkPredicate]] for
- * the semantics of `stateWatermark` and `prevStateWatermark`.
+ * the semantics of `stateWatermark` and `prevStateWatermark`.
`conditionBoundsColumn` is true
+ * only when the default mode picked the column that `expr` tests because
the join condition
+ * bounds it, so that a row with a NULL in it can never match. The legacy
mode and the fallback
+ * for an input bounded only through a column cast to TIMESTAMP leave it
false.
Review Comment:
**Nit (P3):** Since this PR, `getStateValueWatermarkColumn` returns a column
cast to TIMESTAMP and `solve()` marks it bounded (line 286), so
`conditionBoundsColumn` is true for such an input and the predicate tests the
cast; the helper suite asserts exactly that for `CAST(leftDate AS TIMESTAMP)`.
This sentence, and the comment on `isEvictionColumnNull` in
`StreamingSymmetricHashJoinExec.scala` (lines 758-761), still say such an input
is tested by its event time. Both should name only the legacy mode and the
whole-input fallback as the cases that leave the flag false and test the event
time.
**Verification:**
- **Inspection:** Check that the scaladoc of
JoinStateValueWatermarkPredicate and the comment on isEvictionColumnNull name
only the legacy mode and the whole-input fallback as the cases that test the
event time.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -710,17 +750,44 @@ case class StreamingSymmetricHashJoinExec(
Predicate.create(Literal(false), Seq.empty).eval _ // false = do not
remove if no predicate
}
+ private[this] var updatedStateRowsCount = 0
+ private[this] var numRemovedFromOtherSideDuringJoinCount = 0
+ private[this] val allowMultipleStatefulOperators: Boolean =
+ conf.getConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE)
+
+ // When the default mode picked the column that the value predicate tests
because the join
+ // condition bounds it, a row with a NULL in it can never match, and
`column <= cutoff` never
+ // holds for it. The legacy mode, and the default mode for an input
bounded only through a
+ // column cast to TIMESTAMP, test the event time, which the condition need
not bound.
+ private[this] val isEvictionColumnNull: UnsafeRow => Boolean =
stateWatermarkPredicate match {
+ case Some(JoinStateValueWatermarkPredicate(LessThanOrEqual(column, _),
_, _, true)) =>
+ Predicate.create(IsNull(column), inputAttributes).eval _
+ case _ => _ => false
+ }
+
+ // Such a row is not stored, but an earlier version or the legacy mode can
have stored one.
private[this] val stateValueWatermarkPredicateFunc =
stateWatermarkPredicate match {
- case Some(JoinStateValueWatermarkPredicate(expr, _, _)) =>
+ case Some(JoinStateValueWatermarkPredicate(expr @
LessThanOrEqual(column, _), _, _, true)) =>
+ Predicate.create(Or(expr, IsNull(column)), inputAttributes).eval _
+ case Some(JoinStateValueWatermarkPredicate(expr, _, _, _)) =>
Predicate.create(expr, inputAttributes).eval _
case _ =>
Predicate.create(Literal(false), Seq.empty).eval _ // false = do not
remove if no predicate
}
- private[this] var updatedStateRowsCount = 0
- private[this] var numRemovedFromOtherSideDuringJoinCount = 0
- private[this] val allowMultipleStatefulOperators: Boolean =
- conf.getConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE)
+ // A left semi join processes its right input first, so this batch's left
rows can still match
+ // a right row that the completion check skips (SPARK-61380). Earlier
versions tested it against
+ // the cutoff on the event time solved over the whole input, which a
picked column can exceed.
+ private[this] val skipsEvictingRightRow: UnsafeRow => Boolean =
stateWatermarkPredicate match {
+ case Some(p: JoinStateValueWatermarkPredicate) if
p.conditionBoundsColumn &&
+ joinType == LeftSemi && joinSide == RightSide =>
+ val cutoff =
StreamingJoinHelper.getStateValueWatermark(AttributeSet(inputAttributes),
Review Comment:
**Nit (P3):** This runs in every task of every batch, since
`skipsEvictingRightRow` is a field of `OneSideHashJoiner`:
`getStateValueWatermark` solves the condition again and logs its constraints at
INFO, and `Predicate.create` compiles a predicate that inlines this batch's
cutoff, so each executor JVM compiles one more class per micro-batch. For a
plain interval left semi join such as `k = rk AND lt BETWEEN re - INTERVAL 1
HOUR AND re`, the picked column is `re` and its own cutoff equals the
whole-input cutoff, so this predicate decides every row exactly as the eviction
predicate does. Solving the whole-input cutoff once in
`getStateWatermarkPredicates`, carrying it on the value predicate, and
comparing the row's event time with it directly removes the extra solve and
compile with the same results.
See **Shared repair plan 1** in the review body.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -710,17 +750,44 @@ case class StreamingSymmetricHashJoinExec(
Predicate.create(Literal(false), Seq.empty).eval _ // false = do not
remove if no predicate
}
+ private[this] var updatedStateRowsCount = 0
+ private[this] var numRemovedFromOtherSideDuringJoinCount = 0
+ private[this] val allowMultipleStatefulOperators: Boolean =
+ conf.getConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE)
+
+ // When the default mode picked the column that the value predicate tests
because the join
+ // condition bounds it, a row with a NULL in it can never match, and
`column <= cutoff` never
+ // holds for it. The legacy mode, and the default mode for an input
bounded only through a
+ // column cast to TIMESTAMP, test the event time, which the condition need
not bound.
+ private[this] val isEvictionColumnNull: UnsafeRow => Boolean =
stateWatermarkPredicate match {
+ case Some(JoinStateValueWatermarkPredicate(LessThanOrEqual(column, _),
_, _, true)) =>
+ Predicate.create(IsNull(column), inputAttributes).eval _
+ case _ => _ => false
+ }
+
+ // Such a row is not stored, but an earlier version or the legacy mode can
have stored one.
private[this] val stateValueWatermarkPredicateFunc =
stateWatermarkPredicate match {
- case Some(JoinStateValueWatermarkPredicate(expr, _, _)) =>
+ case Some(JoinStateValueWatermarkPredicate(expr @
LessThanOrEqual(column, _), _, _, true)) =>
+ Predicate.create(Or(expr, IsNull(column)), inputAttributes).eval _
+ case Some(JoinStateValueWatermarkPredicate(expr, _, _, _)) =>
Predicate.create(expr, inputAttributes).eval _
case _ =>
Predicate.create(Literal(false), Seq.empty).eval _ // false = do not
remove if no predicate
}
- private[this] var updatedStateRowsCount = 0
- private[this] var numRemovedFromOtherSideDuringJoinCount = 0
- private[this] val allowMultipleStatefulOperators: Boolean =
- conf.getConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE)
+ // A left semi join processes its right input first, so this batch's left
rows can still match
+ // a right row that the completion check skips (SPARK-61380). Earlier
versions tested it against
+ // the cutoff on the event time solved over the whole input, which a
picked column can exceed.
+ private[this] val skipsEvictingRightRow: UnsafeRow => Boolean =
stateWatermarkPredicate match {
+ case Some(p: JoinStateValueWatermarkPredicate) if
p.conditionBoundsColumn &&
+ joinType == LeftSemi && joinSide == RightSide =>
+ val cutoff =
StreamingJoinHelper.getStateValueWatermark(AttributeSet(inputAttributes),
+ AttributeSet(left.output), condition.full,
eventTimeWatermarkForEviction)
+
WatermarkSupport.watermarkExpression(WatermarkSupport.findEventTimeColumn(inputAttributes,
Review Comment:
**Non-blocking (P2):** For a left semi join on `k = rk AND lt BETWEEN re AND
rx` with 0-second watermarks on `lt` and `re`, the right input is evicted by
`rx`, but this check skips storing a right row when `re` is at or below the
cutoff, which here equals the `rx` cutoff. A right row (1, re 08:00, rx 12:00)
arriving when the eviction watermark is 10:00 is not stored, so a left row (1,
lt 11:00) in the next batch finds nothing, although 08:00 <= 11:00 <= 12:00; an
inner join with the same condition stores that row through the eviction
predicate and returns the match. The base branch lost the row for both joins,
so the fix stops short for left semi joins. Skipping a right row only when the
eviction predicate holds for it and its event time is at or below the
whole-input cutoff keeps the existing left semi test's behavior and stores
every row the new eviction keeps.
See **Shared repair plan 1** in the review body.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -156,6 +156,73 @@ object UnsupportedOperationChecker extends Logging {
}
}
+ /**
+ * Checks, in append mode, for an operator that drops late rows after a
stream-stream join whose
+ * state of an input has no cutoff, as
[[checkStreamingQueryGlobalWatermarkLimit]] does for other
+ * operators. It takes the optimized plan, whose join conditions eviction
uses. 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 =>
+ // 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 =>
+ 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. With allowMultiple, an input that eviction
picks another column
+ // for counts too, since its state keeps rows of any event time. A left semi
join only emits
+ // 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) &&
(
+ StreamingJoinHelper.getStateValueWatermark(
+ input.outputSet, other.outputSet, condition,
Some(1000000)).isEmpty ||
+ SQLConf.get.getConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE) &&
+ StreamingJoinHelper.getStateValueWatermarkColumn(input.output,
other.outputSet,
+ condition, Some(1000000)).exists { case (column, _) =>
!hasEventTimeCol(column) }
+ ) => side
+ }
+ case _ => None
+ }
+
+ // A stateful operator that drops the input rows below its watermark for
late rows. Its
+ // physical operator filters by an event-time column of its input, so it
needs one.
+ private def dropsLateRows(p: LogicalPlan): Boolean = p.isStreaming &&
Review Comment:
**Nit (P3):** Each of these regressions passes the suites: removing the
`Join` case (line 218), so a key-only join feeding a second stream-stream join
is accepted; turning the `EventTimeTimeout` or `EventTime` conditions (lines
219-222) into `false`; turning the event-time precondition at line 216 into
`true`, which rejects operators whose input has no event-time column; dropping
the append-mode guard at line 171, which rejects update-mode queries that the
base branch runs; or dropping the `allowMultiple` condition at line 205, which
rejects legacy-mode queries. Cases that reject a key-only join followed by a
second stream-stream join reading its flagged event time, by
`flatMapGroupsWithState` with an event-time timeout, by `transformWithState` in
event-time mode and by `dropDuplicatesWithinWatermark`, and that accept the
same join when the next operator's input has no event-time column or the query
runs in update mode, plus a join evicted by another column in the legacy mode,
wou
ld give each branch a failure signal.
**Verification:**
- **Behavior:** Check that in append mode a key-only stream-stream join
followed by a second stream-stream join reading its flagged event time, by
flatMapGroupsWithState with an event-time timeout, by transformWithState in
event-time mode and by dropDuplicatesWithinWatermark is rejected.
- **Behavior:** Check that the same key-only join is accepted when the
following operator's input has no event-time column and when the query runs in
update mode, and that a join evicted by another column before a window
aggregation is accepted with spark.sql.streaming.statefulOperator.allowMultiple
set to false.
--
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]