spark-test commented on code in PR #60282:
URL: https://github.com/apache/spark/pull/60282#discussion_r4606680286
##########
docs/streaming/ss-migration-guide.md:
##########
@@ -25,6 +25,171 @@ Please refer [Migration Guide: SQL, Datasets and
DataFrame](../sql-migration-gui
## Upgrading from Structured Streaming 4.3 to 4.4
+- Since Spark 4.4, left outer and left semi stream-stream joins require a
watermark on the
+ right input and a time condition that limits how late a matching right row
can arrive.
+ Right outer joins require the corresponding settings on the left; full outer
joins require
+ them on both sides. An equality key counts as such a time condition when it
is the other
+ input's event time, or that event time shifted by constant intervals, except
a shift with
+ months, years, or a day-time interval of 24 hours or more that can move a
time backward. To
+ decide this without the session time zone, Spark counts each day as 12 to 36
hours and each
+ month as 28 to 31 such days, takes the shortest length for an added term and
the longest for a
+ subtracted one, and counts a key only when the total is never negative. So
+ `leftTime = rightTime + INTERVAL 1 DAY - INTERVAL 1 HOUR` counts. A key such
as
+ `leftTime = rightTime - INTERVAL 1 DAY`, `leftTime = rightTime - INTERVAL 36
HOURS`,
+ `leftTime = rightTime + INTERVAL 1 DAY - INTERVAL 13 HOURS`,
+ `leftTime = rightTime + INTERVAL 5 DAYS - INTERVAL 2 DAYS` or
+ `leftTime = rightTime + INTERVAL 1 MONTH - INTERVAL 15 DAYS`, or one
truncated from the other
+ input's event time, such as
+ `leftTime = CAST(CAST(rightTime AS BIGINT) AS TIMESTAMP)`, does not count,
while
+ `timestampadd` in hours, minutes or seconds does, whatever the amount. When
both inputs
+ have watermarks, a time range condition between the two event times can
bound such a join
+ instead. Some previously accepted queries now fail if these requirements are
not met. Update
+ their watermarks and join conditions using the
+ [join support
table](apis-on-dataframes-and-datasets.html#support-matrix-for-joins-in-streaming-queries).
+ A stateful operator after such a join that uses the other input's event time
also needs that
+ input bounded: for example, a left outer join followed by an append-mode
aggregation over the
+ right event time also needs a watermark on the left input and a time
condition that limits
+ how late a matching left row can arrive: an equality with an exact shift (an
interval under
+ one day, or `timestampadd` in hours, minutes or seconds), or a range
condition in place of a
+ shifted equality. Without them, the join holds back its output
+ watermark, and an append-mode aggregation right after the join, with no
later stream-stream
+ join in between, fails at start (see below) because it would never emit
results.
+
+- Since Spark 4.4, a time condition can finalize an input that has no
watermark of its own, such
+ as impressions without a watermark joined on
+ `clickTime BETWEEN impressionTime AND impressionTime + INTERVAL 1 HOUR`.
Such a bound must
+ have an exact length. An interval of a day or more, such as `INTERVAL 1 DAY`
or
+ `INTERVAL 48 HOURS`, or a truncating cast such as `CAST(impressionTime AS
BIGINT)`, does not
+ finalize that input in any session time zone, because Spark adds whole days
in the session
+ time zone, where a day can last 23 or 25 hours. An outer or left semi join
that relies on such
+ a bound fails analysis. Use an exact bound instead, such as a bound shorter
than a day on the
+ TIMESTAMP columns in place of the cast. A watermark on that input lets the
join run, but the
+ cutoff then counts a day as 24 hours and reads the cast as exact, so it can
finalize a row that
+ a later row still matches, in a time zone where a day lasts 25 hours or by
up to a second with
+ the cast.
+
+- Since Spark 4.4, you can set
`spark.sql.streaming.join.checkFinalization.enabled` to `false`
+ to run a stream-stream outer or left semi join that fails the requirement
above, or a query
+ that fails the start-time check for an aggregation after a join, below.
Spark then logs a
+ warning instead of failing the query. Joins that earlier versions also
rejected, such as an
+ outer join without a watermarked equality key or a range condition on a
watermarked event
+ time, still fail. The corrected state eviction cannot be turned
+ off: such a query keeps the state of the input that lacks a bound for the
life of the query,
+ and an outer join never outputs that input's unmatched rows. Because the
corrected eviction
+ changes results and cannot be turned off, these stream-stream join
corrections are made in
+ Spark 4.4.0 and are not backported to earlier releases.
+
+- Spark 4.4 corrects cases where stream-stream equality joins could discard
rows before their
+ matches arrived or output unmatched rows too early. Such joins with a
watermark on only one
+ input now keep the watermarked input's rows for the life of the query,
because the other input
+ has no watermark that bounds them, and hold back the join's output watermark
for that input.
+ An append-mode aggregation right after the join, with no later stream-stream
join in between,
+ over that input's event time then fails at start. Other stateful operators
after the join that
+ use it keep its rows in state and do not emit results that wait for the
watermark, such as
+ event-time timeouts and an aggregation behind a later stream-stream join,
while update-mode
+ aggregations and deduplication still emit rows. Add a watermark on the other
input to bound
+ those rows.
+
+- With `spark.sql.streaming.statefulOperator.allowMultiple` set to `false`, an
input of a
+ stream-stream join can keep several watermarked columns, such as its event
time together with a
+ copy of it or a time window over it, and late rows are filtered by whichever
of them comes
+ first in the planned input. As in earlier versions, an equality key on any
watermarked column
+ of an input bounds the other input's state, so a join on the window of an
input built with
+ `withColumn("window", window($"ts", ...))` still bounds the other input's
state by that
+ window. Since Spark 4.4,
+ when Spark can see that some rows of the input hold the key below a
watermarked column before
+ it, the key bounds the other input's state at the watermark less that
amount: the shift for a
+ key built from a time shifted backward by a fixed interval, and the window's
length for a copy
+ of, or a window over, a column that an earlier watermarked window is built
over. Earlier
+ versions removed rows that could still match in these cases. Which column
filters late rows
+ depends on column pruning: a copy placed after a window is filtered by its
source when the
+ query reads the source after the join, and by the window otherwise. Analysis
takes the largest
+ amount over the watermarked columns that can come first, and execution the
amount for the one
+ that does, so the other input keeps its rows, and an outer join outputs its
unmatched rows, up
+ to that amount later. A key that rows can hold below by an amount that Spark
cannot bound no
+ longer bounds state: one built from a time shifted backward by whole days,
months or years,
+ one that copies a column that an earlier session window with a gap that is
not constant is
+ built over, and one that an input of a union builds from a column without a
watermark, also in
+ a batch where that input has no data. Outer
+ and left semi joins on such a key now fail, and inner joins keep the other
input's rows for the
+ life of the query. To bound state, join on the first watermarked column
itself or on a time
+ window over it, or select the key before the other watermarked columns of
its input. A range
+ condition on a watermarked column after the first one bounds state at that
column's watermark
+ less the same amount, but only when Spark can see how the column is built
from the ones before
+ it. Spark can also see this through an earlier inner join whose condition
equates a
+ watermarked column of each of its inputs, such as `at = bt`, or bounds one
of them from below by
+ the other plus constant intervals, such as `bt BETWEEN at AND at + INTERVAL
1 HOUR`, and through
+ an earlier left or right outer join with such a condition for a column of
the input that it pads
+ with nulls.
+ When each such condition relates the columns by an amount that Spark cannot
bound, the column
+ bounds no state, as above. Among the keys that bound state, Spark prefers
one whose amount it
+ can see over one that the plan does not relate to the column that filters
late rows. Spark
+ reuses a checkpoint from an earlier version of a join whose only watermarked
equality key, at
+ the same position in both inputs, bounds state at the watermark itself, such
as a join on a
+ time window over the first watermarked column, or on that column while the
input also keeps
+ the window. Other checkpoints from earlier versions of joins on a
watermarked column after the
+ first one are rejected at restart, as described below.
+
+- Spark 4.4 holds back the output watermark of a stream-stream join when
retained state can
+ still emit old event times. Downstream stateful operators may retain more
state, take longer
+ to finalize results, or never emit results that wait for the watermark while
the join has no
+ event-time eviction bound.
+ The join holds back only for an input whose event time reaches the next
stateful operator: in
+ a join on `clickTime <= impressionTime + INTERVAL 1 HOUR`, a window
aggregation over
+ `impressionTime` makes progress, and one over `clickTime` does not. Spark
follows the event
+ time through projections, filters, unions, stream-static joins, and time and
session windows,
+ to aggregations, deduplication, stream-stream joins,
`flatMapGroupsWithState` and
+ `applyInPandasWithState` with event-time timeouts, and `transformWithState`
in event-time
+ mode. It also follows an event time plus constant intervals with no negative
+ part, such as `impressionTime + INTERVAL 1 MINUTE`, which never falls below
that event time.
+ When Spark cannot tell which input's event time the operator uses, for
example when the
+ operator's event time subtracts an interval or is computed by another
function, it holds back
+ for both inputs.
+
+ Since Spark 4.4, a query fails at start with
`STREAMING_JOIN_UNBOUNDED_DOWNSTREAM_EVENT_TIME`
+ when an append-mode aggregation after a stream-stream join uses the event
time of a join input
+ whose state the join cannot bound, because that aggregation would never emit
results. The
+ error names the input and the missing watermark or time constraint. Spark
judges the
+ aggregation against the nearest stream-stream join that its event time
reaches. An aggregation
+ behind a later stream-stream join is not rejected yet (SPARK-61509): it
starts and does not
+ emit results while an earlier join holds back its output watermark, as do
event-time timeouts
+ and a later outer join. An aggregation in update output mode, or one whose
event time Spark
+ cannot trace to a join input, is not rejected either.
+
+- When restarting a stream-stream join from an older Spark version, Spark may
reject the
+ existing checkpoint with `STREAMING_JOIN_CHECKPOINT_INCOMPATIBLE`. Spark
reuses the checkpoint
+ of a join without watermarks, of a join with an equality condition between
the two inputs'
+ event times, such as `leftTime = rightTime`, and of a join whose time
condition compares the
+ two inputs' event times with each other by an ordering comparison (`<`,
`<=`, `>`, `>=` or
+ `BETWEEN`), each event time optionally cast and offset by constant intervals
or numbers, such as
+ `rightTime BETWEEN leftTime AND leftTime + INTERVAL 1 HOUR`. An equality in
which one event time
+ is shifted or cast, such as `leftTime = rightTime + INTERVAL 1 SECOND`, is
rejected. When such a
Review Comment:
**Nit (P3):** This sentence says that `leftTime = rightTime + INTERVAL 1
SECOND` is rejected, but the same paragraph later says that Spark reuses the
checkpoint of an equality with the other event time shifted forward by constant
intervals when no stateful operator after the join reads the shifted input's
event time, and `forwardShiftedKey` in `isWatermarkCheckpointCompatible`
accepts a one-second forward shift under that condition. An upgrader who trusts
this sentence prepares to rebuild a checkpoint that Spark reuses, which the
guide warns needs input history that may no longer exist. The equality shapes
the check rejects are casts and truncations, backward shifts, shifts on both
keys, and forward shifts whose shifted event time a later stateful operator
reads.
**Verification:**
- **Inspection:** In the restart paragraph of the Structured Streaming
migration guide, every equality example called rejected is one the restart
check rejects, and the forward-shift example called reused is accepted when no
stateful operator after the join uses the shifted input's event time.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -705,33 +716,171 @@ object UnsupportedOperationChecker extends Logging {
plan = operator)
}
- private def checkForStreamStreamJoinWatermark(join: Join): Unit = {
- val watermarkInJoinKeys = StreamingJoinHelper.isWatermarkInJoinKeys(join)
-
- // Check if the nullable side has a watermark, and there's a range
condition which
- // implies a state value watermark on the first side.
- val hasValidWatermarkRange = join.joinType match {
- case LeftOuter | LeftSemi => StreamingJoinHelper.getStateValueWatermark(
- join.left.outputSet, join.right.outputSet, join.condition,
Some(1000000)).isDefined
- case RightOuter => StreamingJoinHelper.getStateValueWatermark(
- join.right.outputSet, join.left.outputSet, join.condition,
Some(1000000)).isDefined
- case FullOuter =>
- Seq((join.left.outputSet, join.right.outputSet),
- (join.right.outputSet, join.left.outputSet)).exists {
- case (attributesToFindStateWatermarkFor,
attributesWithEventWatermark) =>
-
StreamingJoinHelper.getStateValueWatermark(attributesToFindStateWatermarkFor,
- attributesWithEventWatermark, join.condition,
Some(1000000)).isDefined
- }
+ private def checkForStreamStreamJoinWatermark(
+ join: Join,
+ eventTimeLags: EventTimeLags): Unit = {
+ val keys = ExtractEquiJoinKeys.unapply(join)
+ val leftKeys = keys.map(_._2).getOrElse(Nil)
+ val rightKeys = keys.map(_._3).getOrElse(Nil)
+
+ // TODO(SPARK-61348): this accepts a range bound on a column that is not
TIMESTAMP,
+ // which eviction never finalizes.
+ // TODO(SPARK-61349): this also accepts a bound that uses only constants,
which does not
+ // follow the other input's watermark and so cannot finalize unmatched
state.
+ def canEvictState(
+ stateInput: LogicalPlan,
+ otherInput: LogicalPlan,
+ otherKeys: Seq[Expression],
+ exactForUnwatermarkedColumns: Boolean = true): Boolean = {
+ // Any watermarked column of the other input can bound state: each
planned input keeps one
+ // distinct watermarked column when multiple stateful operators are
allowed, or execution
+ // fails at start, and in legacy mode its lag lowers the cutoff.
+ StreamingJoinHelper.getStateKeyWatermarkOrdinal(
+ otherKeys, otherInput.output, Some(eventTimeLags)).isDefined ||
+
StreamingJoinHelper.getStateValueWatermarkForLags(stateInput.outputSet,
otherInput.output,
+ join.condition, Some(1000000), Some(eventTimeLags),
+ exactForUnwatermarkedColumns).isDefined
+ }
+
+ // The rule of Spark versions before 4.4: a watermarked equality key, or a
range bound that the
+ // solver finds for a finalized input. Disabling the finalization check
never goes below it.
+ def admittedBeforeFinalizationCheck: Boolean = {
+ def hasRangeBound(stateInput: LogicalPlan, otherInput: LogicalPlan):
Boolean =
+ StreamingJoinHelper.getStateValueWatermark(stateInput.outputSet,
otherInput.outputSet,
+ join.condition, Some(1000000)).isDefined
+ (leftKeys ++ rightKeys).exists {
+ case a: AttributeReference =>
a.metadata.contains(EventTimeWatermark.delayKey)
+ case _ => false
+ } || (join.joinType match {
+ case LeftOuter | LeftSemi => hasRangeBound(join.left, join.right)
+ case RightOuter => hasRangeBound(join.right, join.left)
+ case _ => hasRangeBound(join.left, join.right) ||
hasRangeBound(join.right, join.left)
+ })
+ }
+
+ val leftCanEvict = canEvictState(join.left, join.right, rightKeys)
+ val rightCanEvict = canEvictState(join.right, join.left, leftKeys)
+ val hasRequiredWatermarks = join.joinType match {
+ case LeftOuter | LeftSemi => leftCanEvict
+ case RightOuter => rightCanEvict
+ case FullOuter => leftCanEvict && rightCanEvict
case _ =>
throwError(
s"Join type ${join.joinType} is not supported with streaming
DataFrame/Dataset")(join)
}
- if (!watermarkInJoinKeys && !hasValidWatermarkRange) {
- throwError(
+ if (!hasRequiredWatermarks) {
+ val requirement = join.joinType match {
+ case FullOuter => "watermarks on both inputs and time constraints in
both directions"
+ case RightOuter => "a watermark on the left input and a time
constraint"
+ case _ => "a watermark on the right input and a time constraint"
+ }
+ val allowMultiple =
SQLConf.get.getConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE)
+ // The join holds back its output watermark for an input whose state is
unbounded. Legacy
+ // mode gives every operator the one global watermark and ignores the
join's output
+ // watermark, so a later operator neither fails at start nor stalls
there.
+ val downstreamRequirement = join.joinType match {
+ case _ if !allowMultiple => None
+ case LeftOuter => Some(("right", "left"))
+ case RightOuter => Some(("left", "right"))
+ case _ => None
+ }
+ // The error says that such an aggregation fails at start, when no later
stream-stream join
+ // separates it from this one, which is the only one that the start-time
check judges. The
+ // warning is logged only with the finalization check disabled, which
lets the query start,
+ // so such an aggregation never emits instead.
+ def downstreamNote(aggregationOutcome: String): String =
+ downstreamRequirement.map { case (eventTimeInput, boundingInput) =>
+ s" A stateful operator after the join that uses the $eventTimeInput
input's event " +
+ s"time also needs a watermark on the $boundingInput input and a
reverse time " +
+ "constraint; otherwise the join holds back its output watermark
for that input, so " +
+ s"an append-mode aggregation over that event time
$aggregationOutcome, and other " +
+ "operators, such as an aggregation behind a later stream-stream
join, keep that " +
+ "input's rows in state and do not emit results that wait for the
watermark."
+ }.getOrElse("")
+ // In legacy mode an input can keep several watermarked columns and
filters late rows by
+ // the first of them. A later watermarked key bounds state, lowered by
how far the plan
+ // shows that some rows can hold it below a watermarked column before it.
+ val legacyKeyNote = if (allowMultiple) {
+ ""
+ } else {
+ def keyNote(input: LogicalPlan, inputKeys: Seq[Expression], side:
String): String = {
+ val eventTime =
input.output.find(_.metadata.contains(EventTimeWatermark.delayKey))
+ val rejectedKey = inputKeys.collectFirst {
+ case n: NamedExpression
+ if eventTimeLags.lagOf(n, input.output).exists(_.unbounded) =>
n
+ }
+ val note = for (first <- eventTime; key <- rejectedKey) yield {
+ s" With ${SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key}=false, the
$side input " +
+ s"filters late rows by its first watermarked column,
${first.name}, and some of " +
+ s"its rows can hold the key ${key.name} below a watermarked
column before it by " +
+ s"an amount that analysis cannot bound, so ${key.name} does not
bound state. " +
+ s"This happens when ${key.name} is built from a time shifted
backward by whole " +
Review Comment:
**Nit (P3):** This list reads as complete, but `lagThroughJoinCondition` now
returns `EventTimeLag.unbounded` when every conjunct of an earlier
stream-stream join that relates the key's column to the late-filtered column
has a shift with whole days that can move a time backward, such as `bt >= at -
INTERVAL 1 DAY`, which `StreamingJoinLegacyEventTimeKeySuite` pins for a window
over `bt`. A legacy-mode right outer join on `lk = rk AND lw = rw`, with `lw =
window(bt, '10 seconds')` over such an earlier join, then fails analysis with
this note, none of whose three causes applies, and the user is never told that
the earlier join's condition is the cause. Legacy mode is reached only through
the internal `spark.sql.streaming.statefulOperator.allowMultiple` setting.
**Verification:**
- **Regression:** With
spark.sql.streaming.statefulOperator.allowMultiple=false, a right outer join
whose left key is a time window over a column that an earlier stream-stream
join ties to the late-filtered column only through a condition such as `bt >=
at - INTERVAL 1 DAY` fails analysis with a note that names the earlier join's
condition as the cause.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala:
##########
@@ -721,14 +1006,81 @@ class IncrementalExecution(
override def apply(plan: SparkPlan): SparkPlan = {
val planWithStateOpId = plan transform composedRule
+ // Validate the checkpoint-pinned semantics before writing state
metadata or opening state,
+ // including a restart retrying an incomplete batch zero.
+ if (isFirstBatchWithOlderJoinWatermarkSemantics) {
+ def watermarkColumns(input: SparkPlan): String = {
+ val columns = input.output.filter(
+ _.metadata.contains(EventTimeWatermark.delayKey))
+ if (columns.isEmpty) "none" else columns.map(_.name).mkString(", ")
+ }
+ // In the default mode, a join's output watermark reaches every
stateful operator above
+ // it. One that uses its input watermark reads the inputs that the
tracer names, or both
+ // inputs when it cannot be traced. An operator uses it when an input
carries an
+ // event-time column, when it fires event-time timeouts, or when it
passes the watermark
+ // to user code, as transformWithState does in every time mode. The
join's output
+ // watermark changes nothing for any other operator, such as an
update-mode count on a
+ // key.
+ def usesInputWatermark(operator: StatefulOperator): Boolean = operator
match {
+ case _: TransformWithStateExec | _: TransformWithStateInPySparkExec
=> true
+ case f: FlatMapGroupsWithStateExec if f.timeoutConf ==
EventTimeTimeout => true
+ case f: FlatMapGroupsInPandasWithStateExec if f.timeoutConf ==
EventTimeTimeout => true
+ case _ => operator.children.exists(
+ _.output.exists(_.metadata.contains(EventTimeWatermark.delayKey)))
+ }
+ val joinsBelowStatefulOperators = planWithStateOpId.collect {
+ case s: StatefulOperator if usesInputWatermark(s) =>
s.children.flatMap(_.collect {
+ case j: StreamingSymmetricHashJoinExec =>
j.stateInfo.map(_.operatorId)
+ }.flatten)
+ }.flatten.toSet
+ val tracedSides = joinWatermarkConsumers(planWithStateOpId)
+ .groupMap(_.joinOperatorId)(_.side)
+ // The inputs whose state watermark reaches an operator through the
join's output
+ // watermark. With a single global watermark, the propagator never
reads the join's
+ // output watermark, and a left semi join's output watermark reads
only its left input.
+ def consumedSides(j: StreamingSymmetricHashJoinExec): Set[JoinSide] =
+ j.stateInfo.map(_.operatorId) match {
+ case Some(id)
+ if allowMultipleStatefulOperators &&
joinsBelowStatefulOperators.contains(id) =>
+ val sides: Set[JoinSide] =
+ tracedSides.get(id).map(_.toSet).getOrElse(Set(LeftSide,
RightSide))
+ if (j.joinType == LeftSemi) sides - RightSide else sides
+ case _ => Set.empty
+ }
+ planWithStateOpId.foreach {
+ case j: StreamingSymmetricHashJoinExec
+ if
!StreamingSymmetricHashJoinHelper.isWatermarkCheckpointCompatible(
+ j.left.output, j.right.output, j.leftKeys, j.rightKeys,
j.condition.full,
+ consumedSides(j), j.stateFormatVersion, eventTimeLags) =>
+ // Name the side of each equality key; both inputs often use the
same column names.
+ val keyConditions = j.leftKeys.zip(j.rightKeys).map { case (left,
right) =>
+ s"left.${left.sql} = right.${right.sql}"
+ }
+ val conditions = keyConditions ++ j.condition.full.map(_.sql)
+ val joinCondition = if (conditions.isEmpty) "none" else
conditions.mkString(" AND ")
+ throw new AnalysisException(
+ errorClass = "STREAMING_JOIN_CHECKPOINT_INCOMPATIBLE",
+ messageParameters = Map(
+ "joinCondition" -> joinCondition,
+ "leftWatermarkColumns" -> watermarkColumns(j.left),
+ "rightWatermarkColumns" -> watermarkColumns(j.right)))
+ case _ =>
+ }
+ }
+ // Like the checkpoint check, this runs before state metadata is written
or state opened.
+ // With a single global watermark, the join's output watermark does not
reach the consumers.
+ if (isFirstBatch && allowMultipleStatefulOperators) {
Review Comment:
**Nit (P3):** This condition judges the first batch of every run, and
`spark.sql.streaming.join.checkFinalization.enabled` is not among the confs
that the offset log pins, so a restart can enable the check after a run that
disabled it. Every test that expects
`STREAMING_JOIN_UNBOUNDED_DOWNSTREAM_EVENT_TIME`, in
`StreamingJoinOutputWatermarkSuite` and the append case of `join with range
join on non-time intervals -> window agg` in `MultiStatefulOperatorsSuite`,
fails in batch 0 of a fresh query. Narrowing this condition to `currentBatchId
== 0` would therefore fail no test, while a query restarted after a run with
the check disabled, or after its downstream aggregation changed to an unbounded
input's event time, would start and keep an aggregation that never emits.
**Verification:**
- **Regression:** A query with an append-mode aggregation over an event time
that the join cannot bound, run with
spark.sql.streaming.join.checkFinalization.enabled=false and then restarted
from its checkpoint with the check enabled, fails on the restarted run with
STREAMING_JOIN_UNBOUNDED_DOWNSTREAM_EVENT_TIME, and the test fails when the
check runs only in batch 0 of a query.
##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinOutputWatermarkSuite.scala:
##########
@@ -0,0 +1,515 @@
+/*
+ * 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.sql.Timestamp
+
+import org.apache.logging.log4j.Level
+
+import org.apache.spark.sql.{AnalysisException, DataFrame, Encoders, Row}
+import org.apache.spark.sql.execution.SparkPlan
+import org.apache.spark.sql.execution.joins.{BroadcastHashJoinExec,
BroadcastNestedLoopJoinExec, SortMergeJoinExec}
+import
org.apache.spark.sql.execution.streaming.operators.stateful.join.StreamingSymmetricHashJoinExec
+import
org.apache.spark.sql.execution.streaming.operators.stateful.join.StreamingSymmetricHashJoinHelper.{JoinSide,
LeftSide, RightSide}
+import org.apache.spark.sql.execution.streaming.runtime.{MemoryStream,
StreamExecution}
+import org.apache.spark.sql.execution.streaming.state.RocksDBStateStoreProvider
+import org.apache.spark.sql.functions.{broadcast, col, count, expr, lit,
session_window, timestamp_seconds, window}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.tags.SlowSQLTest
+
+@SlowSQLTest
+class StreamingJoinOutputWatermarkSuite extends StreamTest {
+ import testImplicits._
+
+ for (version <- Seq(2, 3, 4)) {
+ test(s"unbounded join state can emit an old event time after watermarks
advance, V$version") {
+ 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, Long)]
+ val rightInput = MemoryStream[(Int, Long)]
+ val left = leftInput.toDF().toDF("key", "seconds")
+ .select($"key", timestamp_seconds($"seconds").as("leftTime"))
+ .withWatermark("leftTime", "10 seconds")
+ val right = rightInput.toDF().toDF("key", "seconds")
+ .select($"key", timestamp_seconds($"seconds").as("rightTime"))
+ .withWatermark("rightTime", "10 seconds")
+ val result = left.join(right, Seq("key"))
+ .select($"key", $"leftTime")
+ .dropDuplicatesWithinWatermark("key")
+ .select($"key", $"leftTime".cast("long"))
+
+ testStream(result)(
+ MultiAddData((leftInput, Seq((1, 5L))), (rightInput, Seq((9, 5L)))),
+ CheckNewAnswer(),
+ MultiAddData((leftInput, Seq((2, 30L))), (rightInput, Seq((3,
30L)))),
+ CheckNewAnswer(),
+ // Process another batch so the join's output watermark reaches
downstream operators.
+ AddData(rightInput, (4, 40L)),
+ CheckNewAnswer(),
+ // The retained left key 1 can still join after both input
watermarks reach 20 seconds.
+ // The right event is newer than that watermark, but the joined left
time is only 5.
+ AddData(rightInput, (1, 100L)),
+ CheckNewAnswer((1, 5L)),
+ Execute { query =>
+ val join = query.lastExecution.executedPlan.collectFirst {
+ case j: StreamingSymmetricHashJoinExec => j
+ }.get
+ assert(join.eventTimeWatermarkForLateEvents.contains(20000L))
+ assert(join.produceOutputWatermark(20000L).contains(0L))
+ })
+ }
+ }
+ }
+
+ // Impressions are bounded by the click watermark; clicks have no lower
bound on clickTime.
+ private def oneDirectionalJoin(): (MemoryStream[(Int, Long)],
MemoryStream[(Int, Long)],
+ DataFrame) = {
+ val impressionInput = MemoryStream[(Int, Long)]
+ val clickInput = MemoryStream[(Int, Long)]
+ val impressions = impressionInput.toDF().toDF("impressionAdId", "seconds")
+ .select($"impressionAdId",
timestamp_seconds($"seconds").as("impressionTime"))
+ .withWatermark("impressionTime", "10 seconds")
+ val clicks = clickInput.toDF().toDF("clickAdId", "seconds")
+ .select($"clickAdId", timestamp_seconds($"seconds").as("clickTime"))
+ .withWatermark("clickTime", "10 seconds")
+ val joined = impressions.join(clicks,
+ expr("clickAdId = impressionAdId AND clickTime <= impressionTime +
INTERVAL 10 SECONDS"))
+ (impressionInput, clickInput, joined)
+ }
+
+ private def windowCounts(
+ df: DataFrame,
+ timeColumn: String,
+ slide: String = "10 seconds"): DataFrame = {
+ df.groupBy(window(col(timeColumn), "10 seconds",
slide)).agg(count("*").as("count"))
+ .select($"window.start".cast("long"), $"count")
+ }
+
+ // The join that reads the inputs, below any stream-stream join after it.
+ private def join(query: StreamExecution): StreamingSymmetricHashJoinExec = {
+ query.lastExecution.executedPlan.collect {
+ case j: StreamingSymmetricHashJoinExec
+ if
!j.children.exists(_.exists(_.isInstanceOf[StreamingSymmetricHashJoinExec])) =>
j
+ }.head
+ }
+
+ private def runOneDirectionalJoin(
+ impressionInput: MemoryStream[(Int, Long)],
+ clickInput: MemoryStream[(Int, Long)],
+ result: DataFrame,
+ expectedRows: Seq[Row],
+ expectedSides: Option[Set[JoinSide]],
+ expectedOutputWatermark: Long,
+ checkPlan: SparkPlan => Unit = _ => ()): Unit = {
+ withSQLConf(SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key ->
"false") {
+ testStream(result, OutputMode.Append())(
+ MultiAddData((impressionInput, Seq((1, 5L), (2, 15L), (3, 25L))),
+ (clickInput, Seq((1, 8L), (2, 20L)))),
+ ProcessAllAvailable(),
+ // The click at 30 seconds joins the retained impression at 25 seconds.
+ MultiAddData((impressionInput, Seq((4, 60L))), (clickInput, Seq((3,
30L), (9, 70L)))),
+ ProcessAllAvailable(),
+ MultiAddData((impressionInput, Seq((5, 100L))), (clickInput, Seq((9,
110L)))),
+ ProcessAllAvailable(),
+ AddData(clickInput, (9, 150L)),
+ ProcessAllAvailable(),
+ AddData(impressionInput, (6, 200L)),
+ ProcessAllAvailable(),
+ CheckAnswer(expectedRows: _*),
+ Execute { query =>
+ checkPlan(query.lastExecution.executedPlan)
+ val j = join(query)
+ assert(j.outputWatermarkSides == expectedSides)
+ assert(j.produceOutputWatermark(j.eventTimeWatermarkForEviction.get)
+ .contains(expectedOutputWatermark))
+ // No joined row arrives behind the watermark of the operator after
the join.
+ assert(query.recentProgress.flatMap(_.stateOperators)
+ .map(_.numRowsDroppedByWatermark).sum == 0)
+ })
+ }
+ }
+
+ test("output watermark follows the bounded input when only its event time is
used") {
Review Comment:
**Nit (P3):** This test pins the right-side filter of
`produceOutputWatermark` (79.999 seconds over `impressionTime`), but nothing
pins its left-side mirror. In every test that traces only the right input, the
right state watermark is 0: the `clickTime` cases of this suite, the first run
of `V4 chained joins scan from the start after the plan between them changes`
in `StreamingJoinCheckpointCompatibilitySuite`, and the crossed-key test in
`StreamingJoinEqualityOutputWatermarkSuite`. Replacing
`leftStateWatermark.filter(_ => sides.contains(LeftSide))` with
`leftStateWatermark` in `StreamingSymmetricHashJoinExec` therefore fails no
test, while a join whose left input it cannot bound, followed by a window count
over its bounded right input's event time, would hold the output watermark at 0
and never emit.
**Verification:**
- **Regression:** For a join that cannot bound its left input but bounds its
right input, followed by an append-mode window count over the right input's
event time, the join's output watermark equals the right input's state
watermark and the window counts are emitted, and the test fails when the left
input's state watermark is not filtered out.
##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinSuite.scala:
##########
@@ -2425,6 +2802,350 @@ abstract class StreamingLeftSemiJoinBase extends
StreamingJoinSuite {
}
}
+ // A left semi join processes the right input before the left input. A right
row at or below
+ // its eviction cutoff passes late filtering when it is above the
late-events watermark, and
+ // the left rows of the same batch must still find it. Each case runs a
batch whose
+ // late-events watermark is 100 seconds and whose eviction watermark is
`watermark` seconds.
+ // (name, condition, left time, right time, watermark, state rows after the
second batch and
+ // after the third)
+ for ((name, condition, leftTime, rightTime, watermark, rowsBefore,
rowsAfter) <- Seq(
+ ("equal event times", "leftTime = rightTime", 102, 102, 105, 2L, 0L),
+ // The left key leftTime + 10 seconds of (7, 100) stays above the
100-second cutoff.
+ ("a key shifted by less than the watermark step",
+ "leftTime + INTERVAL 10 SECONDS = rightTime", 120, 130, 150, 3L, 1L),
+ // The right key cutoff is the watermark plus 10 seconds less 1 ms, so
the right row
+ // (1, 112) is at or below it although the watermark advances by only 5
seconds. The left
+ // keys of (7, 100) and (7, 105) stay above the 105-second left cutoff.
+ ("a key shifted by more than the watermark step",
+ "leftTime + INTERVAL 10 SECONDS = rightTime", 102, 112, 105, 2L, 2L),
+ // A value cutoff of the watermark less 10 seconds and 1 ms: (1, 130) is
below 139.999 s.
+ ("a time interval",
+ "leftTime BETWEEN rightTime - INTERVAL 10 SECONDS AND rightTime +
INTERVAL 10 SECONDS",
+ 125, 130, 150, 4L, 2L))) {
+ test(s"left semi join keeps a same-batch match between the watermarks:
$name") {
+ withSQLConf(SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key ->
"false") {
+ val leftInput = MemoryStream[(Int, Int)]
+ val rightInput = MemoryStream[(Int, Int)]
+ val left = leftInput.toDF()
+ .select($"_1".as("leftKey"), timestamp_seconds($"_2").as("leftTime"))
+ .withWatermark("leftTime", "0 seconds")
+ val right = rightInput.toDF()
+ .select($"_1".as("rightKey"),
timestamp_seconds($"_2").as("rightTime"))
+ .withWatermark("rightTime", "0 seconds")
+ val joined = left.join(right, expr(s"leftKey = rightKey AND
$condition"), "left_semi")
+ .select($"leftKey", $"leftTime".cast("int"))
+
+ testStream(joined)(
+ MultiAddData(leftInput, (7, 100))(rightInput, (8, 100)),
+ CheckNewAnswer(),
+ MultiAddData(leftInput, (7, watermark))(rightInput, (8, watermark)),
+ CheckNewAnswer(),
+ assertNumStateRows(total = rowsBefore, updated = 4),
+ MultiAddData(leftInput, (1, leftTime))(rightInput, (1, rightTime)),
+ CheckNewAnswer((1, leftTime)),
+ // The right row is stored for the left row to probe and removed at
the end of the
+ // batch, together with the other rows at or below the cutoffs.
+ assertNumStateRows(total = rowsAfter, updated = 1))
+ }
+ }
+ }
+
+ // The right cutoff comes from a bound on rightExpiry. The right row (1,
110, 160) matches the
+ // left row (1, 120) of the same batch and is evicted at its end, whether
the cutoff is applied
+ // to rightExpiry or to rightTime. Storing only the right rows above the
cutoff at the
+ // late-events watermark would drop this match when the cutoff is applied to
rightTime.
+ test("left semi join keeps a same-batch match bounded by another right
column") {
+ withSQLConf(SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key ->
"false") {
+ val leftInput = MemoryStream[(Int, Int, Int)]
+ val rightInput = MemoryStream[(Int, Int, Int)]
+ val left = leftInput.toDF()
+ .select($"_1".as("leftKey"), timestamp_seconds($"_2").as("leftTime"))
+ .withWatermark("leftTime", "0 seconds")
+ val right = rightInput.toDF()
+ .select($"_1".as("rightKey"), timestamp_seconds($"_2").as("rightTime"),
+ timestamp_seconds($"_3").as("rightExpiry"))
+ .withWatermark("rightTime", "0 seconds")
+ val joined = left.join(right, expr("leftKey = rightKey AND " +
+ "rightExpiry >= leftTime + INTERVAL 30 SECONDS AND " +
+ "leftTime >= rightTime - INTERVAL 1 HOUR"), "left_semi")
+ .select($"leftKey", $"leftTime".cast("int"))
+
+ testStream(joined)(
+ MultiAddData(leftInput, (7, 100, 0))(rightInput, (8, 100, 100)),
+ CheckNewAnswer(),
+ MultiAddData(leftInput, (7, 150, 0))(rightInput, (8, 150, 150)),
+ CheckNewAnswer(),
+ assertNumStateRows(total = 3, updated = 4),
+ // The late-events watermark is 100 seconds, and the right cutoff at
it is 130 seconds
+ // less 1 ms: above the right row's rightTime of 110 seconds, below
its rightExpiry.
+ MultiAddData(leftInput, (1, 120, 0))(rightInput, (1, 110, 160)),
+ CheckNewAnswer((1, 120)),
+ assertNumStateRows(total = 2, updated = 1))
+ }
+ }
+
+ // With equal watermarks, a left row that passes late filtering has a time
above the watermark,
+ // so a right row that the right cutoff evicts in its arrival batch cannot
match it. Here the
+ // right cutoff applies to rightExpiry, the column that the condition
bounds, so the right row
+ // stays in state and matches the later left row. The same-batch decision to
skip or store an
+ // evicted right row is covered by the default-mode test above and the tests
of the exact
+ // cutoffs below.
+ test("left semi join applies the right cutoff to the bounded right column
when both " +
Review Comment:
**Nit (P3):** The name says that the right cutoff goes to `rightExpiry`, but
the only assertion is `CheckNewAnswer((1, 120))` in the right row's own batch.
If the cutoff of 130 seconds less 1 ms were applied to `rightTime` instead, the
right row `(1, 110, 1000)` would still be stored, because
`getLeftSemiExactRightCutoffs` finds no key cutoff (`leftTime` is not a join
key) and no value cutoff (`leftTime >= rightTime - INTERVAL 1 HOUR` bounds
`rightTime` only from above), so the match would still be emitted and only the
eviction at the end of the batch would differ, which the test does not observe.
The comment's "later left row" also arrives in the same batch.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60282#discussion_r4598420050).
**Verification:**
- **Regression:** With
spark.sql.streaming.statefulOperator.allowMultiple=false and equal watermarks,
the right row (1, 110, 1000) stays in state after its batch and a later left
row such as (1, 125) matches it, and the test fails when the right cutoff is
applied to rightTime, which removes that row at the end of its batch.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -186,6 +942,39 @@ object StreamingJoinHelper extends PredicateHelper with
Logging {
return None
}
+ // The terms count a whole day as 24 hours, although Spark adds days in
the session time
+ // zone, where a day can be 23 or 25 hours, and read CAST(ts AS BIGINT) as
ts, although the
+ // cast drops the fraction of a second. Either can put the cutoff above a
row that can still
+ // match. A column with its own watermark keeps such a cutoff, as existing
queries rely on
+ // it. With exactForUnwatermarkedColumns, any other column, such as the
bounded column of an
+ // input without a watermark, gets no cutoff from such a condition.
+ // TODO(SPARK-61381): count a day as 12 to 36 hours and a truncating cast
by its loss, so that
+ // such a column gets a conservative cutoff. Until then an inner join on
+ // `rightTime <= expiry + INTERVAL 1 DAY`, with `expiry` lacking a
watermark, keeps every
+ // left row, and an outer or left semi join of that shape fails analysis.
+ val stateColumnHasWatermark = constraintTerm.exists {
+ case a: AttributeReference =>
+ attributesToFindStateWatermarkFor.contains(a) &&
a.metadata.contains(delayKey)
+ case _ => false
+ }
+ if (exactForUnwatermarkedColumns && !stateColumnHasWatermark &&
Review Comment:
**Blocking (P1):** This gate tests the constrained column
(`stateColumnHasWatermark`), not its input, and since 0ad26f2a1fa
`hasInexactArithmetic` counts an interval of a day or more as inexact in every
session time zone. Take impressions watermarked on `impressionTime` with
`dayStart = date_trunc('DAY', impressionTime)`, joined to clicks watermarked on
`clickTime` on `adId = clickAdId AND clickTime >= impressionTime AND clickTime
< dayStart + INTERVAL 1 DAY`, in UTC. On the base branch,
`getOneSideStateWatermarkPredicate` solved the impressions over all of their
columns and evicted them at `impressionTime <= watermark - 1 day`, which is
correct there because `dayStart` never exceeds `impressionTime` and a UTC day
is 24 hours, and the left outer form passed analysis. At this head, `clickTime
>= impressionTime` bounds `impressionTime` only from above and the `dayStart`
conjunct stops at this gate, so by the review's reading of the code:
- the inner join keeps every impression for the life of the query, also in
the default state format 2, where the V4 layout reason for the zone-independent
rule does not apply;
- an append-mode window count over `impressionTime` right after the join
fails at start with `STREAMING_JOIN_UNBOUNDED_DOWNSTREAM_EVENT_TIME`;
- the left outer, right outer, full outer and left semi forms that need the
impressions finalized fail analysis, and the inexact-bound note tells the user
that a watermark on that input lets the join run, although the impressions
already have one.
The PR description says that columns with their own watermark keep their
cutoffs, the migration guide scopes the rule to an input without a watermark,
and the reply on the V4 layout accepts a cost only for such inputs, so nothing
states or accepts this regression for watermarked inputs, and upgrading users
get no migration note. In daylight-saving zones the base branch could evict
these rows up to an hour early, so there the change corrects results at the
same cost.
This extends existing discussions
[1](https://github.com/apache/spark/pull/60282#discussion_r4523762419),
[2](https://github.com/apache/spark/pull/60282#discussion_r4531361718),
[3](https://github.com/apache/spark/pull/60282#discussion_r4598420028).
**Recommended change:** Either remove the regression or state and accept it.
To remove it, land in this PR the conservative day count that SPARK-61381
plans: for a column without its own watermark, count each whole day of an
interval as 12 to 36 hours and a truncating cast by its loss, whichever keeps
more rows, as intervalShift already counts days for equality keys, instead of
giving the column no cutoff, so that such a column gets a cutoff in every
session time zone and these joins pass analysis again. To state and accept it
instead, say in the PR description and in the Structured Streaming migration
guide for 4.3 to 4.4 that a watermarked input whose only lower bound is an
interval of a day or more on another of its columns, one without its own
watermark such as a day-start column built with date_trunc, is no longer
finalized in any session time zone, including UTC, where Spark 4.3 finalized it
correctly: an inner join keeps its rows, an append-mode aggregation over its
event t
ime right after the join fails at start, and an outer or left semi join that
needs it finalized fails analysis. Name the conservative count as the
alternative and why it waits for SPARK-61381. Either way, correct the analysis
error's inexact-bound note, which tells users that a watermark on that input
lets the join run even when the input already has one and the bound is on
another of its columns.
**Why this works:** A conservative count keeps each cutoff at or below every
value that local-day arithmetic in any zone can give, so it removes no row that
can still match while bounding state, and it does not read the session time
zone, so the V4 index column stays the same across restarts. Stating the
regression instead gives users of watermarked inputs the notice that the
migration guide already gives for inputs without a watermark, so they can
change such a bound before upgrading.
**Risks:** With the conservative count, an input bounded through such an
interval keeps up to 12 more hours of rows per day of the interval than an
exact count would, in every session time zone. If the regression is accepted
instead, inner joins of these shapes keep state that grows for the life of the
query, and their outer and left semi forms fail analysis, until SPARK-61381
lands.
**Constraints:** A column without its own watermark must not get a cutoff
that a 25-hour day or a truncating cast can put above a row that can still
match. Whether a column gets a cutoff must not depend on the session time zone,
so the V4 index column and lookup ordinal stay the same across restarts. The
admission check must keep applying the rule that eviction applies. Columns with
their own watermark keep their current cutoffs.
**Exclusions:**
- Bounds on columns with their own watermark, which keep the 24-hour day of
the base branch.
- Bounds on columns that are not TIMESTAMP and bounds that use only
constants, which later PRs in the stack handle.
**Verification:**
- **Regression:** In UTC and in America/Los_Angeles, the left outer and
inner forms of a join of impressions watermarked on impressionTime with clicks,
bounded only by clickTime < dayStart + INTERVAL 1 DAY with dayStart =
date_trunc('DAY', impressionTime), either evict impressions and emit the
unmatched ones without losing a match, or behave as the PR description and the
migration guide document.
- **Behavior:** The analysis error for that left outer join names the bound
on a column without its own watermark and gives advice that applies to an input
that already has a watermark.
- **Compatibility:** Cutoffs for columns with their own watermark and for
exact sub-day bounds are unchanged, and a state format 4 join restarted between
UTC and America/Los_Angeles still stores and finds rows by the same column.
##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinSuite.scala:
##########
@@ -2425,6 +2802,275 @@ abstract class StreamingLeftSemiJoinBase extends
StreamingJoinSuite {
}
}
+ // A left semi join processes the right input before the left input. A right
row at or below
+ // its eviction cutoff passes late filtering when it is above the
late-events watermark, and
+ // the left rows of the same batch must still find it. Each case runs a
batch whose
+ // late-events watermark is 100 seconds and whose eviction watermark is
`watermark` seconds.
+ // (name, condition, left time, right time, watermark, state rows after the
second batch and
+ // after the third)
+ for ((name, condition, leftTime, rightTime, watermark, rowsBefore,
rowsAfter) <- Seq(
+ ("equal event times", "leftTime = rightTime", 102, 102, 105, 2L, 0L),
+ // The left key leftTime + 10 seconds of (7, 100) stays above the
100-second cutoff.
+ ("a key shifted by less than the watermark step",
+ "leftTime + INTERVAL 10 SECONDS = rightTime", 120, 130, 150, 3L, 1L),
+ // The right key cutoff is the watermark plus 10 seconds less 1 ms, so
the right row
+ // (1, 112) is at or below it although the watermark advances by only 5
seconds. The left
+ // keys of (7, 100) and (7, 105) stay above the 105-second left cutoff.
+ ("a key shifted by more than the watermark step",
+ "leftTime + INTERVAL 10 SECONDS = rightTime", 102, 112, 105, 2L, 2L),
+ // A value cutoff of the watermark less 10 seconds and 1 ms: (1, 130) is
below 139.999 s.
+ ("a time interval",
+ "leftTime BETWEEN rightTime - INTERVAL 10 SECONDS AND rightTime +
INTERVAL 10 SECONDS",
+ 125, 130, 150, 4L, 2L))) {
+ test(s"left semi join keeps a same-batch match between the watermarks:
$name") {
+ withSQLConf(SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key ->
"false") {
+ val leftInput = MemoryStream[(Int, Int)]
+ val rightInput = MemoryStream[(Int, Int)]
+ val left = leftInput.toDF()
+ .select($"_1".as("leftKey"), timestamp_seconds($"_2").as("leftTime"))
+ .withWatermark("leftTime", "0 seconds")
+ val right = rightInput.toDF()
+ .select($"_1".as("rightKey"),
timestamp_seconds($"_2").as("rightTime"))
+ .withWatermark("rightTime", "0 seconds")
+ val joined = left.join(right, expr(s"leftKey = rightKey AND
$condition"), "left_semi")
+ .select($"leftKey", $"leftTime".cast("int"))
+
+ testStream(joined)(
+ MultiAddData(leftInput, (7, 100))(rightInput, (8, 100)),
+ CheckNewAnswer(),
+ MultiAddData(leftInput, (7, watermark))(rightInput, (8, watermark)),
+ CheckNewAnswer(),
+ assertNumStateRows(total = rowsBefore, updated = 4),
+ MultiAddData(leftInput, (1, leftTime))(rightInput, (1, rightTime)),
+ CheckNewAnswer((1, leftTime)),
+ // The right row is stored for the left row to probe and removed at
the end of the
+ // batch, together with the other rows at or below the cutoffs.
+ assertNumStateRows(total = rowsAfter, updated = 1))
+ }
+ }
+ }
+
+ // The right cutoff comes from a bound on rightExpiry. The right row (1,
110, 160) matches the
+ // left row (1, 120) of the same batch and is evicted at its end, whether
the cutoff is applied
+ // to rightExpiry or to rightTime. Storing only the right rows above the
cutoff at the
+ // late-events watermark would drop this match when the cutoff is applied to
rightTime.
+ test("left semi join keeps a same-batch match bounded by another right
column") {
+ withSQLConf(SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key ->
"false") {
+ val leftInput = MemoryStream[(Int, Int, Int)]
+ val rightInput = MemoryStream[(Int, Int, Int)]
+ val left = leftInput.toDF()
+ .select($"_1".as("leftKey"), timestamp_seconds($"_2").as("leftTime"))
+ .withWatermark("leftTime", "0 seconds")
+ val right = rightInput.toDF()
+ .select($"_1".as("rightKey"), timestamp_seconds($"_2").as("rightTime"),
+ timestamp_seconds($"_3").as("rightExpiry"))
+ .withWatermark("rightTime", "0 seconds")
+ val joined = left.join(right, expr("leftKey = rightKey AND " +
+ "rightExpiry >= leftTime + INTERVAL 30 SECONDS AND " +
+ "leftTime >= rightTime - INTERVAL 1 HOUR"), "left_semi")
+ .select($"leftKey", $"leftTime".cast("int"))
+
+ testStream(joined)(
+ MultiAddData(leftInput, (7, 100, 0))(rightInput, (8, 100, 100)),
+ CheckNewAnswer(),
+ MultiAddData(leftInput, (7, 150, 0))(rightInput, (8, 150, 150)),
+ CheckNewAnswer(),
+ assertNumStateRows(total = 3, updated = 4),
+ // The late-events watermark is 100 seconds, and the right cutoff at
it is 130 seconds
+ // less 1 ms: above the right row's rightTime of 110 seconds, below
its rightExpiry.
+ MultiAddData(leftInput, (1, 120, 0))(rightInput, (1, 110, 160)),
+ CheckNewAnswer((1, 120)),
+ assertNumStateRows(total = 2, updated = 1))
+ }
+ }
+
+ test("left semi join keeps a same-batch match bounded by another right
column when both " +
+ "watermarks are equal") {
+ withSQLConf(SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> "false",
+ SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key -> "false") {
+ val leftInput = MemoryStream[(Int, Int, Int)]
+ val rightInput = MemoryStream[(Int, Int, Int)]
+ val left = leftInput.toDF()
+ .select($"_1".as("leftKey"), timestamp_seconds($"_2").as("leftTime"))
+ .withWatermark("leftTime", "0 seconds")
+ val right = rightInput.toDF()
+ .select($"_1".as("rightKey"), timestamp_seconds($"_2").as("rightTime"),
+ timestamp_seconds($"_3").as("rightExpiry"))
+ .withWatermark("rightTime", "0 seconds")
+ val joined = left.join(right, expr("leftKey = rightKey AND " +
+ "rightExpiry >= leftTime + INTERVAL 30 SECONDS AND " +
+ "leftTime >= rightTime - INTERVAL 1 HOUR"), "left_semi")
+ .select($"leftKey", $"leftTime".cast("int"))
+
+ testStream(joined)(
+ MultiAddData(leftInput, (7, 100, 0))(rightInput, (8, 100, 100)),
+ CheckNewAnswer(),
+ // Both watermarks are 100 seconds, and the right cutoff is 130
seconds less 1 ms. The
+ // right row passes late filtering but is at or below the cutoff on
rightTime, and the
Review Comment:
Thanks, the new name and comment no longer say that this test reaches the
same-batch eviction. This review raises a follow-up on the renamed test: its
assertions pass whichever right column takes the cutoff.
<!-- SPARK_DEV_REVIEW_REPLY
{"feedback_id":"inline:4598420050","thread_id":"inline:4598420050","verdict_sha256":"063fbdbac14a46a77e438b5bdb33f859328b048129afc32d63fa830b110bae16"}
-->
--
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]