spark-test commented on code in PR #60667:
URL: https://github.com/apache/spark/pull/60667#discussion_r4641791867
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -262,27 +262,34 @@ object StreamingSymmetricHashJoinHelper extends Logging {
prevStateKeyWatermark)
}
} else if (isWatermarkDefinedOnInput) { // case 2 in the
StreamingSymmetricHashJoinExec docs
- val stateValueWatermark = StreamingJoinHelper.getStateValueWatermark(
- attributesToFindStateWatermarkFor =
AttributeSet(oneSideInputAttributes),
- attributesWithEventWatermark =
AttributeSet(otherSideInputAttributes),
- condition,
- eventTimeWatermarkForEviction)
- // A row can pass late-input filtering but already be eligible for
eviction in this batch.
- // When the previous join-derived state cutoff is ahead of the
late-input watermark, a new
- // row can fall at or below that cutoff. V4 must scan from the
beginning to find such rows.
- val prevStateValueWatermark = eventTimeWatermarkForLateEvents.flatMap
{ lateWatermark =>
- StreamingJoinHelper.getStateValueWatermark(
- attributesToFindStateWatermarkFor =
AttributeSet(oneSideInputAttributes),
- attributesWithEventWatermark =
AttributeSet(otherSideInputAttributes),
- condition,
- eventTimeWatermarkForLateEvents).filter(_ <= lateWatermark)
- }
- val inputAttributeWithWatermark =
oneSideInputAttributes.find(_.metadata.contains(delayKey))
- val expr = watermarkExpression(inputAttributeWithWatermark,
stateValueWatermark)
- expr.map { e =>
- // watermarkExpression only provides the expression when
eventTimeWatermarkForEviction
- // is defined
- JoinStateValueWatermarkPredicate(e, stateValueWatermark.get,
prevStateValueWatermark)
+ val eventTime =
oneSideInputAttributes.find(_.metadata.contains(delayKey))
+ // The legacy mode with a single global watermark keeps applying a
cutoff on any column of
+ // this input to the event time.
+ def solve(watermark: Option[Long]): Option[(Attribute, Long)] =
+ if (useFirstEventTimeColumn) {
+ StreamingJoinHelper.getStateValueWatermark(
+ attributesToFindStateWatermarkFor =
AttributeSet(oneSideInputAttributes),
+ attributesWithEventWatermark =
AttributeSet(otherSideInputAttributes),
+ condition,
+ watermark).map(eventTime.get -> _)
+ } else {
+
StreamingJoinHelper.getStateValueWatermarkColumn(oneSideInputAttributes,
Review Comment:
Thanks. With the guard, a new append-mode query with a stateful operator
after such a join now fails at its first batch. Queries restarted from an
existing checkpoint are not covered yet; this review raises that separately.
<!-- SPARK_DEV_REVIEW_REPLY
{"feedback_id":"inline:4615752059","thread_id":"inline:4615752059","verdict_sha256":"06ab5a980cde5dceea58368744a350a74017041c59a8ed5a7e45e6684548c46d"}
-->
##########
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) &&
Review Comment:
**Blocking (P1):** This disjunct puts an input that the default mode evicts
by another column, such as `expiry` in `rightTime BETWEEN leftTime AND expiry`,
under the guard's restart policy, which only warns. A checkpoint written before
the guard restores
spark.sql.streaming.statefulOperator.checkJoinOutputWatermark as false
(OffsetSeq.scala:282), so for a query restarted from a 4.3.0 checkpoint the
error is caught and logged, while on state formats 1 to 3 the restarted join
already evicts by `expiry` and still reports an output watermark that assumes
eviction by the event time. By the review's reading of the code, with
`groupBy(window(leftTime, '1 minute')).count()` after the join, the restarted
query emits (2, null) with leftTime 100 s long after its output watermark has
passed 120 s, and the aggregation drops it, and the match with the right row at
460 s, as late, so the window [60 s, 120 s) that 4.3.0 counted is never
emitted. The only signals are one driver warning per run and
the aggregation's numRowsDroppedByWatermark metric. Warning on restart suits
an input whose state is never evicted, whose rows the base branch already
dropped, but not this case, whose eviction changes on restart.
This extends existing discussions
[1](https://github.com/apache/spark/pull/60667#issuecomment-7035615207),
[2](https://github.com/apache/spark/pull/60667#discussion_r4615752059).
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 +740,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's right input whose column the
default mode picked, this test applies the cutoff solved over the whole input
to the event time. When the condition bounds the right input only through
another TIMESTAMP column, that cutoff comes from that column, so the completion
check at line 968 keeps the earlier rule for arriving rows while stored right
rows are now evicted by the picked column. By the review's reading of the code,
for `k = rk AND lt BETWEEN re AND rx` with 0-second watermarks on lt and re,
after a first batch that moves the watermark to 10 h, the right row (1, re 8 h,
rx 12 h) arriving in the next batch passes late filtering but is not stored,
because 8 h is below the 10 h cutoff, although eviction by rx would keep it
until rx reaches the cutoff; the left row (1, lt 11 h) of the batch after that
finds no match and is never emitted, while an inner join stores that right row
and returns the match. The earlier test is needed where the ev
ent time is picked and its own cutoff exceeds the whole-input cutoff
(SPARK-61380), but for an input evicted by another column it skips rows that
eviction keeps.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60667#issuecomment-7035615207).
See **Shared repair plan 2** 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 " +
Review Comment:
**Non-blocking (P2):** This message is reused for the new case in which the
default mode evicts the input by another TIMESTAMP column. For `rightTime
BETWEEN leftTime AND expiry`, the left input's state does have a cutoff, on
`expiry`, and the condition already bounds that input by the right watermark
through `expiry`, so 'has no cutoff' misstates the cause and the
range-condition advice describes what the query already has;
StreamingJoinOutputWatermarkSuite's 'reject a join evicted by another column
before a window aggregation' asserts this text. The migration guide's
4.4-to-4.5 entry points to the same remedy, and the doc of
spark.sql.streaming.statefulOperator.checkJoinOutputWatermark and this method's
scaladoc describe only an input whose state has no cutoff. What clears the
failure without disabling the check or changing the join keys is a bound on the
input's event time: in the suite's query, where `expiry` is `leftTime +
INTERVAL 10 MINUTES`, adding `rightTime <= leftTime +
INTERVAL 10 MINUTES` leaves the matches unchanged and makes the check accept
the query.
See **Shared repair plan 1** in the review body.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -117,6 +117,29 @@ 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, and
otherwise the first other
+ * TIMESTAMP column in input order that the condition bounds. Each column is
solved on its own,
+ * so the cutoff applies to the column that the condition bounds.
+ */
+ def getStateValueWatermarkColumn(
+ inputAttributes: Seq[Attribute],
+ attributesWithEventWatermark: AttributeSet,
+ joinCondition: Option[Expression],
+ eventWatermark: Option[Long]): Option[(Attribute, 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)
+ }
+ candidates.iterator.flatMap { a =>
Review Comment:
**Nit (P3):** This scan must skip each TIMESTAMP candidate that the
condition does not bound from below. StreamingJoinHelperSuite covers an
unbounded event time and the order of two bounded columns, and the inputs of
StreamingJoinRangeEvictionSuite have one non-event-time TIMESTAMP column, so no
test puts an unbounded candidate ahead of the bounded one. For an input with
validFrom and validTo, in that order, and `rightTime BETWEEN validFrom AND
validTo`, validFrom is bounded only from above; a change that solves only the
first referenced candidate would return no column, and the input would fall
back to eviction by its event time with validTo's cutoff, the early eviction
this change fixes, while both suites still pass. A StreamingJoinHelperSuite
case with that input and condition that asserts validTo is picked with its
cutoff would pin it.
**Verification:**
- **Behavior:** For an input with an event time and the TIMESTAMP columns
validFrom and validTo, in that order, and the condition `rightTime BETWEEN
validFrom AND validTo`, the eviction column pick returns validTo with its
cutoff.
##########
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) }
Review Comment:
**Nit (P3):** This `exists` accepts an input for which the pick returns no
column, such as one bounded only through `CAST(leftDate AS TIMESTAMP)`, whose
eviction keeps the base branch's rule. StreamingJoinOutputWatermarkSuite covers
an event-time pick, which the check accepts, and an `expiry` pick, which it
rejects, but no query on that fallback, so a refactor such as
`!getStateValueWatermarkColumn(...).exists { case (c, _) => hasEventTimeCol(c)
}` would start rejecting a new append-mode join on `leftKey = rightKey AND
rightTime BETWEEN leftTime AND CAST(leftDate AS TIMESTAMP)` followed by a
window aggregation on leftTime, which runs on master, and no test would fail. A
case in that suite, on state formats 2 and 4, that asserts such a query is
accepted and runs would pin it.
**Verification:**
- **Compatibility:** A new append-mode query on state formats 2 and 4 that
joins on `leftKey = rightKey AND rightTime BETWEEN leftTime AND CAST(leftDate
AS TIMESTAMP)` and counts windows of leftTime is accepted at its first batch
and runs.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -710,17 +740,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.
Review Comment:
**Nit (P3):** The eviction predicate below evicts such a row only on state
formats 1 to 3. State format 4 evicts by ranges of its index, where a NULL
event time is stored at timestamp 0, below the scan start once that start is
not negative, so a row with a NULL leftTime that a 4.3.0 checkpoint holds stays
in state and a restarted left outer join never emits it, as on master. Leaving
that to SPARK-62038 is fine, but only the reply on the earlier thread says so;
a TODO here that names SPARK-62038 and says state format 4 still keeps such
rows would let readers see that the fix is partial.
This extends existing discussions
[1](https://github.com/apache/spark/pull/60667#issuecomment-7035615207),
[2](https://github.com/apache/spark/pull/60667#discussion_r4626507407).
**Verification:**
- **Inspection:** A TODO naming SPARK-62038 at the eviction of restored rows
with a NULL eviction column says that state format 4 keeps rows with a NULL
event time that a checkpoint of an earlier release holds.
##########
docs/streaming/ss-migration-guide.md:
##########
@@ -23,6 +23,33 @@ 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 stream-stream join evicts the state of an input with its
own watermark by
+ another TIMESTAMP column of that input when the join condition limits how
long a row of that
+ input can match only through that column, for example through `expiry` in
+ `rightTime BETWEEN leftTime AND expiry`. Earlier versions evicted by the
event time, and could
+ emit outer join rows too early and lose matches. Such a join can emit rows
below its output
+ watermark, which still assumes eviction by the event time, so in append mode
a new query fails
+ when an operator that drops late rows follows it, as described below for an
input whose state
+ is never evicted. In such a join, and in a time-interval join such as
+ `rightTime BETWEEN leftTime AND leftTime + INTERVAL 10 MINUTES`, a row whose
eviction column is
+ NULL can never match: an outer join now emits it when it arrives, and no
join keeps it in state.
+ With state format versions 1 to 3, such rows that a checkpoint of an earlier
version holds are
+ evicted, and emitted by an outer join, after the upgrade. With state format
version 4, a join
+ evicted by another column cannot restart from a checkpoint of an earlier
version, or after a
+ change of `spark.sql.streaming.statefulOperator.allowMultiple`; start it
with a new checkpoint.
+ With state format versions 1 to 3, it restarts, and rows that an earlier
version evicted are
+ not restored. With `spark.sql.streaming.statefulOperator.allowMultiple` set
to false, joins keep
Review Comment:
**Non-blocking (P2):** This sentence makes
spark.sql.streaming.statefulOperator.allowMultiple=false the only way back from
the new eviction, the NULL rule, the guard's new case and the state format 4
restart failures, but that setting also makes every stateful operator of the
query filter late rows by the current batch's watermark, drops the state format
4 scan bound, and, per its doc, allows only one stateful operator. By the
review's reading of the code, a new append-mode query that counts
`window(leftTime, '1 minute')` after a left outer join on `rightTime BETWEEN
leftTime AND expiry` now fails at its first batch; with the correctness check
off the aggregation drops the join's later rows, and with allowMultiple set to
false it drops the outer rows that the join emits at watermark 340 s with
leftTime 100 s, so no setting gives that query back the result it has on
master. A state format 4 checkpoint of an earlier release of this join restarts
only in that mode, and one started on
this change in the default mode cannot switch to it without a new checkpoint.
The previous review left this as a question; after your answer, this review
raises it as a finding, because a change that can hurt users needs a setting
whose off state restores master's behavior. The concern that such a setting
brings back the earlier wrong results applies equally to the legacy mode, which
restores the same eviction, and a setting that is on by default changes no
result unless a user turns it off.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60667#issuecomment-7035615207).
**Recommended change:** Add an internal SQLConf, on by default, that is read
in every run as spark.sql.streaming.statefulOperator.allowMultiple is, rather
than recorded in the offset log. When it is off, getStateWatermarkPredicates
skips the eviction-column pick, so the join builds the base branch's value
predicate on the event time with the cutoff solved over the whole input and
leaves conditionBoundsColumn false, which stores rows with a NULL eviction
column and keeps the base branch's left semi skip and state format 4 scan
start; joinInputWithoutStateCutoff does not flag an input that the pick would
evict by another column; StreamExecution records index version 0 for a new
query, as it does for the legacy mode; and the state format 4 restart check
runs for an index-version-1 checkpoint as it does in the legacy mode, so a
checkpoint whose input the default mode orders by another column fails with
STREAMING_JOIN_STATE_V4_CHECKPOINT_INCOMPATIBLE. Everything else, including
late-ro
w filtering, the watermarks of every stateful operator and the join's output
watermark, stays in the default mode. Name the setting in the migration guide's
4.4-to-4.5 entry as the way back to the earlier join behavior instead of
allowMultiple and say that its off state also brings back the earlier results,
mention it beside the legacy mode in the doc of
spark.sql.streaming.join.stateFormatV4.indexVersion, and add join tests with
the setting off.
**Why this works:** With the setting off, every reader of the
eviction-column pick gets the answer the legacy mode gives, but only for the
join: it evicts, keeps rows with a NULL eviction column, skips arriving left
semi right rows and orders state format 4 state as before this change, and the
join output watermark check flags only inputs whose state has no cutoff, while
the query keeps the default mode's watermarks and late-row filtering. The
recorded state format 4 index version and its restart check keep a checkpoint
from switching orderings when the setting changes between runs.
**Compatibility:** With the setting on, its default, every query behaves
exactly as with this change, and with allowMultiple set to false the legacy
mode keeps its current behavior whatever the setting.
**Risks:** With the setting off, these joins return the base branch's
results again, including the early outer rows and lost matches this change
fixes; the setting's doc and the migration note must say so. A state format 4
query that ran with the setting on and evicts an input by another column cannot
restart with it off and needs a new checkpoint, as in the legacy mode. Because
the setting is read in every run, changing it between runs moves a state format
1 to 3 join between the two eviction rules, so rows that one rule kept can be
evicted, and emitted by an outer join, at the next eviction.
**Constraints:** Nothing changes while the setting is on, its default. Other
stateful operators, the join's late-row filtering and its output watermark do
not read the setting. With allowMultiple set to false, the legacy mode keeps
its current behavior whatever the setting.
**Exclusions:**
- Restoring the base branch's eviction for a state format 4 checkpoint that
this change already ordered by another column, which would need a migration of
the persisted state.
**Verification:**
- **Regression:** With the setting off, on state formats 2 and 4, the left
outer join on `leftKey = rightKey AND rightTime BETWEEN leftTime AND expiry`
with the batches of 'range eviction uses the bounded column' emits (1, null,
100) and (2, null, 100) once the watermark reaches 340 s and no match for the
right row (1, 460 s), as the base branch does, and a left row whose expiry is
NULL is stored instead of being emitted on arrival.
- **Regression:** With the setting off, a window aggregation on leftTime
after that join is accepted at its first batch and counts the window [60 s, 120
s), and with the setting on the same query still fails at its first batch.
- **Behavior:** With the setting off, a new state format 4 query of that
shape records index version 0, a checkpoint whose offset log lacks the index
version restarts, and a checkpoint that ran with the setting on, recorded index
version 1 and evicts the left input by expiry fails to restart with
STREAMING_JOIN_STATE_V4_CHECKPOINT_INCOMPATIBLE for the left input and `expiry`.
- **Compatibility:** With the setting off and allowMultiple at its default,
a right row of that join whose event time lies between the previous and the
current batch's watermark is still joined, as in the default mode, and with
allowMultiple set to false the join keeps the legacy mode's output whatever the
setting.
- **Inspection:** The 4.4-to-4.5 migration guide entry names the new
setting, not spark.sql.streaming.statefulOperator.allowMultiple, as the way
back to the earlier join behavior and says that its off state also brings back
the earlier results, and the setting's doc says the same.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -710,18 +740,30 @@ case class StreamingSymmetricHashJoinExec(
Predicate.create(Literal(false), Seq.empty).eval _ // false = do not
remove if no predicate
}
- private[this] val stateValueWatermarkPredicateFunc =
stateWatermarkPredicate match {
- 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)
+ // When the join condition bounds the column that the value predicate
tests, 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, _, _, _)) =>
+ val predicate = Predicate.create(expr, inputAttributes)
+ (row: UnsafeRow) => predicate.eval(row) || isEvictionColumnNull(row)
Review Comment:
Thanks for checking against master and for tracking it in SPARK-62038.
Leaving state format 4 to that change is fine. The code does not mark the
deferral yet; this review raises that separately.
<!-- SPARK_DEV_REVIEW_REPLY
{"feedback_id":"inline:4626507407","thread_id":"inline:4626507407","verdict_sha256":"06ab5a980cde5dceea58368744a350a74017041c59a8ed5a7e45e6684548c46d"}
-->
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -710,17 +740,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,
+ allowMultipleEventTimeColumns = false), cutoff)
+ .map(Predicate.create(_, inputAttributes).eval _).getOrElse((_:
UnsafeRow) => false)
Review Comment:
**Nit (P3):** This compiles a second per-batch predicate, and the solve
above runs again in every task, for the right side of a left semi join whose
column the default mode picked. This predicate and the value predicate both
inline the batch's cutoff as a literal, so each misses the codegen cache once
per batch on every executor, where the base branch compiled one such predicate
for that side. For `lt BETWEEN re - INTERVAL 1 HOUR AND re`, re is picked with
its own cutoff equal to the whole-input cutoff, and because rows with a NULL re
are screened out on arrival, this predicate answers exactly as the value
predicate does for every row that reaches the completion check. The cost is a
bounded fixed amount per batch, and results are unchanged.
See **Shared repair plan 2** 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]