spark-test commented on code in PR #60669:
URL: https://github.com/apache/spark/pull/60669#discussion_r4663259200
##########
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 =>
Review Comment:
Thanks, tracing the later operator's event time fixes both examples in this
thread: a window on leftTime after the one-sided bound now runs, and so does a
later join whose side keeps no event-time column. This review separately raises
the nodes at which the trace on this branch still stops when they sit between
the join and a later operator that drops late rows: an intervening stateful
operator, such as an aggregation or a deduplication, and the nodes that you say
e4ec72eccf8 in #60713 already follows, such as a repartition. If that commit
also traces through an intervening stateful operator, rebasing on it should
resolve that finding.
<!-- SPARK_DEV_REVIEW_REPLY
{"feedback_id":"inline:4642190846","thread_id":"inline:4642190846","verdict_sha256":"440cfbd3cbf9171c85bd590da6e6659561a718f4190448e2e807c30077325eb1"}
-->
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -92,13 +101,18 @@ object StreamingJoinHelper extends PredicateHelper with
Logging {
}
}
+ var inexactCutoff = false
val allStateWatermarks =
splitConjunctivePredicates(joinCondition.get).flatMap { predicate =>
// The generated the state watermark cleanup expression is inclusive of
the state watermark.
// If state watermark is W, all state where timestamp <= W will be
cleaned up.
// Now when the canonicalized join condition solves to leftTime >= W, we
don't want to clean
// up leftTime <= W. Rather we should clean up leftTime <= W - 1. Hence
the -1 below.
- val stateWatermark = predicate match {
+ val inexact = predicate.exists {
Review Comment:
**Blocking (P1):** This rule covers casts, but not the other way the
solver's reading of the condition can be too high for an input without its own
watermark. The solver sums `TimestampAddInterval` as plain microseconds and
reads `INTERVAL 1 DAY` as exactly 24 hours, while `timestampAddDayTime` adds
whole days with `plusDays` in the session time zone, as `DateTimeUtilsSuite`
pins for the 2019 fall-back. Reading the code with `spark.sql.session.timeZone`
set to America/Los_Angeles, a new left outer join of a left input without a
watermark and a right input with a 10-minute watermark on `leftKey = rightKey
AND leftTime BETWEEN rightTime - INTERVAL 1 DAY AND rightTime` stores left (1,
2026-10-31 12:30 PDT). A right row at 2026-11-01 11:55 PST moves the watermark
to 11:45 PST, so the next micro-batch's cutoff of 2026-10-31 19:44:59.999 UTC
evicts the left row at 19:30 UTC and emits (1, null). Right (1, 2026-11-01
12:00 PST) then passes the late filter, and `rightTime - INTERVAL 1 DAY`
is 2026-10-31 12:00 PDT, 25 hours earlier, so it would match, but the left
row is gone. The base branch never evicts that input and returns the match.
Inputs with their own watermark already use this 24-hour reading on the base
branch, and fixed-offset zones such as UTC are exact.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60669#discussion_r4642190874).
**Recommended change:** In StreamingJoinHelper.getStateValueWatermark, under
exactCutoffsOnly, also give no cutoff from a conjunct that contains a
TimestampAddInterval whose interval literal has a whole-day part, a day-time
interval of 24 hours or more or a calendar interval with days, when its time
zone has offset transitions, that is, when its zone rules are not a fixed
offset. Keep this separate from the inexact-cast flag that selects the earlier
minimum for inputs with their own watermark. Update the comment at
getStateValueWatermarkColumn and the migration guide's sentence about casts for
an input without its own watermark, and add one-sided watermark join tests in a
daylight-saving session time zone.
**Why this works:** Adding whole days on a zone's calendar is a fixed shift
only in a fixed-offset zone. Giving such conjuncts no cutoff in other zones
keeps every row of an input without its own watermark that a later admitted row
can match, as the base branch did for these inputs, while fixed-offset zones
and intervals shorter than a day keep the exact cutoff the solver computes.
**Risks:** In every session time zone that is not a fixed offset, which
includes nearly every region-based zone, not only daylight-saving zones such as
America/Los_Angeles but also zones such as Asia/Tokyo, whose offset has not
changed since 1951, a join whose only bound on an input without its own
watermark goes through an interval of a day or more keeps that input's state
forever and never emits its unmatched rows, as on the base branch; a
fixed-offset session time zone such as UTC or +09:00, or a bound shorter than a
day, keeps the eviction.
**Constraints:** Inputs with their own watermark keep their cutoffs,
including the earlier minimum that a cast that can round or drop digits
selects. Fixed-offset zones and intervals without a whole-day part keep the
exact cutoff, so the one-sided joins with second-scale ranges keep evicting.
The rule depends only on the conjunct and its time zone, not on the watermark,
so the column that state format 4 orders such an input by cannot change between
micro-batches.
**Exclusions:**
- Inputs with their own watermark, whose eviction cutoffs and state format 4
probe ranges also read a whole-day interval as 24 hours on the base branch.
**Verification:**
- **Regression:** With spark.sql.session.timeZone set to
America/Los_Angeles, a left outer join of a left input without a watermark and
a right input with a 10-minute watermark on `leftKey = rightKey AND leftTime
BETWEEN rightTime - INTERVAL 1 DAY AND rightTime` stores left (1, 2026-10-31
12:30 PDT), then gets right (9, 2026-11-01 11:55 PST), then right (8,
2026-11-01 11:56 PST) in its own micro-batch, then right (1, 2026-11-01 12:00
PST); it emits the match of key 1 and no row with a null right side for that
left row, on state formats 2 and 4, where the reviewed head emits the left row
with a null right side and loses the match.
- **Behavior:** With spark.sql.session.timeZone set to UTC, the same join
evicts left (1, 2026-10-31 19:30) and emits it with a null right side once a
right row of another key moves the right watermark past 2026-11-01 19:30, so
the exact cutoff is kept in a fixed-offset zone.
- **Compatibility:** In a session time zone with daylight saving, a bound
through an interval shorter than a day, as in the one-sided joins with a
5-second range, still gives an input without its own watermark its cutoff, and
an input with its own watermark bounded through INTERVAL 1 DAY keeps the cutoff
it gets on the base branch.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -710,17 +753,55 @@ 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.
+ // TODO: [SPARK-62038] State format 4 evicts by ranges of its index, which
stores a NULL at
+ // timestamp 0, below the scan start, so it still keeps such rows.
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,
+ // with constant-only and negative-sign conjuncts.
+ private[this] val skipsEvictingRightRow: UnsafeRow => Boolean =
stateWatermarkPredicate match {
+ case Some(p: JoinStateValueWatermarkPredicate) if
p.conditionBoundsColumn &&
+ joinType == LeftSemi && joinSide == RightSide =>
+ val eventTime = WatermarkSupport.findEventTimeColumn(inputAttributes,
+ allowMultipleEventTimeColumns = false)
+ val cutoff =
StreamingJoinHelper.getStateValueWatermark(AttributeSet(inputAttributes),
+ AttributeSet(left.output), condition.full,
eventTimeWatermarkForEviction,
+ risingCutoffsOnly = false)
+ // The value predicate gives the same answer when it tests the event
time with that cutoff,
+ // since a row with a NULL in the picked column does not reach the
completion check.
+ if (cutoff.contains(p.stateWatermark) &&
eventTime.exists(p.expr.references.contains)) {
+ stateValueWatermarkPredicateFunc
+ } else {
+ WatermarkSupport.watermarkExpression(eventTime, cutoff)
Review Comment:
**Non-blocking (P2):** For a right input evicted by another TIMESTAMP
column, this branch tests the event time against the whole-input cutoff, while
this micro-batch's eviction tests the picked column, so it can skip a right row
that eviction keeps. Reading the code for a left semi join on `k = rk AND lt
BETWEEN re - INTERVAL 1 HOUR AND rx` with 0-second watermarks on lt and re, the
right input is evicted by `rx <= watermark - 1 ms`. In a data micro-batch that
evicts at 10 hours while late rows are filtered at 0, right (1, re = 9.5 hours,
rx = 12 hours) satisfies `re <= 10 h - 1 ms` and is not stored, although
eviction by rx would keep it, so left (1, lt = 10.5 hours) in the next
micro-batch matches nothing. An inner join on that condition stores the row and
emits the match. Skipping a right row only when both the value predicate and
this event-time test hold would store such rows and keep the base branch's
threshold for left rows of the same micro-batch (SPARK-61380).
This extends an [existing
discussion](https://github.com/apache/spark/pull/60669#discussion_r4627362484).
**Verification:**
- **Regression:** In a new default-mode left semi join on `k = rk AND lt
BETWEEN re - INTERVAL 1 HOUR AND rx` with 0-second watermarks on lt and re and
no-data micro-batches disabled, after a micro-batch with events at 10 hours on
both inputs, a micro-batch receives right (1, re = 9.5 hours, rx = 12 hours)
and the next receives left (1, lt = 10.5 hours); the join emits (1, 10.5 hours)
on state formats 2 and 4, where the reviewed head emits nothing.
- **Compatibility:** A left semi join still keeps a right row that the
whole-input cutoff keeps when the picked column is the event time, still emits
each matched left row once, and skips the same right rows as the base branch
when the picked column is the event time.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -156,6 +157,116 @@ 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 on its event time, 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,
+ * and its join keeps evicting by the event time an input that would
otherwise be evicted by
+ * another column.
+ */
+ 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 on its
event time, 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 the event time of 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.
+ // TODO: An input evicted by a join key other than its event time is not
checked yet, such as
+ // the right input of `leftKey = rightKey AND leftTime = rightTs`, evicted
by rightTs.
+ 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) &&
(
+ // As the join's output watermark, take the cutoff of earlier
versions.
+ StreamingJoinHelper.getStateValueWatermark(input.outputSet,
other.outputSet,
+ condition, Some(1000000), risingCutoffsOnly = false).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
+ }
+
+ // The columns of `join`'s output that the event-time columns of
`operator`'s input are computed
+ // from, or None when the path from the operator down to the join has a node
other than a
+ // projection, a filter, a watermark or an expansion, such as the one of a
sliding window.
+ private def eventTimeSources(operator: LogicalPlan, join: Join):
Option[AttributeSet] = {
+ def trace(plan: LogicalPlan, attrs: AttributeSet): Option[AttributeSet] =
plan match {
+ case p if p eq join => Some(attrs)
+ case Project(list, child) =>
+ trace(child, AttributeSet(list.filter(e =>
attrs.contains(e.toAttribute))
+ .flatMap(_.references)))
+ case Filter(_, child) => trace(child, attrs)
+ case w: EventTimeWatermark => trace(w.child, attrs)
+ case Expand(projections, output, child) =>
+ trace(child, AttributeSet(output.indices.filter(i =>
attrs.contains(output(i)))
+ .flatMap(i => projections.flatMap(_(i).references))))
+ case _ => None
Review Comment:
**Blocking (P1):** Reading the code, this fallback still makes every input
of the join count whenever the path from the later operator down to the join
contains a node other than a projection, a filter, a watermark or a sliding
window's expansion. With watermarks on both inputs, `left.join(right,
expr("leftKey = rightKey AND rightTime <= leftTime + INTERVAL 10
SECONDS")).groupBy(window($"leftTime", "10 seconds")).count()` now runs, but
adding `.groupBy(window(window_time($"window"), "1 minute")).count()` makes the
second aggregation's trace stop at the first Aggregate, so the right input,
which has no cutoff, counts, and a new query fails at its first micro-batch
with 'the state of the right input of a stream-stream join has no cutoff on its
event time'. The second aggregation reads only the first one's windows, which
come from leftTime, so it never receives a joined row carrying rightTime, and
the base branch runs the query and returns its counts. The same stop rejects a
deduplic
ation between the join and a window aggregation, a join with a static table,
and a repartition, whose rejection StreamingJoinOutputWatermarkSuite's 'reject
a range join bounded on one side only before a node that the check does not
follow' pins. You say e4ec72eccf8 in #60713 follows the nodes that pass their
input's columns through; its files are not in this checkout, so whether it also
follows an intervening aggregation or deduplication could not be read. Until
then such queries run only with
spark.sql.streaming.statefulOperator.checkCorrectness.enabled set to false,
which also turns the other chained-operator checks into warnings.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60669#discussion_r4642190846).
**Recommended change:** Make the trace of the chained-operator check follow
every node between the join and the later operator whose output columns it can
map to its input: a node that passes its input's columns through unchanged,
such as a repartition or the streaming side of a join with a static table,
which the discussion says e4ec72eccf8 in #60713 already follows; an Aggregate,
by the references of the grouping expressions behind the traced output columns,
returning no source set when a traced column is an aggregate result; and a
Deduplicate or DeduplicateWithinWatermark, which pass their input's columns
unchanged. Keep returning no source set at every node whose output columns it
cannot map to its input. Turn the join output watermark test that pins a
rejection through a repartition after a join bounded on one side only into one
that expects the query to run, and add tests for a window aggregation over the
windows of a first one, and for a deduplication followed by a window a
ggregation, after such a join. If e4ec72eccf8 reaches this branch first, make
the change on top of that version.
**Why this works:** A later operator drops rows only by an event-time column
of its input. Mapping that column through the intervening operator to the join
output columns it is computed from lets the check count only the join inputs
whose event time can reach that filter, as it already does through projections,
filters, watermarks and expansions, while a column it cannot map still makes
every input count.
**Risks:** Following an aggregation's grouping columns relies on the
aggregation emitting each group only once its own watermark passes it, as
append mode does; following an aggregate result that carried an event-time
column could make the check accept a query that drops rows, so the trace must
stop at aggregate results. Queries that the check now accepts run as on the
base branch, and spark.sql.streaming.statefulOperator.checkCorrectness.enabled
stays the only way to run the queries it still rejects.
**Constraints:** Nodes whose output columns the trace cannot map to its
input keep making every input count. A key-only join, a join bounded on one
side only before an aggregation on the unbounded input's time, and a join that
evicts an input by another column before an aggregation on that input's event
time keep failing at their first micro-batch.
**Exclusions:**
- Correcting the join's output watermark itself, which this pull request
leaves out of scope.
- Operators whose output columns cannot be mapped to their input, such as
flatMapGroupsWithState and transformWithState, below which the check keeps
counting every input.
**Verification:**
- **Regression:** A new append-mode query that joins two watermarked inputs
on `leftKey = rightKey AND rightTime <= leftTime + INTERVAL 10 SECONDS`, counts
rows per 10-second window of leftTime and then counts those windows per
1-minute window runs over several micro-batches and returns the counts that the
base branch returns; the reviewed head fails it at its first micro-batch.
- **Regression:** A new append-mode query that keeps leftKey and leftTime of
that join, drops duplicates of leftKey and then counts rows per 10-second
window of leftTime runs; the reviewed head fails it at its first micro-batch.
- **Regression:** A new append-mode query that repartitions the output of
that one-sided join and then counts rows per 10-second window of leftTime runs
and returns the counts that the base branch returns; the reviewed head fails it
at its first micro-batch, as the join output watermark test of a node that the
check does not follow asserts.
- **Compatibility:** A key-only join of the two inputs followed by a window
aggregation and a second window aggregation over its windows, the one-sided
join followed by a window aggregation on rightTime, and a join on `rightTime
BETWEEN leftTime AND expiry` followed by a window aggregation on leftTime still
fail at their first micro-batch.
##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinOneSidedWatermarkSuite.scala:
##########
@@ -0,0 +1,216 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.streaming
+
+import org.apache.spark.sql.Row
+import org.apache.spark.sql.execution.streaming.runtime.MemoryStream
+import org.apache.spark.sql.execution.streaming.state.RocksDBStateStoreProvider
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.tags.SlowSQLTest
+
+@SlowSQLTest
+class StreamingJoinOneSidedWatermarkSuite extends StateStoreMetricsTest {
+ import testImplicits._
+
+ private def withJoinConf(version: Int)(f: => Unit): Unit = {
+ withSQLConf(
+ SQLConf.STREAMING_JOIN_STATE_FORMAT_VERSION.key -> version.toString,
+ SQLConf.STATE_STORE_PROVIDER_CLASS.key ->
classOf[RocksDBStateStoreProvider].getName,
+ SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> "false")(f)
+ }
+
+ for {
+ version <- Seq(2, 3, 4)
+ joinType <- Seq("left_outer", "right_outer", "full_outer")
+ } {
+ test(s"range eviction needs only the opposite watermark, V$version
$joinType") {
+ withSQLConf(
+ SQLConf.STREAMING_JOIN_STATE_FORMAT_VERSION.key -> version.toString,
+ SQLConf.STATE_STORE_PROVIDER_CLASS.key ->
classOf[RocksDBStateStoreProvider].getName,
+ SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> "false") {
+ val leftInput = MemoryStream[(Int, Int)]
+ val rightInput = MemoryStream[(Int, Int)]
+ val leftData = leftInput.toDF().toDF("leftKey", "time")
+ .select($"leftKey", timestamp_seconds($"time").as("leftTime"))
+ val rightData = rightInput.toDF().toDF("rightKey", "time")
+ .select($"rightKey", timestamp_seconds($"time").as("rightTime"))
+ // Only one input has a watermark: the one whose rows are not
preserved, and the right
+ // input of a full outer join, whose unmatched rows are then never
emitted.
+ val watermarkOnLeft = joinType == "right_outer"
+ val left = if (watermarkOnLeft) leftData.withWatermark("leftTime", "10
seconds") else {
+ leftData
+ }
+ val right = if (watermarkOnLeft) rightData else {
+ rightData.withWatermark("rightTime", "10 seconds")
+ }
+ val joined = left.join(right, expr("leftKey = rightKey AND " +
+ "leftTime BETWEEN rightTime - INTERVAL 5 SECONDS AND " +
+ "rightTime + INTERVAL 5 SECONDS"), joinType)
+ .select($"leftKey", $"rightKey", $"leftTime".cast("int"),
$"rightTime".cast("int"))
+ val stateInput = if (watermarkOnLeft) rightInput else leftInput
+ val watermarkInput = if (watermarkOnLeft) leftInput else rightInput
+ def unmatched(key: Int): Row = {
+ if (watermarkOnLeft) Row(null, key, null, 5) else Row(key, null, 5,
null)
+ }
+ withTempDir { checkpoint =>
+ testStream(joined)(
+ StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+ AddData(stateInput, (1, 5)), CheckNewAnswer(),
+ AddData(watermarkInput, (2, 30)), CheckNewAnswer(),
+ AddData(watermarkInput, (2, 40)), CheckNewAnswer(unmatched(1)),
+ StopStream,
+ StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+ // The input without a watermark can add rows below an earlier
eviction cutoff.
+ AddData(stateInput, (3, 5)), CheckNewAnswer(unmatched(3)),
+ AddData(watermarkInput, (3, 5)), CheckNewAnswer(),
+ AddData(watermarkInput, (4, 50)), CheckNewAnswer(),
+ // The watermarked input keeps its state for arbitrarily old rows
of the other input.
+ AddData(stateInput, (2, 30)), CheckNewAnswer(Row(2, 2, 30, 30)))
+ }
+ }
+ }
+ }
+
+ // The input without a watermark is evicted, and its matches within the
range are kept.
+ for {
+ version <- Seq(2, 4)
+ (joinType, watermarkOnLeft) <- Seq(("inner", false), ("inner", true),
("left_semi", false))
+ } {
+ test(s"range eviction needs only the opposite watermark, V$version
$joinType " +
+ s"watermarkOnLeft=$watermarkOnLeft") {
+ withJoinConf(version) {
+ val leftInput = MemoryStream[(Int, Int)]
+ val rightInput = MemoryStream[(Int, Int)]
+ val leftData = leftInput.toDF().toDF("leftKey", "time")
+ .select($"leftKey", timestamp_seconds($"time").as("leftTime"))
+ val rightData = rightInput.toDF().toDF("rightKey", "time")
+ .select($"rightKey", timestamp_seconds($"time").as("rightTime"))
+ val left =
+ if (watermarkOnLeft) leftData.withWatermark("leftTime", "10
seconds") else leftData
+ val right =
+ if (watermarkOnLeft) rightData else
rightData.withWatermark("rightTime", "10 seconds")
+ val joined = left.join(right, expr("leftKey = rightKey AND " +
+ "leftTime BETWEEN rightTime - INTERVAL 5 SECONDS AND " +
+ "rightTime + INTERVAL 5 SECONDS"), joinType)
+ val result = if (joinType == "left_semi") {
+ joined.select($"leftKey", $"leftTime".cast("int"))
+ } else {
+ joined.select($"leftKey", $"rightKey", $"leftTime".cast("int"),
$"rightTime".cast("int"))
+ }
+ val stateInput = if (watermarkOnLeft) rightInput else leftInput
+ val watermarkInput = if (watermarkOnLeft) leftInput else rightInput
+ // A match of a row of stateInput at time s with a row of
watermarkInput at time w.
+ def matched(key: Int, s: Int, w: Int): Row = {
+ if (joinType == "left_semi") {
+ Row(key, s)
+ } else if (watermarkOnLeft) {
+ Row(key, key, w, s)
+ } else {
+ Row(key, key, s, w)
+ }
+ }
+ withTempDir { checkpoint =>
+ testStream(result)(
+ StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+ // The row with key 4 never matches.
+ AddData(stateInput, (1, 5), (4, 5)), CheckNewAnswer(),
+ AddData(watermarkInput, (1, 8)), CheckNewAnswer(matched(1, 5, 8)),
+ AddData(watermarkInput, (2, 30)), CheckNewAnswer(),
+ // At watermark 20 the rows at 5 s of the input without a
watermark are evicted.
+ AddData(watermarkInput, (2, 40)), CheckNewAnswer(),
+ Execute { q =>
+ val numRows = q.lastProgress.stateOperators.head.numRowsTotal
+ assert(numRows === 3)
+ },
+ StopStream,
+ StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+ AddData(stateInput, (3, 5)), CheckNewAnswer(),
+ AddData(stateInput, (2, 30)), CheckNewAnswer(matched(2, 30, 30)))
+ }
+ }
+ }
+ }
+
+ // An earlier version, like the legacy mode, kept every row of such an
input, including one
Review Comment:
**Nit (P3):** These two lines describe the test 'a stored row of an input
without its own watermark whose column is NULL is evicted' further down, not
the cast loop below them, where 'such an input' has no antecedent. Moving them
above that test, and keeping only the cast explanation here, would make each
comment describe its code.
**Verification:**
- **Inspection:** In the one-sided watermark join tests, the comment above
the inexact-cast tests explains only why the casts give no cutoff, and the test
of a stored row whose column is NULL is preceded by the sentence saying that an
earlier version, like the legacy mode, kept every row of such an input,
including one whose bounded column is NULL.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -362,6 +364,45 @@ 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.
+ // They keep the rows of an input without an event time out of the index.
Such rows are never
+ // evicted, which only an outer join that emits the unmatched rows of that
input cannot accept,
+ // so it fails with a checkpoint written by an earlier version or started
in the legacy mode.
+ // TODO: [SPARK-62075] A legacy-mode run of a version 1 checkpoint is not
checked for an input
+ // without an event time. That input has no predicate in the legacy mode,
so the rows of the
+ // run get no index entry, and the default mode never evicts them
afterwards.
+ val indexVersion =
conf.getConf(SQLConf.STREAMING_JOIN_STATE_V4_INDEX_VERSION)
+ if (stateFormatVersion == 4 && (indexVersion == 0 ||
!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,
Review Comment:
**Nit (P3):** This branch picks the column with getStateValueWatermarkColumn
alone, while solve in getStateWatermarkPredicates keeps a column other than the
event time only when the restored checkJoinOutputWatermark is true. Reading the
code, a new state format 4 left outer join on `leftKey = rightKey AND rightTime
BETWEEN leftTime AND expiry`, started with allowMultiple true and
checkJoinOutputWatermark set to false, records index version 1 but orders the
left state by leftTime, because solve drops expiry. Restarting it with
allowMultiple set to false computes expiry here and throws
STREAMING_JOIN_STATE_V4_CHECKPOINT_INCOMPATIBLE for the left input and
`expiry`, although both runs order that state by leftTime. Sharing solve's
column choice, including that filter, with this branch would let it restart and
keep the failure for a checkpoint started with the conf at its default.
**Verification:**
- **Regression:** A new state format 4 left outer join on `leftKey =
rightKey AND rightTime BETWEEN leftTime AND expiry`, started with allowMultiple
true and spark.sql.streaming.statefulOperator.checkJoinOutputWatermark set to
false, restarts with allowMultiple set to false and keeps evicting the left
input by leftTime, where the reviewed head fails with
STREAMING_JOIN_STATE_V4_CHECKPOINT_INCOMPATIBLE.
- **Compatibility:** The same join started with the join output watermark
check at its default still fails that restart, naming the left input and
`expiry`.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -156,6 +157,116 @@ 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 on its event time, 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,
+ * and its join keeps evicting by the event time an input that would
otherwise be evicted by
+ * another column.
+ */
+ 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 on its
event time, 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 the event time of 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.
+ // TODO: An input evicted by a join key other than its event time is not
checked yet, such as
+ // the right input of `leftKey = rightKey AND leftTime = rightTs`, evicted
by rightTs.
+ 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) &&
(
+ // As the join's output watermark, take the cutoff of earlier
versions.
+ StreamingJoinHelper.getStateValueWatermark(input.outputSet,
other.outputSet,
+ condition, Some(1000000), risingCutoffsOnly = false).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
+ }
+
+ // 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:
**Nit (P3):** Only a sliding window, whose window and slide durations
differ, puts an Expand between a streaming aggregation and the join, since
streaming rejects grouping sets and distinct aggregations, and every window in
StreamingJoinOutputWatermarkSuite is tumbling. If this case fell through to
None, a sliding-window aggregation on leftTime after a join bounded on one side
only would be rejected; if it mapped the wrong projection column, one on
rightTime could be accepted and drop joined rows as late, and no test would
fail. A sliding-window aggregation on each input's time after that join, one
expected to run and one to fail naming the right input, would cover both
directions.
**Verification:**
- **Behavior:** A new append-mode query that joins two watermarked inputs on
`leftKey = rightKey AND rightTime <= leftTime + INTERVAL 10 SECONDS` and counts
rows per 10-second window of leftTime sliding every 5 seconds runs and returns
its counts.
- **Behavior:** The same query with the sliding window on rightTime fails at
its first micro-batch with the check's error naming the right input.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -261,28 +266,65 @@ object StreamingSymmetricHashJoinHelper extends Logging {
eventTimeWatermarkForEviction.get,
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 =>
+ } else if (isWatermarkDefinedOnInput || !useFirstEventTimeColumn) {
Review Comment:
Thanks, I checked: a conjunct through a cast that can round or drop digits
no longer gives an input without its own watermark a cutoff, on either input's
column, and the new StreamingJoinOneSidedWatermarkSuite cases cover both casts
for inner and left outer joins on state formats 2 and 4. This review separately
raises a related case in which such an input's cutoff can still be too high: a
bound through an interval with a whole-day part around a daylight-saving change.
<!-- SPARK_DEV_REVIEW_REPLY
{"feedback_id":"inline:4642190874","thread_id":"inline:4642190874","verdict_sha256":"440cfbd3cbf9171c85bd590da6e6659561a718f4190448e2e807c30077325eb1"}
-->
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -261,28 +272,70 @@ object StreamingSymmetricHashJoinHelper extends Logging {
eventTimeWatermarkForEviction.get,
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 =>
+ } else if (isWatermarkDefinedOnInput || !useFirstEventTimeColumn) {
+ // case 2 in the StreamingSymmetricHashJoinExec docs. The opposite
watermark bounds the
+ // future matches, so this input needs no watermark of its own, except
in the legacy mode.
+ val eventTime =
oneSideInputAttributes.find(_.metadata.contains(delayKey))
+ def wholeInput(watermark: Option[Long]): Option[Long] =
StreamingJoinHelper.getStateValueWatermark(
attributesToFindStateWatermarkFor =
AttributeSet(oneSideInputAttributes),
attributesWithEventWatermark =
AttributeSet(otherSideInputAttributes),
condition,
- eventTimeWatermarkForLateEvents).filter(_ <= lateWatermark)
+ watermark)
+ // The column that evicts this input, its cutoff, and whether the
condition bounds that
+ // column. The legacy mode with a single global watermark keeps
applying a cutoff on any
+ // column of this input to the event time. So does the default mode
when the condition
+ // bounds no TIMESTAMP column, such as through a DATE column cast to
TIMESTAMP only.
+ // So does a checkpoint written without the join output watermark
check for an input that
+ // the default mode would evict by another column, since for such a
checkpoint that check
+ // only warns about a later operator that drops the rows this eviction
emits late.
+ // An input without its own watermark that the condition bounds only
through a cast gets
Review Comment:
**Nit (P3):** getStateValueWatermarkColumn drops only conjuncts through a
cast that isInexactCast flags, so a cast that keeps every digit, such as
`CAST(lt AS DOUBLE) >= CAST(rt AS DOUBLE) - 5` or a cast to DECIMAL with a
scale of 6 or more, still gives such an input a cutoff, and this sentence
overstates the rule. When a checkpoint written before this change restores
checkJoinOutputWatermark as false, the filter in solve also drops every column
picked for an input without its own watermark, so such an input is never
evicted after that restart; the comment names that exemption only for an input
with an event time, with a reason that does not apply to one without, and the
conf's doc says only that false makes the join evict by the event time. Stating
the exact-cast rule here, and the earlier-checkpoint exemption in both places,
would let readers see which inputs get no cutoff and why.
**Verification:**
- **Inspection:** The comment above solve in getStateWatermarkPredicates
names every case in which an input without its own watermark gets no cutoff
exactly as the solver and the filter on the restored join output watermark conf
implement them, including a restart from a checkpoint written without that
conf, and the doc of
spark.sql.streaming.statefulOperator.checkJoinOutputWatermark says that false
also keeps such an input from being evicted.
##########
common/utils/src/main/resources/error/error-conditions.json:
##########
@@ -8419,6 +8419,13 @@
],
"sqlState" : "55019"
},
+ "STREAMING_JOIN_STATE_V4_CHECKPOINT_INCOMPATIBLE" : {
+ "message" : [
+ "Cannot restart the stream-stream join from this checkpoint. The
checkpoint and this query order the state format version 4 state of the <side>
input differently: one of them orders it by <column>. This happens with a
checkpoint of an earlier version, or after a change of
spark.sql.streaming.statefulOperator.allowMultiple.",
Review Comment:
**Nit (P3):** A checkpoint of an earlier version restores
spark.sql.streaming.statefulOperator.checkJoinOutputWatermark as false, so
solve keeps a picked column only when it is the event time and an input without
one gets no predicate, and the state format 4 restart check then never throws
for such a checkpoint, as the bundled-fixture restart test of `rightTime
BETWEEN leftTime AND expiry` shows. Only a checkpoint that this version wrote
reaches this error after a change of allowMultiple, and restoring the previous
value restarts it with its state: an index version 0 checkpoint passes the
check in the legacy mode, and an index version 1 checkpoint skips it in the
default mode. Naming the change of allowMultiple as the cause, offering to
restore it or to start a new checkpoint, and dropping earlier-version
checkpoints from the comment above the check in
StreamingSymmetricHashJoinExec.doExecute would point users at a remedy that
keeps their state.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60669#discussion_r4623031796).
**Verification:**
- **Inspection:** The message of
STREAMING_JOIN_STATE_V4_CHECKPOINT_INCOMPATIBLE names a change of
spark.sql.streaming.statefulOperator.allowMultiple as the cause and offers
restoring its previous value or a new checkpoint, and the comment above the
state format 4 restart check no longer says that a checkpoint written by an
earlier version fails it.
- **Behavior:** A state format 4 checkpoint that fails this check after
allowMultiple changed restarts with its state once allowMultiple is restored to
its earlier value, both for a checkpoint started in the legacy mode and for one
started in the default mode.
##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinRangeEvictionSuite.scala:
##########
@@ -0,0 +1,703 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.streaming
+
+import java.io.File
+import java.nio.charset.StandardCharsets.UTF_8
+import java.nio.file.Files
+
+import org.apache.hadoop.fs.Path
+import org.apache.logging.log4j.Level
+
+import org.apache.spark.sql.{AnalysisException, DataFrame, Row}
+import org.apache.spark.sql.catalyst.analysis.StreamingJoinHelper
+import org.apache.spark.sql.execution.streaming.checkpointing.{OffsetMap,
OffsetSeq, OffsetSeqLog}
+import
org.apache.spark.sql.execution.streaming.operators.stateful.join.StreamingSymmetricHashJoinExec
+import
org.apache.spark.sql.execution.streaming.operators.stateful.join.StreamingSymmetricHashJoinHelper.JoinStateValueWatermarkPredicate
+import org.apache.spark.sql.execution.streaming.runtime.MemoryStream
+import org.apache.spark.sql.execution.streaming.state.RocksDBStateStoreProvider
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.tags.SlowSQLTest
+import org.apache.spark.util.Utils
+
+@SlowSQLTest
+class StreamingJoinRangeEvictionSuite extends StateStoreMetricsTest {
+ import testImplicits._
+
+ private def withJoinConf(version: Int)(f: => Unit): Unit = {
+ withSQLConf(
+ SQLConf.STREAMING_JOIN_STATE_FORMAT_VERSION.key -> version.toString,
+ SQLConf.STATE_STORE_PROVIDER_CLASS.key ->
classOf[RocksDBStateStoreProvider].getName,
+ SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> "false")(f)
+ }
+
+ // The left input has the event time leftTime and another TIMESTAMP column
expiry. A negative
+ // start or end gives a NULL leftTime or expiry.
+ private def joinWithExpiry(range: String, joinType: String)
+ : (MemoryStream[(Int, Long, Long)], MemoryStream[(Int, Long)],
DataFrame) = {
+ val leftInput = MemoryStream[(Int, Long, Long)]
+ val rightInput = MemoryStream[(Int, Long)]
+ val left = leftInput.toDF().toDF("leftKey", "start", "end")
+ .select($"leftKey", when($"start" >= 0,
timestamp_seconds($"start")).as("leftTime"),
+ when($"end" >= 0, timestamp_seconds($"end")).as("expiry"))
+ .withWatermark("leftTime", "60 seconds")
+ val right = rightInput.toDF().toDF("rightKey", "time")
+ .select($"rightKey", timestamp_seconds($"time").as("rightTime"))
+ .withWatermark("rightTime", "60 seconds")
+ val condition = expr(s"leftKey = rightKey AND $range")
+ val joined = if (joinType == "right_outer") {
+ right.join(left, condition, joinType)
+ } else {
+ left.join(right, condition, joinType)
+ }
+ val result = joined.select($"leftKey",
$"rightTime".cast("long").as("matchTime"),
+ $"leftTime".cast("long"))
+ (leftInput, rightInput, result)
+ }
+
+ // State format 3 shares the eviction code of format 2.
+ for {
+ version <- Seq(2, 4)
+ joinType <- Seq("inner", "left_outer", "right_outer")
+ shape <- Seq("between", "conjunction", "upper", "interval")
+ } {
+ test(s"range eviction uses the bounded column, V$version $joinType
$shape") {
+ withJoinConf(version) {
+ val range = shape match {
+ case "between" => "rightTime BETWEEN leftTime AND expiry"
+ case "conjunction" => "rightTime >= leftTime AND rightTime <= expiry"
+ case "interval" => "rightTime BETWEEN leftTime AND leftTime +
INTERVAL 10 MINUTES"
+ case _ => "rightTime <= expiry"
+ }
+ val (leftInput, rightInput, result) = joinWithExpiry(range, joinType)
+ testStream(result)(
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (1, 100L, 700L), (2, 100L, 700L)),
AddData(rightInput, (9, 100L)))),
+ CheckNewAnswer(),
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (8, 400L, 1000L)), AddData(rightInput, (9,
400L)))),
+ CheckNewAnswer(),
+ AddData(rightInput, (9, 400L)),
+ // The watermark has passed the start time, but the range has not
expired.
+ CheckNewAnswer(),
+ Execute { query =>
+ val join = query.lastExecution.executedPlan.collectFirst {
+ case j: StreamingSymmetricHashJoinExec => j
+ }.get
+ assert(join.eventTimeWatermarkForEviction.contains(340000L))
+ },
+ AddData(rightInput, (1, 460L)),
+ CheckNewAnswer(Row(1, 460L, 100L)),
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (8, 1000L, 1600L)), AddData(rightInput, (9,
1000L)))),
+ CheckNewAnswer(),
+ AddData(rightInput, (9, 1100L)),
+ CheckNewAnswer((if (joinType != "inner") Seq(Row(2, null, 100L))
else Nil): _*)
+ )
+ }
+ }
+ }
+
+ for {
+ version <- Seq(2, 3, 4)
+ joinType <- Seq("left_outer", "right_outer")
+ } {
+ test(s"range eviction includes newly admitted expired values, V$version
$joinType") {
+ withJoinConf(version) {
+ val (leftInput, rightInput, result) = joinWithExpiry("rightTime <=
expiry", joinType)
+ testStream(result)(
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (8, 100L, 700L)), AddData(rightInput, (9,
100L)))),
+ CheckNewAnswer(),
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (8, 400L, 1000L)), AddData(rightInput, (9,
400L)))),
+ CheckNewAnswer(),
+ AddData(rightInput, (9, 400L)), CheckNewAnswer(),
+ // The start passes late filtering, but expiry is below the previous
eviction cutoff.
+ AddData(leftInput, (3, 460L, 200L)), CheckNewAnswer(Row(3, null,
460L)),
+ AddData(rightInput, (9, 500L)), CheckNewAnswer())
+ }
+ }
+ }
+
+ for {
+ version <- Seq(2, 4)
+ joinType <- Seq("left_outer", "right_outer")
+ } {
+ test(s"a row whose range-eviction column is NULL is emitted on arrival,
V$version $joinType") {
+ withJoinConf(version) {
+ val (leftInput, rightInput, result) =
+ joinWithExpiry("rightTime BETWEEN leftTime AND expiry", joinType)
+ testStream(result)(
+ // The row can never match, so it is not stored, although the next
eviction would remove
+ // it.
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (1, 100L, -1L), (2, 100L, 700L)),
AddData(rightInput, (2, 150L)))),
+ CheckNewAnswer(Row(1, null, 100L), Row(2, 150L, 100L)),
+ assertNumStateRows(total = 2, updated = 2))
+ }
+ }
+ }
+
+ for (version <- Seq(2, 4)) {
+ test(s"a row whose event time is NULL is emitted on arrival, V$version") {
+ withJoinConf(version) {
+ val (leftInput, rightInput, result) = joinWithExpiry(
+ "rightTime BETWEEN leftTime AND leftTime + INTERVAL 10 MINUTES",
"left_outer")
+ testStream(result)(
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (1, -1L, 700L), (2, 100L, 700L)),
AddData(rightInput, (2, 150L)))),
+ CheckNewAnswer(Row(1, null, null), Row(2, 150L, 100L)),
+ assertNumStateRows(total = 2, updated = 2))
+ }
+ }
+ }
+
+ // The condition bounds the left input only through leftDate cast to
TIMESTAMP, so the left
+ // input is evicted by leftTime with the cutoff from leftDate, as in earlier
versions. A negative
+ // start gives a NULL leftTime, which the condition does not reference.
+ private def joinWithDate(joinType: String)
+ : (MemoryStream[(Int, Long, Int)], MemoryStream[(Int, Long)], DataFrame)
= {
+ val leftInput = MemoryStream[(Int, Long, Int)]
+ val rightInput = MemoryStream[(Int, Long)]
+ val left = leftInput.toDF().toDF("leftKey", "start", "day")
+ .select($"leftKey", when($"start" >= 0,
timestamp_seconds($"start")).as("leftTime"),
+ date_add(lit("1970-01-01").cast("date"), $"day").as("leftDate"))
+ .withWatermark("leftTime", "60 seconds")
+ val right = rightInput.toDF().toDF("rightKey", "time")
+ .select($"rightKey", timestamp_seconds($"time").as("rightTime"))
+ .withWatermark("rightTime", "60 seconds")
+ val result = left.join(right,
+ expr("leftKey = rightKey AND CAST(leftDate AS TIMESTAMP) >= rightTime"),
joinType)
+ .select($"leftKey", $"rightTime".cast("long").as("matchTime"),
$"leftTime".cast("long"))
+ (leftInput, rightInput, result)
+ }
+
+ for {
+ version <- Seq(2, 4)
+ joinType <- Seq("inner", "left_outer")
+ } {
+ test(s"an input bounded only through a cast column keeps the earlier
eviction, " +
+ s"V$version $joinType") {
+ withJoinConf(version) {
+ val (leftInput, rightInput, result) = joinWithDate(joinType)
+ testStream(result)(
+ // The left row with a NULL leftTime and a leftDate of one day
matches.
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (1, -1L, 1), (2, 100L, 0)), AddData(rightInput,
(1, 100L)))),
+ CheckNewAnswer(Row(1, 100L, null)),
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (8, 400L, 0)), AddData(rightInput, (1, 400L)))),
+ CheckNewAnswer(Row(1, 400L, null)),
+ // The cutoff on leftTime is 340 s. State format 4 indexed the NULL
leftTime as 0 and
+ // evicted it in the last batch.
+ AddData(rightInput, (1, 500L)),
+ CheckNewAnswer(
+ (if (version == 2) Seq(Row(1, 500L, null)) else Nil) ++
+ (if (joinType == "left_outer") Seq(Row(2, null, 100L)) else
Nil): _*))
+ }
+ }
+ }
+
+ // A left semi join processes its right input first. The right row and the
left row of the
+ // second batch match, and lie between the late-events watermark (0) and the
eviction watermark
+ // (10 h). The cutoff over the whole right input is 7 h, from rx, so the
right row is stored.
+ for (version <- Seq(2, 4)) {
+ test(s"left semi join keeps a right row that the whole-input cutoff keeps,
V$version") {
+ withJoinConf(version) {
+ val leftInput = MemoryStream[(Int, Long)]
+ val rightInput = MemoryStream[(Int, Long, Long)]
+ val left = leftInput.toDF().toDF("k", "t")
+ .select($"k", timestamp_seconds($"t").as("lt"))
+ .withWatermark("lt", "0 seconds")
+ val right = rightInput.toDF().toDF("rk", "e", "x")
+ .select($"rk", timestamp_seconds($"e").as("re"),
timestamp_seconds($"x").as("rx"))
+ .withWatermark("re", "0 seconds")
+ val joined = left.join(right, expr("k = rk AND lt BETWEEN re -
INTERVAL 1 HOUR AND re " +
+ "AND rx >= lt - INTERVAL 3 HOURS"), "left_semi")
+ .select($"k", $"lt".cast("long"))
+ testStream(joined)(
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (9, 36000L)), AddData(rightInput, (9, 36000L,
36000L)))),
+ CheckNewAnswer(Row(9, 36000L)),
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (1, 27000L)), AddData(rightInput, (1, 28800L,
28800L)))),
+ CheckNewAnswer(Row(1, 27000L)))
+ }
+ }
+ }
+
+ // The legacy mode stores rows by the earlier rule: it evicts by the event
time, with the cutoff
+ // from expiry, and keeps a row whose event time is NULL.
+ for (version <- Seq(2, 4)) {
+ test(s"range eviction in the legacy mode keeps the earlier behavior,
V$version") {
+ withJoinConf(version) {
+ withSQLConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key -> "false") {
+ val (leftInput, rightInput, result) =
+ joinWithExpiry("rightTime BETWEEN leftTime AND expiry",
"left_outer")
+ testStream(result)(
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (1, 100L, 700L), (2, 100L, 700L), (3, -1L,
700L)),
+ AddData(rightInput, (9, 100L)))),
+ CheckNewAnswer(),
+ assertNumStateRows(total = 4, updated = 4),
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (8, 400L, 1000L)), AddData(rightInput, (9,
400L)))),
+ // State format 4 indexes a NULL event time as 0.
+ CheckNewAnswer((if (version == 4) Seq(Row(3, null, null)) else
Nil): _*),
+ AddData(rightInput, (9, 400L)),
+ CheckNewAnswer(Row(1, null, 100L), Row(2, null, 100L)),
+ AddData(rightInput, (1, 460L)),
+ CheckNewAnswer())
+ }
+ }
+ }
+ }
+
+ // An earlier version, like the legacy mode, stored a row whose expiry is
NULL and evicted it by
+ // leftTime.
+ for (version <- Seq(2, 3)) {
+ test(s"a stored row whose range-eviction column is NULL is evicted,
V$version") {
+ withJoinConf(version) {
+ withTempDir { checkpoint =>
+ val (leftInput, rightInput, result) =
+ joinWithExpiry("rightTime BETWEEN leftTime AND expiry",
"left_outer")
+ withSQLConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key -> "false")
{
+ testStream(result)(
+ StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (1, 100L, -1L)), AddData(rightInput, (9,
100L)))),
+ CheckNewAnswer(),
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (8, 400L, 1000L)), AddData(rightInput, (9,
400L)))),
+ CheckNewAnswer(),
+ StopStream)
+ }
+ testStream(result)(
+ StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+ AddData(rightInput, (9, 400L)),
+ CheckNewAnswer(Row(1, null, 100L)))
+ }
+ }
+ }
+ }
+
+ // In state format 4, the extra conjunct gives the right side a value
predicate on rightTime, so
+ // that the range scan of the right joiner solves the bound that shifts by a
column.
+ for {
+ bound <- Seq("leftTime > rightTime + rightDelay",
+ "CAST(leftTime AS BIGINT) + leftOffset > CAST(rightTime AS BIGINT)")
+ version <- Seq(2, 4)
+ } {
+ test(s"range eviction does not log solver errors for other columns:
$bound, V$version") {
+ val logAppender = new LogAppender("stream-stream join state constraints")
+ withLogAppender(logAppender,
+ loggerNames =
Seq(StreamingJoinHelper.getClass.getName.stripSuffix("$")),
+ level = Some(Level.WARN)) {
+ withJoinConf(version) {
+ val leftInput = MemoryStream[(Int, Long, Long)]
+ val rightInput = MemoryStream[(Int, Long, Int)]
+ val left = leftInput.toDF().toDF("leftKey", "time", "leftOffset")
+ .select($"leftKey", timestamp_seconds($"time").as("leftTime"),
$"leftOffset")
+ .withWatermark("leftTime", "0 seconds")
+ val right = rightInput.toDF().toDF("rightKey", "time", "delay")
+ .select($"rightKey", timestamp_seconds($"time").as("rightTime"),
+ ($"delay" * expr("INTERVAL 1 SECOND")).as("rightDelay"))
+ .withWatermark("rightTime", "0 seconds")
+ val extra = if (version == 4) " AND leftTime < rightTime + INTERVAL
1 HOUR" else ""
+ val joined = left.join(right, expr(s"leftKey = rightKey AND
$bound$extra"))
+ .select($"leftKey", $"leftTime".cast("long"),
$"rightTime".cast("long"))
+ testStream(joined)(
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (1, 20L, 0L)), AddData(rightInput, (1, 10L,
5)))),
+ CheckNewAnswer(Row(1, 20L, 10L)),
+ AddData(rightInput, (2, 30L, 1)),
+ CheckNewAnswer())
+ }
+ }
+ // A per-row column leaves the bound unknown, which is not an error.
+ assert(!logAppender.loggingEvents.exists(
+ _.getMessage.getFormattedMessage.contains("Error trying to extract
state constraint")))
+ }
+ }
+
+ private val indexVersionKey =
SQLConf.STREAMING_JOIN_STATE_V4_INDEX_VERSION.key
+
+ private def indexVersion(checkpoint: File): Option[String] = {
+ new OffsetSeqLog(spark, new File(checkpoint,
"offsets").getCanonicalPath).getLatest().get._2
+ .metadataOpt.get.conf.get(indexVersionKey)
+ }
+
+ // Removes the V4 index version from the latest offset log entry, as older
versions wrote it.
+ private def removeIndexVersion(checkpoint: File): Unit =
removeConf(checkpoint, indexVersionKey)
+
+ private def removeConf(checkpoint: File, key: String): Unit = {
+ val offsetsPath = new File(checkpoint, "offsets").getCanonicalPath
+ val log = new OffsetSeqLog(spark, offsetsPath)
+ val (batchId, offsets) = log.getLatest().get
+ val updated = offsets match {
+ case o: OffsetSeq =>
+ o.copy(metadataOpt = o.metadataOpt.map(m => m.copy(conf = m.conf -
key)))
+ case o: OffsetMap =>
+ o.copy(metadata = o.metadata.copy(conf = o.metadata.conf - key))
+ }
+ val path = new Path(offsetsPath, batchId.toString)
+ assert(path.getFileSystem(spark.sessionState.newHadoopConf()).delete(path,
false))
+ assert(log.add(batchId, updated))
+ }
+
+ // Copies a bundled checkpoint and points the copied operator metadata at
the state schema files
+ // of the copy. The bundled metadata names them under the placeholder
directory /checkpoint.
+ private def copyCheckpointFixture(name: String, checkpoint: File): Unit = {
+ Utils.copyDirectory(
+ new File(getClass.getResource(s"/structured-streaming/$name/").toURI),
checkpoint)
+ val metadataDir = new File(checkpoint, "state/0/_metadata/v2")
+ metadataDir.listFiles().filter(f => f.isFile &&
!f.getName.startsWith(".")).foreach { file =>
+ val metadata = new String(Files.readAllBytes(file.toPath), UTF_8)
+ val updated = metadata.replace("file:/checkpoint/", new
Path(checkpoint.toURI).toString + "/")
+ assert(updated != metadata, s"No state schema file is named in $file")
+ Files.write(file.toPath, updated.getBytes(UTF_8))
+ }
+ }
+
+ test("V4 restart from an older checkpoint keeps evicting by the event time")
{
+ withJoinConf(4) {
+ withTempDir { checkpoint =>
+ val (leftInput, rightInput, result) = joinWithExpiry(
+ "rightTime BETWEEN leftTime AND leftTime + INTERVAL 10 MINUTES",
"left_outer")
+ testStream(result)(
+ StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (1, 100L, 700L), (2, 100L, 700L)),
AddData(rightInput, (9, 100L)))),
+ CheckNewAnswer(),
+ StopStream)
+ assert(indexVersion(checkpoint) === Some("1"))
+ removeIndexVersion(checkpoint)
+ testStream(result)(
+ StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+ AddData(rightInput, (1, 160L)),
+ CheckNewAnswer(Row(1, 160L, 100L)),
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (8, 1000L, 1600L)), AddData(rightInput, (9,
1000L)))),
+ CheckNewAnswer(),
+ // The cutoff on leftTime is 340 s.
+ AddData(rightInput, (9, 1000L)),
+ CheckNewAnswer(Row(2, null, 100L)),
+ StopStream)
+ assert(indexVersion(checkpoint) === Some("0"))
+ }
+ }
+ }
+
+ // The legacy mode orders the state by the event time.
+ for (legacyFirst <- Seq(true, false)) {
+ test("V4 restart fails when the legacy mode changes and the condition
bounds another " +
+ s"column, legacy first=$legacyFirst") {
+ withJoinConf(4) {
+ withTempDir { checkpoint =>
+ val (leftInput, rightInput, result) =
+ joinWithExpiry("rightTime BETWEEN leftTime AND expiry",
"left_outer")
+ withSQLConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key ->
(!legacyFirst).toString) {
+ testStream(result)(
+ StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (1, 100L, 700L)), AddData(rightInput, (9,
100L)))),
+ CheckNewAnswer(),
+ StopStream)
+ }
+ assert(indexVersion(checkpoint) === Some(if (legacyFirst) "0" else
"1"))
+ withSQLConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key ->
legacyFirst.toString) {
+ testStream(result)(
+ StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+ AddData(rightInput, (9, 400L)),
+ ExpectFailure[AnalysisException] { e =>
+ checkError(
+ e.asInstanceOf[AnalysisException],
+ condition =
"STREAMING_JOIN_STATE_V4_CHECKPOINT_INCOMPATIBLE",
+ parameters = Map("side" -> "left", "column" -> "`expiry`"))
+ })
+ }
+ // The failed restart keeps the recorded version.
+ assert(indexVersion(checkpoint) === Some(if (legacyFirst) "0" else
"1"))
+ }
+ }
+ }
+ }
+
+ // The legacy mode, like earlier versions, evicted left rows only up to the
lower cutoff from
+ // expiry, so the V4 scan after the restart must start at or below that
cutoff.
+ test("V4 restart evicts rows between the earlier and the new cutoff") {
+ withJoinConf(4) {
+ withTempDir { checkpoint =>
+ val (leftInput, rightInput, result) = joinWithExpiry("leftTime >= " +
+ "rightTime - INTERVAL 10 SECONDS AND expiry >= rightTime - INTERVAL
100 SECONDS",
+ "left_outer")
+ withSQLConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key -> "false") {
+ testStream(result)(
+ StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (1, 900L, 5000L), (8, 1000L, 5000L)),
+ AddData(rightInput, (9, 1000L)))),
+ CheckNewAnswer(),
+ // The watermark is 940 s, and the cutoff from expiry keeps
leftTime 900 s.
+ AddData(rightInput, (9, 1000L)),
+ CheckNewAnswer(),
+ StopStream)
+ }
+ testStream(result)(
+ StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+ AddData(rightInput, (9, 1300L)),
+ CheckNewAnswer(Row(1, null, 900L)))
+ }
+ }
+ }
+
+ // Within a run, the V4 scan of the left input starts at the event time's
own cutoff, which is
+ // above the cutoff from expiry.
+ test("V4 range eviction by the event time over several batches of a run") {
+ withJoinConf(4) {
+ val (leftInput, rightInput, result) = joinWithExpiry("leftTime >= " +
+ "rightTime - INTERVAL 10 SECONDS AND expiry >= rightTime - INTERVAL
100 SECONDS",
+ "left_outer")
+ testStream(result)(
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (1, 900L, 5000L), (8, 1000L, 5000L)),
+ AddData(rightInput, (9, 1000L)))),
+ CheckNewAnswer(),
+ // The watermark is 940 s, so the cutoff on leftTime is 930 s.
+ AddData(rightInput, (9, 1000L)),
+ CheckNewAnswer(Row(1, null, 900L)),
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (2, 1200L, 5000L)), AddData(rightInput, (9,
1300L)))),
+ CheckNewAnswer(),
+ // The late-events watermark is 940 s. This batch scans the left input
from the cutoff on
+ // leftTime at it, not from the lower cutoff from expiry.
+ Execute { q =>
+ val join = q.lastExecution.executedPlan.collectFirst {
+ case j: StreamingSymmetricHashJoinExec => j
+ }.get
+ assert(join.stateWatermarkPredicates.left.get
+ .asInstanceOf[JoinStateValueWatermarkPredicate].prevStateWatermark
=== Some(929999L))
+ },
+ // The watermark is 1140 s, so the cutoff on leftTime is 1130 s.
+ AddData(rightInput, (2, 1300L)),
+ CheckNewAnswer(Row(8, null, 1000L)),
+ AddData(rightInput, (9, 1300L)),
+ CheckNewAnswer())
+ }
+ }
+
+ // A legacy-mode restart of a checkpoint that orders the state by the event
time works.
+ test("V4 restart in the legacy mode of a join evicted by the event time") {
+ withJoinConf(4) {
+ withTempDir { checkpoint =>
+ val (leftInput, rightInput, result) = joinWithExpiry(
+ "rightTime BETWEEN leftTime AND leftTime + INTERVAL 10 MINUTES",
"left_outer")
+ testStream(result)(
+ StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (1, 100L, 700L), (2, 100L, 700L)),
AddData(rightInput, (9, 100L)))),
+ CheckNewAnswer(),
+ StopStream)
+ assert(indexVersion(checkpoint) === Some("1"))
+ withSQLConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key -> "false") {
+ testStream(result)(
+ StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+ AddData(rightInput, (1, 160L)),
+ CheckNewAnswer(Row(1, 160L, 100L)),
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (8, 1000L, 1600L)), AddData(rightInput, (9,
1000L)))),
+ CheckNewAnswer(),
+ AddData(rightInput, (9, 1000L)),
+ CheckNewAnswer(Row(2, null, 100L)))
+ }
+ }
+ }
+ }
+
+ test("V4 restart in the legacy mode fails for the right input that is
evicted by another " +
+ "column") {
+ withJoinConf(4) {
+ withTempDir { checkpoint =>
+ val (leftInput, rightInput, result) =
+ joinWithExpiry("rightTime BETWEEN leftTime AND expiry",
"right_outer")
+ testStream(result)(
+ StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (1, 100L, 700L)), AddData(rightInput, (9,
100L)))),
+ CheckNewAnswer(),
+ StopStream)
+ withSQLConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key -> "false") {
+ testStream(result)(
+ StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+ AddData(rightInput, (9, 400L)),
+ ExpectFailure[AnalysisException] { e =>
+ checkError(
+ e.asInstanceOf[AnalysisException],
+ condition = "STREAMING_JOIN_STATE_V4_CHECKPOINT_INCOMPATIBLE",
+ parameters = Map("side" -> "right", "column" -> "`expiry`"))
+ })
+ }
+ }
+ }
+ }
+
+ // Only state format 4 orders the state by the column, and the check covers
both inputs.
+ for ((version, joinType) <- Seq((2, "left_outer"), (4, "right_outer"), (4,
"inner"))) {
+ test(s"restart from a checkpoint without the index version, V$version
$joinType") {
+ withJoinConf(version) {
+ withTempDir { checkpoint =>
+ val (leftInput, rightInput, result) =
+ joinWithExpiry("rightTime BETWEEN leftTime AND expiry", joinType)
+ testStream(result)(
+ StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (1, 100L, 700L)), AddData(rightInput, (9,
100L)))),
+ CheckNewAnswer(),
+ StopStream)
+ removeIndexVersion(checkpoint)
+ testStream(result)(
+ StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+ AddData(rightInput, (1, 460L)),
+ if (version == 4) {
+ ExpectFailure[AnalysisException] { e =>
+ checkError(
+ e.asInstanceOf[AnalysisException],
+ condition =
"STREAMING_JOIN_STATE_V4_CHECKPOINT_INCOMPATIBLE",
+ parameters = Map("side" -> (if (joinType == "right_outer")
"right" else "left"),
+ "column" -> "`expiry`"))
+ }
+ } else {
+ CheckNewAnswer(Row(1, 460L, 100L))
+ })
+ }
+ }
+ }
+ }
+
+ // A checkpoint written without the join output watermark check keeps the
earlier eviction, which
+ // never evicted an input without its own watermark.
+ test("restart from a checkpoint without the output watermark check for an
input without its " +
+ "own watermark") {
+ withJoinConf(2) {
Review Comment:
**Nit (P3):** This restart without the output watermark check's conf is the
only one for an input without its own watermark, and it runs on state format 2.
The state format 4 restarts of such inputs remove only the index version after
a legacy-mode run, which records the conf as true, and every stored-NULL-row
test also restarts from a legacy-mode run. So if the state format 4 restart
check derived the column of an index version 0 checkpoint as its version 1
branch does, every upgraded state format 4 outer join with such an input would
fail to restart, and if solve dropped the event-time arm of its filter,
upgraded time-interval joins would keep their stored NULL-event-time rows
forever, with no test failing. A state format 4 variant of this restart, and a
state format 2 time-interval restart that holds a left row with a NULL
leftTime, both with the conf removed, would pin those behaviors.
**Verification:**
- **Behavior:** A state format 4 left outer join with a watermark only on
the right input and `leftKey = rightKey AND leftTime BETWEEN rightTime -
INTERVAL 5 SECONDS AND rightTime + INTERVAL 5 SECONDS`, first run in the legacy
mode with the left rows (1, 5 seconds) and (2, 5 seconds) and then restarted in
the default mode from an offset log without the join output watermark check and
the index version, restarts without
STREAMING_JOIN_STATE_V4_CHECKPOINT_INCOMPATIBLE, matches the left row of key 2
with a right row (2, 8 seconds) that arrives right after the restart, and, once
right rows of another key move the right watermark past 10 seconds, emits no
row with a null right side for the left row of key 1 and keeps it in state.
- **Behavior:** A state format 2 left outer join on `leftKey = rightKey AND
rightTime BETWEEN leftTime AND leftTime + INTERVAL 10 MINUTES`, first run in
the legacy mode with a stored left row whose leftTime is NULL and then
restarted in the default mode from an offset log without the join output
watermark check, emits that row with a null right side at the first eviction
and removes it from state.
--
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]