spark-test commented on code in PR #60282:
URL: https://github.com/apache/spark/pull/60282#discussion_r4531362216
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -706,32 +707,44 @@ object UnsupportedOperationChecker extends Logging {
}
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
- }
+ val keys = ExtractEquiJoinKeys.unapply(join)
+ val leftKeys = keys.map(_._2).getOrElse(Nil)
+ val rightKeys = keys.map(_._3).getOrElse(Nil)
+
+ def canEvictState(
Review Comment:
Thanks, understood that #60283 and #60284 remove this gap. The stack's PRs
still merge one at a time, though, so until they land master would admit these
joins with nothing at `canEvictState` or `getStateValueWatermarkForInput`
saying the gap is known. A one-line TODO naming SPARK-61348 and SPARK-61349 at
each spot is enough, and #60283 can delete it together with the gap. This stays
a minor, non-blocking nit.
<!-- SPARK_DEV_REVIEW_REPLY
{"feedback_id":"inline:4523762383","thread_id":"inline:4523762383","verdict_sha256":"0042e4c7c6b7cb7775269472085f92208cfa538c4b2cb792572e86e16bb88411"}
-->
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -717,6 +729,22 @@ case class StreamingSymmetricHashJoinExec(
Predicate.create(Literal(false), Seq.empty).eval _ // false = do not
remove if no predicate
}
+ // A NULL in the column that the state watermark predicate tests makes the
predicate unknown,
+ // so eviction never removes the row. The row cannot match either: that
column is an equality
+ // key, or a comparison in the join condition bounds it. Handle the row
like one that fails
+ // the pre-join filter.
+ private[this] val isEvictionColumnNull: UnsafeRow => Boolean = {
+ val isNull = stateWatermarkPredicate.map {
+ case JoinStateKeyWatermarkPredicate(expr, _, _) =>
+ // Only a NULL key fails equality. A struct key with a NULL field
can still be equal.
+ val ordinal = expr.collectFirst { case b: BoundReference =>
b.ordinal }.get
+ IsNull(joinKeys(ordinal))
Review Comment:
**Nit (P3):** For a key eviction predicate this evaluates the selected key
expression on the input row, and `keyGenerator` evaluates it again for every
row that passes. With an attribute key that costs only a null-bit read, but a
computed key such as `lt + INTERVAL 10 SECONDS` now goes through its interval
addition, with a time-zone conversion, twice per input row, where the base
branch computed it once. Generating the key first and testing
`key.isNullAt(ordinal)` keeps the same NULL handling.
**Verification:**
- **Regression:** The join tests for a NULL selected key or window end,
including the V4 full outer null-window tests, produce the same rows.
- **Inspection:** For a side with a key eviction predicate, the input-row
loop evaluates the key expressions only in keyGenerator.
##########
docs/streaming/apis-on-dataframes-and-datasets.md:
##########
@@ -1297,6 +1297,15 @@ joined <- join(
Outer joins have the same guarantees as [inner
joins](#semantic-guarantees-of-stream-stream-inner-joins-with-watermarking)
regarding watermark delays and whether data will be dropped or not.
+Unmatched output and state removal use the same cutoff, derived from the
opposite input's
+watermark and the time constraint. In the example above, the `clickTime`
watermark finalizes
+impressions; no watermark on `impressionTime` is needed for this. Without that
watermark, the
+time constraint must have an exact length: whole days in a session time zone
with daylight saving
Review Comment:
**Non-blocking (P2):** The code is broader than this sentence.
`hasInexactArithmetic` treats any day-time interval of 24 hours or more as
whole days, which Spark adds as local days, so `INTERVAL 48 HOURS` is rejected
too, and it does so in every session time zone that is not fixed-offset,
including region IDs without daylight saving time today, such as Asia/Tokyo. A
user whose one-sided outer join is rejected also gets the generic analysis
error, which says the join needs a watermark on the right input and a time
constraint, both of which the query has, and the migration guide names only
those two requirements. Neither text points to what works: a watermark on the
bounded input, a fixed-offset session time zone, a bound shorter than a day, or
`spark.sql.streaming.join.checkFinalization.enabled=false`.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60282#discussion_r4523762419).
**Verification:**
- **Behavior:** A one-sided left outer join with a one-day bound, and one
with a 48-hour bound, under America/Los_Angeles fail analysis with a message
naming an interval of a day or more in a zone that is not a fixed offset, while
a join that lacks the right watermark keeps the existing message.
- **Inspection:** The join guide and the migration guide say that intervals
of a day or more in any session time zone that is not a fixed offset, and
truncating casts, do not finalize an input without its own watermark.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -706,32 +707,66 @@ object UnsupportedOperationChecker extends Logging {
}
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
- }
+ val keys = ExtractEquiJoinKeys.unapply(join)
+ val leftKeys = keys.map(_._2).getOrElse(Nil)
+ val rightKeys = keys.map(_._3).getOrElse(Nil)
+
+ def canEvictState(
+ stateInput: LogicalPlan,
+ otherInput: LogicalPlan,
+ otherKeys: Seq[Expression]): Boolean = {
+ val eventTime =
otherInput.output.find(_.metadata.contains(EventTimeWatermark.delayKey))
+ StreamingJoinHelper.getStateKeyWatermarkOrdinal(otherKeys,
otherInput.output).isDefined ||
+ StreamingJoinHelper.getStateValueWatermark(stateInput.outputSet,
+ AttributeSet(eventTime.toSeq), join.condition, Some(1000000),
+ exactForUnwatermarkedColumns = true).isDefined
+ }
+
+ 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"
+ }
+ // The join holds back its output watermark for an input whose state is
unbounded.
+ val downstreamRequirement = join.joinType match {
+ case LeftOuter => Some(("right", "left"))
+ case RightOuter => Some(("left", "right"))
+ case _ => None
+ }
+ val downstreamNote = downstreamRequirement.map { case (eventTimeInput,
boundingInput) =>
+ s" A stateful operator after the join that uses the $eventTimeInput
input's event time " +
+ s"also needs a watermark on the $boundingInput input and a reverse
time constraint; " +
+ "otherwise the join holds back its output watermark and that
operator stops " +
Review Comment:
**Nit (P3):** A held-back output watermark stops only results that wait for
the watermark, such as append-mode aggregations, and the downstream operator's
state eviction. An update-mode aggregation keeps emitting updated rows
(MultiStatefulOperatorsSuite's join-to-window test expects (0, 4), (10, 1) and
(0, 5) in update mode), and deduplication keeps emitting first occurrences.
This note, and the migration guide's equality-join bullet that says such an
operator 'stops emitting results', can lead users to restructure queries that
would keep producing output, while not telling them that the operator's state
grows.
**Verification:**
- **Inspection:** The downstream note in the admission error and the
migration guide's equality-join bullet limit the stopped output to
watermark-driven results and state eviction.
##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinOutputWatermarkSuite.scala:
##########
@@ -0,0 +1,171 @@
+/*
+ * 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.{DataFrame, Row}
+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.{col, count, expr, 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): DataFrame = {
+ df.groupBy(window(col(timeColumn), "10
seconds")).agg(count("*").as("count"))
+ .select($"window.start".cast("long"), $"count")
+ }
+
+ private def join(query: StreamExecution): StreamingSymmetricHashJoinExec = {
+ query.lastExecution.executedPlan.collectFirst {
+ case j: StreamingSymmetricHashJoinExec => j
+ }.get
+ }
+
+ private def runOneDirectionalJoin(
+ impressionInput: MemoryStream[(Int, Long)],
+ clickInput: MemoryStream[(Int, Long)],
+ result: DataFrame,
+ expectedRows: Seq[Row],
+ expectedSides: Option[Set[JoinSide]],
+ expectedOutputWatermark: Long): 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 =>
+ 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 is the only test whose assertion depends on narrowing.
The `dropDuplicatesWithinWatermark` test above expects 0 with or without it,
because both state watermarks are 0; the 'downstream' `dropDuplicates` shape in
`StreamingJoinRangeEvictionSuite` evicts the consumed side on expiry, so its
state watermark is 0 too; and `StreamingJoinSelectedEventTimeSuite` disables
multiple stateful operators. Dropping `StreamingDeduplicateExec`,
`StreamingDeduplicateWithinWatermarkExec` or `StreamingSymmetricHashJoinExec`
from the consumer pattern would hold those pipelines at 0, with deduplication
state never evicted and a downstream outer join never emitting unmatched rows,
and every test would still pass.
See **Shared repair plan 1** in the review body.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -403,19 +408,21 @@ case class StreamingSymmetricHashJoinExec(
// Create left and right side hash joiners and store in the joiner manager.
// Both sides should use the same store generator if we are re-using the
same store instance.
val joinStateManagerStoreGenerator = new JoinStateManagerStoreGenerator()
- val joinKeyOrdinalForWatermark =
-
StreamingSymmetricHashJoinHelper.findJoinKeyOrdinalForWatermark(leftKeys,
rightKeys)
val joinerManager = OneSideHashJoinerManager(
new OneSideHashJoiner(
LeftSide, left.output, leftKeys, leftInputIter,
condition.leftSideOnly, postJoinFilter, stateWatermarkPredicates.left,
partitionId,
checkpointIds.left.keyToNumValues,
checkpointIds.left.keyWithIndexToValue,
- skippedNullValueCount, joinStateManagerStoreGenerator,
joinKeyOrdinalForWatermark),
+ skippedNullValueCount, joinStateManagerStoreGenerator,
+ getStateKeyOrdinalForLookup(
Review Comment:
**Nit (P3):** Only the V4 state manager reads this ordinal; state formats 1
to 3, including the default 2, drop it. It is still computed for both sides in
every task of every batch, and for an equality key that is an exact interval
shift of the opposite event time, such as `lt = rt + INTERVAL 10 SECONDS`,
`getStateKeyWatermarkOrdinal` runs the cutoff solver, which logs 'Final
expression to evaluate constraint' and 'Condition ... generated watermark
constraint' at INFO. By the review's reading of the code, a V2 join with 200
shuffle partitions writes about 400 such executor log lines per batch. The
ordinals depend only on plan fields, so they can be computed once, and only for
V4.
**Verification:**
- **Compatibility:** The V4 join tests that check point lookups at a side's
own event-time key and at the key the opposite watermark bounds, and the unit
test of getStateKeyOrdinalForLookup, still pass.
- **Behavior:** A state format 2 join on lk = rk AND lt = rt + INTERVAL 10
SECONDS with both inputs watermarked logs no cutoff-solver lines from executor
tasks.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala:
##########
@@ -630,6 +633,71 @@ class IncrementalExecution(
watermarkPropagator.propagate(currentBatchId, plan,
watermarkForCurrBatch)
}
+ /**
+ * Tell each stream-stream join which input's event time reaches the
stateful operator that
+ * consumes its output watermark, so that the join holds back that
watermark only for that
+ * input's state. The consumers below apply the watermark only to the
event-time column of
+ * their input. The walk down to the join follows that column through
nodes that pass it on
+ * unchanged, or turn it into a window that ends after it. Any other node
or consumer leaves
+ * the join holding back for both inputs.
+ */
+ private def withJoinOutputWatermarkSides(plan: SparkPlan): SparkPlan = {
+ def eventTime(output: Seq[Attribute]): Option[Attribute] =
+ output.find(_.metadata.contains(EventTimeWatermark.delayKey))
+
+ def passThrough(child: SparkPlan, attribute: Attribute): Option[(Long,
JoinSide)] =
+ child.output.find(_.exprId ==
attribute.exprId).flatMap(findJoinSide(child, _))
+
+ def findJoinSide(node: SparkPlan, attribute: Attribute): Option[(Long,
JoinSide)] = {
+ node match {
+ case j: StreamingSymmetricHashJoinExec =>
+ val side = if (eventTime(j.left.output).exists(_.exprId ==
attribute.exprId)) {
+ Some(LeftSide)
+ } else if (eventTime(j.right.output).exists(_.exprId ==
attribute.exprId)) {
+ Some(RightSide)
+ } else {
+ None
+ }
+ j.stateInfo.map(_.operatorId).zip(side)
+ case p: ProjectExec =>
+ p.projectList.find(_.exprId == attribute.exprId).flatMap {
+ case a: Attribute => passThrough(p.child, a)
+ case Alias(a: Attribute, _) => passThrough(p.child, a)
+ case alias: Alias if alias.metadata.contains(TimeWindow.marker)
=>
+ alias.child.references.toSeq match {
+ case Seq(a) => passThrough(p.child, a)
+ case _ => None
+ }
+ case _ => None
+ }
+ case a: BaseAggregateExec => passThrough(a.child, attribute)
+ case _: FilterExec | _: SortExec | _: ShuffleExchangeLike | _:
StateStoreRestoreExec =>
+ passThrough(node.children.head, attribute)
+ case _ => None
Review Comment:
**Blocking (P1):** Any node other than these six, and any stateful consumer
other than the four collected below, ends the trace here, so
`outputWatermarkSides` stays `None` and the join's output watermark includes
the 0 that an unbounded side now contributes. Take the one-directional
impressions and clicks join in `StreamingJoinOutputWatermarkSuite`: when its
`impressionTime` output reaches a window count through a union, as in that
suite's union test, the aggregation's watermark stays at 0 and no window is
ever emitted. By the review's reading of the code, the base branch left the
clicks side out of the minimum, so its output watermark reached 79999 ms and
the windows at 0, 10 and 20 seconds were emitted, which is correct because
impressions are bounded. A sliding window, which is planned as Expand, a
session window, and `flatMapGroupsWithState` or `transformWithState` with
event-time timeouts on `impressionTime` stall the same way, silently and for
the life of the query.
See **Shared repair plan 1** in the review body.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/SymmetricHashJoinStateManager.scala:
##########
@@ -441,11 +451,26 @@ class SymmetricHashJoinStateManagerV4(
private val tsWithKey = new TsWithKeyTypeStore
override def append(key: UnsafeRow, value: UnsafeRow, matched: Boolean):
Unit = {
- val eventTime =
extractEventTimeFnFromKey(key).getOrElse(extractEventTimeFn(value))
+ // A null selected key or indexed value timestamp makes the eviction
predicate SQL-unknown.
+ // Keep such a row in a primary random bucket only, so timestamp eviction
cannot remove it.
+ val timestamp = if (joinKeyOrdinalForWatermark.isDefined) {
+ extractTimestampFromKey(key)
+ } else {
+ extractTimestampFromValue(value)
+ }
+ // When no timestamp is available, we will use random bucketing strategy
to decide where the
+ // new value will be stored. There is a trade-off between the bucket size
and the number of
+ // values in each bucket; we can tune the bucket size with the
configuration if we figure out
+ // the magic number to not work well. On a side that is indexed by
timestamp, evicting a real
+ // row removes every value with the same key and timestamp, which must not
include a row
+ // without a timestamp. Use the lowest timestamps for such rows: a real
event time within
+ // the first 1024 microseconds of the timestamp range (year -290308) would
still share them.
+ val bucket = random.nextInt(bucketCountWithoutTimestamp)
Review Comment:
**Nit (P3):** `bucket` and `bucketTimestamp` are computed for every appended
row, but `timestamp.getOrElse(bucketTimestamp)` below uses them only for a row
without a timestamp. On the base branch the draw happened only in
`extractEventTimeFn`'s branch for a side without an event-time column, which
`getOrElse` evaluated by name. So every row of a side stored at its event time
or a key timestamp now pays a `java.util.Random` draw, an atomic
compare-and-set on the seed, and discards it. Drawing inside the fallback, for
example `timestamp.getOrElse { val bucket =
random.nextInt(bucketCountWithoutTimestamp); ... }`, stores exactly the same
rows.
**Verification:**
- **Regression:** The V4 state manager tests for rows with a NULL or missing
timestamp, including the one that keeps such rows apart from real rows at
timestamps 0 to 1023, still pass.
- **Inspection:** append calls random.nextInt only on the path that stores a
row without a timestamp.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala:
##########
@@ -721,14 +789,46 @@ 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.
+ val requiredWatermarkSemanticsVersion =
+
SQLConf.STREAMING_JOIN_CHECKPOINT_WATERMARK_SEMANTICS_VERSION.defaultValue.get
+ if (isFirstBatch &&
+
conf.getConf(SQLConf.STREAMING_JOIN_CHECKPOINT_WATERMARK_SEMANTICS_VERSION) <
+ requiredWatermarkSemanticsVersion) {
+ def watermarkColumns(input: SparkPlan): String = {
+ val columns = input.output.filter(
+ _.metadata.contains(EventTimeWatermark.delayKey))
+ if (columns.isEmpty) "none" else columns.map(_.name).mkString(", ")
+ }
+ planWithStateOpId.foreach {
+ case j: StreamingSymmetricHashJoinExec
+ if
!StreamingSymmetricHashJoinHelper.isWatermarkCheckpointCompatible(
+ j.left.output, j.right.output, j.leftKeys, j.rightKeys,
j.condition.full) =>
+ // 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 _ =>
+ }
+ }
// Need to check before write to metadata because we need to detect add
operator
// Only check when streaming is restarting and is first batch
if (isFirstBatch && currentBatchId != 0) {
checkOperatorValidWithMetadata(planWithStateOpId, currentBatchId - 1)
}
stateStoreWritersWithMetadata = Some(Seq.empty)
- val planWithSchemas = planWithStateOpId transform
StateSchemaAndOperatorMetadataRule.rule
+ val planWithSchemas = withJoinOutputWatermarkSides(
Review Comment:
**Blocking (P1):** This narrowing also applies to the first batch after
restarting a checkpoint that the previous version wrote.
`simulateWatermarkPropagation` then re-simulates the previous batch with the
narrowed plan, and `WatermarkPropagationRule` passes that late-events watermark
to a downstream V4 join as its scan start, but the old version evicted that
join with the lower, un-narrowed watermark. For example, with V4 state from
Spark 4.3, an upstream `A.id = B.id AND A.t BETWEEN B.t AND B.t + INTERVAL 1
HOUR` join projected to `(A.id, A.t)` feeds a left outer `j.id = C.id AND C.t
BETWEEN j.t AND j.t + INTERVAL 10 MINUTES` join. By the review's reading of the
code, Spark 4.3 evicted `j` rows only up to about W - 1 hour 10 minutes; after
the upgrade the first scan starts after about W - 10 minutes, so `j` rows in
between stay in state forever and their unmatched outer rows are never emitted.
Both joins pass the generation check, and Spark 4.3's join operator, helper and
state
manager are byte-identical to the base branch's, so released V4 checkpoints
reach this.
**Recommended change:** On the first batch of a run whose restored
checkpoint generation is older than the current one, pass no V4 scan start: set
prevBatchLateEventsWm to None, as legacy mode and a query's first batch already
do. Cover it with join checkpoint tests for an older-generation V4 restart.
**Why this works:** That first batch evicts every entry at or below its
cutoff, whatever the old run evicted, so the scan starts of later batches are
again cutoffs this version actually used.
**Scope:** Scan V4 eviction indexes from the start on the first batch after
restarting an older-generation checkpoint.
**Risks:** Each restart of an upgraded V4 checkpoint scans every join's
eviction index from its start once, a one-time pass bounded by the state size.
**Constraints:** Restarts of checkpoints written by this version keep their
scan starts.
**Success:** After a V4 checkpoint written before this change is upgraded,
no state row of a stream-stream join is skipped by eviction, and an outer join
emits every unmatched row once the watermark passes it.
**Verification:**
- **Regression:** Restarting a V4 checkpoint whose generation marker is
older than the current one gives every stream-stream join no scan start on that
batch, so a stored row at or below the cutoff at the re-simulated late-events
watermark is evicted and, for an outer join, emitted.
- **Compatibility:** Restarting a checkpoint written with the current
generation keeps using the late-events watermark as the V4 scan start.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -35,18 +34,130 @@ import org.apache.spark.unsafe.types.CalendarInterval
object StreamingJoinHelper extends PredicateHelper with Logging {
/**
- * Check the provided logical plan to see if its join keys contain a
watermark attribute.
- *
- * Will return false if the plan is not an equijoin.
- * @param plan the logical plan to check
+ * Find the equality key filtered by this input's watermark. Its ordinal can
be used to
+ * evict the opposite input's state, whose equality keys have the same
ordering.
+ * For leftTime = rightTime, a watermark on rightTime bounds leftTime even
when leftTime
+ * has no watermark. It does not bound right-side state without a watermark
on leftTime.
+ * A key computed from the event time by adding a constant interval, such as
+ * leftTime = rightTime + INTERVAL 10 SECONDS, is bounded too; see
[[getStateKeyWatermark]].
*/
- def isWatermarkInJoinKeys(plan: LogicalPlan): Boolean = {
- plan match {
- case ExtractEquiJoinKeys(_, leftKeys, rightKeys, _, _, _, _, _) =>
- (leftKeys ++ rightKeys).exists {
- case a: AttributeReference =>
a.metadata.contains(EventTimeWatermark.delayKey)
- case _ => false
- }
+ def getStateKeyWatermarkOrdinal(
+ keys: Seq[Expression],
+ inputAttributes: Seq[Attribute]): Option[Int] = {
+ getEventTimeKeyOrdinal(keys, inputAttributes).orElse {
+ keys.indices.find(getStateKeyWatermark(keys, inputAttributes, _,
Some(0L)).isDefined)
+ }
+ }
+
+ /** Find the equality key that is this input's event-time column itself. */
+ def getEventTimeKeyOrdinal(
+ keys: Seq[Expression],
+ inputAttributes: Seq[Attribute]): Option[Int] = {
+ // When multiple stateful operators are disabled, late filtering uses the
first event-time
+ // column. Otherwise, execution rejects multiple distinct event-time
columns.
+ inputAttributes.find(_.metadata.contains(delayKey)).flatMap { eventTime =>
+ keys.indexWhere(_.semanticEquals(eventTime)) match {
+ case ordinal if ordinal >= 0 => Some(ordinal)
+ case _ => None
+ }
+ }
+ }
+
+ /**
+ * Get the cutoff for the opposite input's equality key at `ordinal`, given
this input's
+ * watermark. `keys` and `inputAttributes` belong to this input, whose
future rows have an event
+ * time above the watermark. When the key is that event time, the equal key
of any state row
+ * they can still match is above the watermark too. When the key is the
event time shifted by
+ * an interval, solving `stateKey >= rightTime + INTERVAL 10 SECONDS` shifts
the cutoff by that
+ * interval, less 1 ms as for range conditions. Returns None for any other
key.
+ */
+ def getStateKeyWatermark(
+ keys: Seq[Expression],
+ inputAttributes: Seq[Attribute],
+ ordinal: Int,
+ eventWatermark: Option[Long]): Option[Long] = {
+ if (getEventTimeKeyOrdinal(keys, inputAttributes).contains(ordinal)) {
+ eventWatermark
+ } else {
+ eventTimeOfKey(keys(ordinal), inputAttributes).flatMap { eventTime =>
Review Comment:
Thanks, the forward-shift rule looks right for whole days, months and years.
I'd still handle the `timestampadd` case from this thread in this PR, though.
With both inputs watermarked, master evicted `lt = timestampadd(HOUR, 1, rt)`
soundly at `lt <= wm`, because a later right row's key is above the watermark.
Now an inner join keeps every left row, and the outer and semi forms fail
analysis with a message that names requirements the query already meets.
Rewriting the key as `rt + INTERVAL 1 HOUR` works once users know to do it, but
nothing tells them to. `intervalShift` could treat a `TimestampAdd` with a
foldable, non-negative quantity as a forward shift that the solver does not
count, so the key gets the opposite watermark itself as its cutoff, as forward
whole-day shifts now do. That would keep these queries working.
<!-- SPARK_DEV_REVIEW_REPLY
{"feedback_id":"inline:4523762397","thread_id":"inline:4523762397","verdict_sha256":"0042e4c7c6b7cb7775269472085f92208cfa538c4b2cb792572e86e16bb88411"}
-->
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -224,98 +228,221 @@ object StreamingSymmetricHashJoinHelper extends Logging {
WatermarkSupport.findEventTimeColumn(rightAttributes,
allowMultipleEventTimeColumns = useFirstEventTimeColumn)
- val joinKeyOrdinalForWatermark: Option[Int] =
findJoinKeyOrdinalForWatermark(
- leftKeys, rightKeys)
-
def getOneSideStateWatermarkPredicate(
oneSideInputAttributes: Seq[Attribute],
oneSideJoinKeys: Seq[Expression],
- otherSideInputAttributes: Seq[Attribute]):
Option[JoinStateWatermarkPredicate] = {
- val isWatermarkDefinedOnInput =
oneSideInputAttributes.exists(_.metadata.contains(delayKey))
+ otherSideInputAttributes: Seq[Attribute],
+ otherSideJoinKeys: Seq[Expression]):
Option[JoinStateWatermarkPredicate] = {
+ // State is bounded by future input from the opposite side, not by its
own watermark.
+ val joinKeyOrdinalForWatermark =
StreamingJoinHelper.getStateKeyWatermarkOrdinal(
+ otherSideJoinKeys, otherSideInputAttributes)
val isWatermarkDefinedOnJoinKey = joinKeyOrdinalForWatermark.isDefined
if (isWatermarkDefinedOnJoinKey) { // case 1 and 3 in the
StreamingSymmetricHashJoinExec docs
+ val ordinal = joinKeyOrdinalForWatermark.get
val keyExprWithWatermark = BoundReference(
- joinKeyOrdinalForWatermark.get,
- oneSideJoinKeys(joinKeyOrdinalForWatermark.get).dataType,
- oneSideJoinKeys(joinKeyOrdinalForWatermark.get).nullable)
- val expr = watermarkExpression(Some(keyExprWithWatermark),
eventTimeWatermarkForEviction)
- expr.map { e =>
- // V4 can skip keys at or below the previous watermark only if
late-input filtering
- // rejects new rows in that range on this same key. A watermark on
the other input's
- // equality key can drive eviction even when this input has no
watermark, or has one
- // on a different column. New rows can then pass late-input
filtering with keys
- // already eligible for eviction. V4 must scan from the beginning to
find them;
- // otherwise, outer joins can fail to emit null rows for these
unmatched inputs.
- val prevStateKeyWatermark =
- if (oneSideInputAttributes.find(_.metadata.contains(delayKey))
-
.exists(oneSideJoinKeys(joinKeyOrdinalForWatermark.get).semanticEquals)) {
- eventTimeWatermarkForLateEvents
- } else {
- None
- }
- // watermarkExpression only provides the expression when
eventTimeWatermarkForEviction
- // is defined.
- JoinStateKeyWatermarkPredicate(
- e,
- 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 =>
- StreamingJoinHelper.getStateValueWatermark(
- attributesToFindStateWatermarkFor =
AttributeSet(oneSideInputAttributes),
- attributesWithEventWatermark =
AttributeSet(otherSideInputAttributes),
- condition,
- eventTimeWatermarkForLateEvents).filter(_ <= lateWatermark)
+ ordinal, oneSideJoinKeys(ordinal).dataType,
oneSideJoinKeys(ordinal).nullable)
+ // The opposite watermark bounds this key, shifted by an exact
constant in the opposite
+ // key. See StreamingJoinHelper.getStateKeyWatermark for the shifts it
accepts.
+ def keyWatermark(watermark: Option[Long]): Option[Long] =
+ StreamingJoinHelper.getStateKeyWatermark(
+ otherSideJoinKeys, otherSideInputAttributes, ordinal, watermark)
+ keyWatermark(eventTimeWatermarkForEviction).flatMap { stateWatermark =>
+ watermarkExpression(Some(keyExprWithWatermark),
Some(stateWatermark)).map { e =>
+ // V4 can skip keys at or below the previous watermark only if
late-input filtering
+ // rejects new rows in that range on this same key. A watermark on
the other input's
+ // equality key can drive eviction even when this input has no
watermark, or has one
+ // on a different column. New rows can then pass late-input
filtering with keys
+ // already eligible for eviction. V4 must scan from the beginning
to find them;
+ // otherwise, outer joins can fail to emit null rows for these
unmatched inputs.
+ val prevStateKeyWatermark =
+ if (oneSideInputAttributes.find(_.metadata.contains(delayKey))
+ .exists(oneSideJoinKeys(ordinal).semanticEquals)) {
+ // Late filtering drops new keys at or below the late-input
watermark, and the
+ // previous batch evicted keys up to its cutoff, which is the
cutoff at that
+ // watermark. A shifted cutoff can lie on either side of the
watermark, so the
+ // scan starts after the lower of the two.
+ eventTimeWatermarkForLateEvents.flatMap { lateWatermark =>
+ keyWatermark(Some(lateWatermark)).map(math.min(_,
lateWatermark))
+ }
+ } else {
+ None
+ }
+ JoinStateKeyWatermarkPredicate(e, stateWatermark,
prevStateKeyWatermark)
+ }
}
- val inputAttributeWithWatermark =
oneSideInputAttributes.find(_.metadata.contains(delayKey))
- val expr = watermarkExpression(inputAttributeWithWatermark,
stateValueWatermark)
- expr.map { e =>
- // watermarkExpression only provides the expression when
eventTimeWatermarkForEviction
- // is defined
- JoinStateValueWatermarkPredicate(e, stateValueWatermark.get,
prevStateValueWatermark)
+ } else { // case 2 in the StreamingSymmetricHashJoinExec docs
+ // Future matches are limited by the opposite watermark. This input
needs no watermark;
+ // its event-time column may also have been pruned from the physical
join.
+ val otherSideEventTime =
otherSideInputAttributes.find(_.metadata.contains(delayKey))
+ getStateValueWatermarkForInput(oneSideInputAttributes,
otherSideInputAttributes,
+ condition, eventTimeWatermarkForEviction).flatMap { case (attribute,
watermark) =>
+ // Late filtering only constrains the input's event-time column. A
different indexed
+ // column can admit values below the previous cutoff and must be
scanned from the start.
+ val prevStateValueWatermark = eventTimeWatermarkForLateEvents.filter
{ _ =>
+ oneSideInputAttributes.find(_.metadata.contains(delayKey))
+ .exists(_.semanticEquals(attribute))
+ }.flatMap { lateWatermark =>
+ // Also scan from the start if the derived cutoff exceeds the
late-input watermark.
+
StreamingJoinHelper.getStateValueWatermark(AttributeSet(Seq(attribute)),
+ AttributeSet(otherSideEventTime.toSeq), condition,
Some(lateWatermark))
+ .filter(_ <= lateWatermark)
+ }
+ watermarkExpression(Some(attribute), Some(watermark)).map { e =>
+ JoinStateValueWatermarkPredicate(e, watermark,
prevStateValueWatermark)
+ }
}
- } else {
- None
}
}
val leftStateWatermarkPredicate =
- getOneSideStateWatermarkPredicate(leftAttributes, leftKeys,
rightAttributes)
+ getOneSideStateWatermarkPredicate(leftAttributes, leftKeys,
rightAttributes, rightKeys)
val rightStateWatermarkPredicate =
- getOneSideStateWatermarkPredicate(rightAttributes, rightKeys,
leftAttributes)
+ getOneSideStateWatermarkPredicate(rightAttributes, rightKeys,
leftAttributes, leftKeys)
JoinStateWatermarkPredicates(leftStateWatermarkPredicate,
rightStateWatermarkPredicate)
}
- private[join] def findJoinKeyOrdinalForWatermark(
+ /** Keep each cutoff attached to the column constrained by the join
condition. */
+ private def getStateValueWatermarkForInput(
+ inputAttributes: Seq[Attribute],
+ otherInputAttributes: Seq[Attribute],
+ condition: Option[Expression],
+ eventWatermark: Option[Long]): Option[(Attribute, Long)] = {
+ val eventTime = inputAttributes.find(_.metadata.contains(delayKey))
+ // Only the first marked column is checked for late input in compatibility
mode.
+ val otherEventTime =
otherInputAttributes.find(_.metadata.contains(delayKey))
+ // First try the watermarked column. If it has no inferable bound, try the
other timestamp
+ // columns in input schema order and use the first with a bound. This
makes the indexed column
+ // deterministic for a fixed input schema and join condition.
+ val candidates = eventTime.toSeq ++ inputAttributes.filter { attribute =>
+ attribute.dataType == TimestampType &&
!eventTime.exists(_.semanticEquals(attribute))
+ }
+ candidates.iterator.flatMap { attribute =>
+ StreamingJoinHelper.getStateValueWatermark(AttributeSet(Seq(attribute)),
+ AttributeSet(otherEventTime.toSeq), condition, eventWatermark,
+ exactForUnwatermarkedColumns = true).map(attribute -> _)
Review Comment:
**Blocking (P1):** With `exactForUnwatermarkedColumns = true` here, whether
a column without its own watermark gets a cutoff depends on the session time
zone, which the offset log does not pin, and that cutoff now decides where V4
stores and looks up the side's rows. Take an inner join on `lk = rk AND
leftTime = refTime AND rightTime <= expiry + INTERVAL 1 DAY`, with watermarks
on `leftTime` and `rightTime`, so `refTime` is not bounded. Under UTC the left
side is evicted on `expiry`, `getStateKeyOrdinalForLookup` gives its manager no
key ordinal, and a left row with `leftTime = T` and `expiry = T + 10 days` is
stored at `(key, T + 10 days)`. After a restart under America/Los_Angeles the
whole-day bound is inexact, the side has no predicate, and the manager gets the
`leftTime` ordinal, so a right row with `refTime = T` reads only `(key, T)` and
misses that row. By the review's reading of the code, the base branch stored
and looked up the row at `(key, T)` and returned the match, wh
ile a right outer join now emits that right row padded with nulls. The reverse
restart evicts rows stored at `leftTime` by the `expiry` cutoff, and one-sided
joins leave rows stored before a restart unindexed. The doc of
`getStateKeyWatermarkOrdinal` says the V4 layout does not depend on the session
time zone.
This extends existing discussions
[1](https://github.com/apache/spark/pull/60282#issuecomment-6775645693),
[2](https://github.com/apache/spark/pull/60282#discussion_r4523762419),
[3](https://github.com/apache/spark/pull/60282#discussion_r4523762444).
**Recommended change:** Choose the column a side stores, indexes and looks
up rows by from the shape of the join condition, before the exactness check:
the first candidate column, the event time first and then other TIMESTAMP
columns in schema order, for which the solver finds a bound when the exactness
rule is ignored. Then apply the exactness rule only to decide whether that
column's cutoff becomes an eviction predicate. Pass the chosen column to the V4
state manager and to getStateKeyOrdinalForLookup even when no cutoff applies.
Correct the doc of getStateKeyWatermarkOrdinal so it no longer claims on its
own that the V4 layout is zone-independent. Add join tests that restart a
value-evicted V4 join between UTC and America/Los_Angeles in both directions.
The column choice of 7bd01bd59a6 did not depend on the zone; 4000ae8f0c6 added
the exactness rule to that choice so that a column without its own watermark
gets no cutoff from whole days or a truncating cast. Start from 7bd01bd5
9a6's choice and keep 4000ae8f0c6's rule for the cutoff.
**Why this works:** The stored column becomes a function of the analyzed
condition's shape and the input schema, which every restart of a checkpoint
reproduces, so rows written in one run are indexed and looked up by the same
column in the next. The session time zone then decides only whether eviction
runs, and a side that is not evicted keeps rows indexed by the chosen column,
so a later run that can evict scans them correctly.
**Scope:** Make the V4 state layout of a range-evicted side independent of
the session time zone, keeping the exactness rule for eviction.
**Compatibility:** The exactness rule's effect on eviction and on admission:
inexact bounds still give an unwatermarked column no cutoff, and the outer
forms that rely on them still fail analysis.
**Risks:** A side bounded by two TIMESTAMP columns, where the first is
bounded only through whole days, no longer falls back to the second column's
exact cutoff in a zone that is not a fixed offset. It keeps its state instead,
which is safe but unbounded. A side whose own event time is an equality key and
whose bound is on another column would store rows at that column and probe them
with prefix scans in every zone, as it already does in a fixed-offset zone, so
in a zone that is not fixed-offset its lookups read every timestamp of the key
instead of one.
**Constraints:** A column without its own watermark must still get no cutoff
from whole days in a zone that is not a fixed offset or from a truncating cast,
and the admission check must keep agreeing with eviction. Joins whose layout
comes from their own event time or from a key ordinal today must keep that
layout.
**Exclusions:**
- Counting whole days conservatively in the cutoff solver, deferred to
SPARK-61381.
**Success:** A V4 join restarted from the same checkpoint under a different
session time zone stores, indexes and looks up rows by the same column as
before the restart. Whether a side is evicted still follows the exactness rule.
**Verification:**
- **Regression:** A V4 inner join with a whole-day bound on an unwatermarked
expiry column, buffered under America/Los_Angeles and restarted under UTC,
keeps every left row that can still match and returns every match, and the
reverse restart also returns every match.
- **Regression:** A V4 join whose left event time is an equality key and
whose only left bound is a whole-day bound on another column returns every
match after a restart in either direction between UTC and America/Los_Angeles.
- **Behavior:** In a zone that is not a fixed offset, an unwatermarked
column bounded only through whole days still gets no eviction cutoff, and the
outer form still fails analysis.
- **Compatibility:** Joins bounded on their own event time, by exact
intervals, or by key eviction keep the same V4 index column, lookup ordinal and
eviction cutoffs.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -224,98 +228,221 @@ object StreamingSymmetricHashJoinHelper extends Logging {
WatermarkSupport.findEventTimeColumn(rightAttributes,
allowMultipleEventTimeColumns = useFirstEventTimeColumn)
- val joinKeyOrdinalForWatermark: Option[Int] =
findJoinKeyOrdinalForWatermark(
- leftKeys, rightKeys)
-
def getOneSideStateWatermarkPredicate(
oneSideInputAttributes: Seq[Attribute],
oneSideJoinKeys: Seq[Expression],
- otherSideInputAttributes: Seq[Attribute]):
Option[JoinStateWatermarkPredicate] = {
- val isWatermarkDefinedOnInput =
oneSideInputAttributes.exists(_.metadata.contains(delayKey))
+ otherSideInputAttributes: Seq[Attribute],
+ otherSideJoinKeys: Seq[Expression]):
Option[JoinStateWatermarkPredicate] = {
+ // State is bounded by future input from the opposite side, not by its
own watermark.
+ val joinKeyOrdinalForWatermark =
StreamingJoinHelper.getStateKeyWatermarkOrdinal(
+ otherSideJoinKeys, otherSideInputAttributes)
val isWatermarkDefinedOnJoinKey = joinKeyOrdinalForWatermark.isDefined
if (isWatermarkDefinedOnJoinKey) { // case 1 and 3 in the
StreamingSymmetricHashJoinExec docs
+ val ordinal = joinKeyOrdinalForWatermark.get
val keyExprWithWatermark = BoundReference(
- joinKeyOrdinalForWatermark.get,
- oneSideJoinKeys(joinKeyOrdinalForWatermark.get).dataType,
- oneSideJoinKeys(joinKeyOrdinalForWatermark.get).nullable)
- val expr = watermarkExpression(Some(keyExprWithWatermark),
eventTimeWatermarkForEviction)
- expr.map { e =>
- // V4 can skip keys at or below the previous watermark only if
late-input filtering
- // rejects new rows in that range on this same key. A watermark on
the other input's
- // equality key can drive eviction even when this input has no
watermark, or has one
- // on a different column. New rows can then pass late-input
filtering with keys
- // already eligible for eviction. V4 must scan from the beginning to
find them;
- // otherwise, outer joins can fail to emit null rows for these
unmatched inputs.
- val prevStateKeyWatermark =
- if (oneSideInputAttributes.find(_.metadata.contains(delayKey))
-
.exists(oneSideJoinKeys(joinKeyOrdinalForWatermark.get).semanticEquals)) {
- eventTimeWatermarkForLateEvents
- } else {
- None
- }
- // watermarkExpression only provides the expression when
eventTimeWatermarkForEviction
- // is defined.
- JoinStateKeyWatermarkPredicate(
- e,
- 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 =>
- StreamingJoinHelper.getStateValueWatermark(
- attributesToFindStateWatermarkFor =
AttributeSet(oneSideInputAttributes),
- attributesWithEventWatermark =
AttributeSet(otherSideInputAttributes),
- condition,
- eventTimeWatermarkForLateEvents).filter(_ <= lateWatermark)
+ ordinal, oneSideJoinKeys(ordinal).dataType,
oneSideJoinKeys(ordinal).nullable)
+ // The opposite watermark bounds this key, shifted by an exact
constant in the opposite
+ // key. See StreamingJoinHelper.getStateKeyWatermark for the shifts it
accepts.
+ def keyWatermark(watermark: Option[Long]): Option[Long] =
+ StreamingJoinHelper.getStateKeyWatermark(
+ otherSideJoinKeys, otherSideInputAttributes, ordinal, watermark)
+ keyWatermark(eventTimeWatermarkForEviction).flatMap { stateWatermark =>
+ watermarkExpression(Some(keyExprWithWatermark),
Some(stateWatermark)).map { e =>
+ // V4 can skip keys at or below the previous watermark only if
late-input filtering
+ // rejects new rows in that range on this same key. A watermark on
the other input's
+ // equality key can drive eviction even when this input has no
watermark, or has one
+ // on a different column. New rows can then pass late-input
filtering with keys
+ // already eligible for eviction. V4 must scan from the beginning
to find them;
+ // otherwise, outer joins can fail to emit null rows for these
unmatched inputs.
+ val prevStateKeyWatermark =
+ if (oneSideInputAttributes.find(_.metadata.contains(delayKey))
+ .exists(oneSideJoinKeys(ordinal).semanticEquals)) {
+ // Late filtering drops new keys at or below the late-input
watermark, and the
+ // previous batch evicted keys up to its cutoff, which is the
cutoff at that
+ // watermark. A shifted cutoff can lie on either side of the
watermark, so the
+ // scan starts after the lower of the two.
+ eventTimeWatermarkForLateEvents.flatMap { lateWatermark =>
+ keyWatermark(Some(lateWatermark)).map(math.min(_,
lateWatermark))
+ }
+ } else {
+ None
+ }
+ JoinStateKeyWatermarkPredicate(e, stateWatermark,
prevStateKeyWatermark)
+ }
}
- val inputAttributeWithWatermark =
oneSideInputAttributes.find(_.metadata.contains(delayKey))
- val expr = watermarkExpression(inputAttributeWithWatermark,
stateValueWatermark)
- expr.map { e =>
- // watermarkExpression only provides the expression when
eventTimeWatermarkForEviction
- // is defined
- JoinStateValueWatermarkPredicate(e, stateValueWatermark.get,
prevStateValueWatermark)
+ } else { // case 2 in the StreamingSymmetricHashJoinExec docs
+ // Future matches are limited by the opposite watermark. This input
needs no watermark;
+ // its event-time column may also have been pruned from the physical
join.
+ val otherSideEventTime =
otherSideInputAttributes.find(_.metadata.contains(delayKey))
+ getStateValueWatermarkForInput(oneSideInputAttributes,
otherSideInputAttributes,
+ condition, eventTimeWatermarkForEviction).flatMap { case (attribute,
watermark) =>
+ // Late filtering only constrains the input's event-time column. A
different indexed
+ // column can admit values below the previous cutoff and must be
scanned from the start.
+ val prevStateValueWatermark = eventTimeWatermarkForLateEvents.filter
{ _ =>
+ oneSideInputAttributes.find(_.metadata.contains(delayKey))
+ .exists(_.semanticEquals(attribute))
+ }.flatMap { lateWatermark =>
+ // Also scan from the start if the derived cutoff exceeds the
late-input watermark.
+
StreamingJoinHelper.getStateValueWatermark(AttributeSet(Seq(attribute)),
+ AttributeSet(otherSideEventTime.toSeq), condition,
Some(lateWatermark))
+ .filter(_ <= lateWatermark)
+ }
+ watermarkExpression(Some(attribute), Some(watermark)).map { e =>
+ JoinStateValueWatermarkPredicate(e, watermark,
prevStateValueWatermark)
+ }
}
- } else {
- None
}
}
val leftStateWatermarkPredicate =
- getOneSideStateWatermarkPredicate(leftAttributes, leftKeys,
rightAttributes)
+ getOneSideStateWatermarkPredicate(leftAttributes, leftKeys,
rightAttributes, rightKeys)
val rightStateWatermarkPredicate =
- getOneSideStateWatermarkPredicate(rightAttributes, rightKeys,
leftAttributes)
+ getOneSideStateWatermarkPredicate(rightAttributes, rightKeys,
leftAttributes, leftKeys)
JoinStateWatermarkPredicates(leftStateWatermarkPredicate,
rightStateWatermarkPredicate)
}
- private[join] def findJoinKeyOrdinalForWatermark(
+ /** Keep each cutoff attached to the column constrained by the join
condition. */
+ private def getStateValueWatermarkForInput(
+ inputAttributes: Seq[Attribute],
+ otherInputAttributes: Seq[Attribute],
+ condition: Option[Expression],
+ eventWatermark: Option[Long]): Option[(Attribute, Long)] = {
+ val eventTime = inputAttributes.find(_.metadata.contains(delayKey))
+ // Only the first marked column is checked for late input in compatibility
mode.
+ val otherEventTime =
otherInputAttributes.find(_.metadata.contains(delayKey))
+ // First try the watermarked column. If it has no inferable bound, try the
other timestamp
+ // columns in input schema order and use the first with a bound. This
makes the indexed column
+ // deterministic for a fixed input schema and join condition.
+ val candidates = eventTime.toSeq ++ inputAttributes.filter { attribute =>
+ attribute.dataType == TimestampType &&
!eventTime.exists(_.semanticEquals(attribute))
+ }
+ candidates.iterator.flatMap { attribute =>
+ StreamingJoinHelper.getStateValueWatermark(AttributeSet(Seq(attribute)),
+ AttributeSet(otherEventTime.toSeq), condition, eventWatermark,
+ exactForUnwatermarkedColumns = true).map(attribute -> _)
+ }.take(1).toSeq.headOption
+ }
+
+ /**
+ * Get the equality-key ordinal at which a V4 state manager stores and looks
up a side's rows.
+ * A side evicted by key uses the key that the opposite input's watermark
bounds. Any other side
+ * stores each row at its own event time, unless it is evicted on another
column. When that
+ * event time is an equality key, its ordinal gives the same stored
timestamps and lets a lookup
+ * read one timestamp instead of scanning every timestamp of the key.
+ */
+ def getStateKeyOrdinalForLookup(
+ oneSideAttributes: Seq[Attribute],
+ oneSideKeys: Seq[Expression],
+ otherSideAttributes: Seq[Attribute],
+ otherSideKeys: Seq[Expression],
+ predicate: Option[JoinStateWatermarkPredicate]): Option[Int] = {
+ def storesRowsAtKey(ordinal: Int): Boolean = predicate match {
+ case Some(p: JoinStateValueWatermarkPredicate) =>
+ p.expr.references.forall(_.semanticEquals(oneSideKeys(ordinal)))
+ case _ => true
+ }
+ StreamingJoinHelper.getStateKeyWatermarkOrdinal(otherSideKeys,
otherSideAttributes).orElse(
+ StreamingJoinHelper.getEventTimeKeyOrdinal(oneSideKeys,
oneSideAttributes)
+ .filter(storesRowsAtKey))
+ }
+
+ /**
+ * Conservatively prove that older state can use the current watermark
semantics. Without
+ * watermarks there is no affected state. Otherwise each side must have
exactly one event-time
+ * column, and either its own event time must be the sole watermarked
equality key at the same
+ * ordinal, or the join must be a two-sided time-interval join on the event
times (see
+ * [[isOwnEventTimeIntervalJoin]]). This excludes other range bounds and
retained event times
+ * with no eviction bound. It also excludes a key computed from the event
time by a constant,
+ * which older versions evicted at the unshifted watermark. A NULL selected
key does not matter:
+ * old V4 state indexed it at timestamp 0 under its own key, and evicting
that row, which can
+ * never match, emits its correct outer row.
+ */
+ private[sql] def isWatermarkCheckpointCompatible(
+ leftAttributes: Seq[Attribute],
+ rightAttributes: Seq[Attribute],
leftKeys: Seq[Expression],
- rightKeys: Seq[Expression]): Option[Int] = {
- // Join keys of both sides generate rows of the same fields, that is, same
sequence of data
- // types. If one side (say left side) has a column (say timestamp) that
has a watermark on it,
- // then it will never consider joining keys that are < state key watermark
(i.e. event time
- // watermark). On the other side (i.e. right side), even if there is no
watermark defined,
- // there has to be an equivalent column (i.e., timestamp). And any right
side data that has the
- // timestamp < watermark will not match will not match with left side
data, as the left side get
- // filtered with the explicitly defined watermark. So, the watermark in
timestamp column in
- // left side keys effectively causes the timestamp on the right side to
have a watermark.
- // We will use the ordinal of the left timestamp in the left keys to find
the corresponding
- // right timestamp in the right keys.
- leftKeys.zipWithIndex.collectFirst {
- case (ne: NamedExpression, index) if ne.metadata.contains(delayKey) =>
index
- } orElse {
- rightKeys.zipWithIndex.collectFirst {
- case (ne: NamedExpression, index) if ne.metadata.contains(delayKey) =>
index
+ rightKeys: Seq[Expression],
+ condition: Option[Expression]): Boolean = {
+ val leftEventTime = leftAttributes.filter(_.metadata.contains(delayKey))
+ val rightEventTime = rightAttributes.filter(_.metadata.contains(delayKey))
+
+ def watermarkKeyOrdinals(keys: Seq[Expression]): Seq[Int] = {
+ keys.zipWithIndex.collect {
+ case (key: NamedExpression, index) if key.metadata.contains(delayKey)
=> index
}
}
+
+ val leftOrdinals = watermarkKeyOrdinals(leftKeys)
+ val rightOrdinals = watermarkKeyOrdinals(rightKeys)
+ if (leftEventTime.isEmpty && rightEventTime.isEmpty) {
+ leftOrdinals.isEmpty && rightOrdinals.isEmpty
+ } else if (leftEventTime.size == 1 && rightEventTime.size == 1) {
+ val leftOrdinal = StreamingJoinHelper.getEventTimeKeyOrdinal(leftKeys,
leftAttributes)
+ val rightOrdinal = StreamingJoinHelper.getEventTimeKeyOrdinal(rightKeys,
rightAttributes)
+ val alignedOwnEventTimeKeys = leftOrdinal.isDefined && leftOrdinal ==
rightOrdinal &&
+ leftOrdinals == leftOrdinal.toSeq && rightOrdinals ==
rightOrdinal.toSeq
+ alignedOwnEventTimeKeys || isOwnEventTimeIntervalJoin(leftAttributes,
rightAttributes,
+ leftKeys, rightKeys, condition, leftEventTime.head,
rightEventTime.head)
+ } else {
+ false
+ }
+ }
+
+ /**
+ * Whether every ordering conjunct compares the two inputs' event times,
each shifted only by
+ * exact constant intervals, and both event times get a range bound. Older
versions solved
+ * every column of an input but then found bounds only in the same
conjuncts, so they derived
+ * the same value predicates, scan starts, V4 index columns and output
watermark. Old V4 stored
+ * a null event time at timestamp 0 under the row's own key; both versions
scan that entry the
+ * same way. No equality key may use an event time: older versions evicted
such keys at the
+ * unshifted watermark.
+ */
+ private def isOwnEventTimeIntervalJoin(
+ leftAttributes: Seq[Attribute],
+ rightAttributes: Seq[Attribute],
+ leftKeys: Seq[Expression],
+ rightKeys: Seq[Expression],
+ condition: Option[Expression],
+ leftEventTime: Attribute,
+ rightEventTime: Attribute): Boolean = {
+ def conjuncts(e: Expression): Seq[Expression] = e match {
+ case And(left, right) => conjuncts(left) ++ conjuncts(right)
+ case other => Seq(other)
+ }
+ def eventTimeOf(e: Expression): Option[Attribute] =
+ Seq(leftEventTime,
rightEventTime).find(StreamingJoinHelper.isExactIntervalShift(e, _))
Review Comment:
**Blocking (P1):** `isExactIntervalShift` counts any interval of a day or
more as inexact in every time zone, so this rejects a released checkpoint of
`leftKey = rightKey AND rightTime >= leftTime AND rightTime <= leftTime +
INTERVAL 1 DAY` with watermarks on both inputs, even under UTC; the
compatibility suite now asserts that. Both versions keep the solver's 24-hour
cutoff for a column with its own watermark (`leftTime <= wm - 1 day - 1 ms`,
`rightTime <= wm - 1 ms`), so the saved state, scan starts, V4 index columns
and probe windows are read the same way. The UTC rejection came in with
c4bdbf09fdb as a side effect of making whole-day key shifts zone-independent.
Key-only joins with watermarks are also still rejected: neither version evicts
their state, and the changed output watermark matters only when a stateful
operator follows the join, which `IncrementalExecution` can see in the plan it
already checks. Users upgrading such a query must discard state that is still
valid and
replay input, and a key-only join's state can be rebuilt only from its full
input history.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60282#discussion_r4523762425).
**Recommended change:** In isOwnEventTimeIntervalJoin, accept comparisons
whose sides are the event times plus or minus constant day-time intervals of
any length, not only shifts shorter than a day; both versions count those days
with the same 24-hour solver for watermarked event times. Also accept
watermarked joins from which neither version derives a key or value predicate,
such as key-only joins and joins on inline computed keys over an event time,
when no stateful operator in the plan consumes the join's output watermark.
IncrementalExecution can pass that fact from the plan it already checks. Update
the compatibility tests that now expect rejection of these shapes, and the
migration guide's list of rejected checkpoints. 4fd804c5931 accepted two-sided
whole-day intervals in a fixed-offset zone; c4bdbf09fdb removed that when it
made whole days inexact in every zone, giving a zone-independent V4 key layout
as the reason, which concerns equality keys rather than interval cutoffs
on watermarked event times. Start from 4fd804c5931's acceptance and extend it
to every zone.
**Why this works:** Acceptance then follows the rule the check's doc states:
old state is reused exactly when the new code reads it, and any output
watermark an operator consumes, the same way the old code did.
**Scope:** Accept older checkpoints of joins whose saved state and consumed
output watermark both versions treat the same way.
**Risks:** A later change to how whole-day intervals or key-only joins are
derived, such as conservative day counting, must bump the generation and
revisit these acceptances.
**Constraints:** One-sided, expiry-bounded, shifted-key, numeric-expiry and
constant-conjunct shapes must stay rejected before any state is opened. A
key-only join followed by a stateful operator must stay rejected.
**Exclusions:**
- Accepting shapes whose derivations later stack PRs change, such as
constant-only, numeric or negative-term bounds.
**Success:** Older checkpoints of two-sided whole-day interval joins with
both inputs watermarked restart in every session time zone. Older checkpoints
of key-only joins with watermarks and no stateful operator after them restart,
and those followed by a stateful operator are still rejected.
**Verification:**
- **Regression:** An older checkpoint of leftKey = rightKey AND rightTime >=
leftTime AND rightTime <= leftTime + INTERVAL 1 DAY with both inputs
watermarked resumes under UTC and under America/Los_Angeles with the base
branch's results, in state formats 1 to 4.
- **Regression:** An older checkpoint of a key-only inner join with
watermarks on both inputs and no later stateful operator resumes and still
matches rows buffered before the restart.
- **Compatibility:** A key-only join followed by an aggregation, and
one-sided, expiry-bounded, shifted-key and numeric-expiry joins, are still
rejected on the first batch with state and commits unchanged.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -224,98 +228,150 @@ object StreamingSymmetricHashJoinHelper extends Logging {
WatermarkSupport.findEventTimeColumn(rightAttributes,
allowMultipleEventTimeColumns = useFirstEventTimeColumn)
- val joinKeyOrdinalForWatermark: Option[Int] =
findJoinKeyOrdinalForWatermark(
- leftKeys, rightKeys)
-
def getOneSideStateWatermarkPredicate(
oneSideInputAttributes: Seq[Attribute],
oneSideJoinKeys: Seq[Expression],
- otherSideInputAttributes: Seq[Attribute]):
Option[JoinStateWatermarkPredicate] = {
- val isWatermarkDefinedOnInput =
oneSideInputAttributes.exists(_.metadata.contains(delayKey))
+ otherSideInputAttributes: Seq[Attribute],
+ otherSideJoinKeys: Seq[Expression]):
Option[JoinStateWatermarkPredicate] = {
+ // State is bounded by future input from the opposite side, not by its
own watermark.
+ val joinKeyOrdinalForWatermark =
StreamingJoinHelper.getStateKeyWatermarkOrdinal(
+ otherSideJoinKeys, otherSideInputAttributes)
val isWatermarkDefinedOnJoinKey = joinKeyOrdinalForWatermark.isDefined
if (isWatermarkDefinedOnJoinKey) { // case 1 and 3 in the
StreamingSymmetricHashJoinExec docs
+ val ordinal = joinKeyOrdinalForWatermark.get
val keyExprWithWatermark = BoundReference(
- joinKeyOrdinalForWatermark.get,
- oneSideJoinKeys(joinKeyOrdinalForWatermark.get).dataType,
- oneSideJoinKeys(joinKeyOrdinalForWatermark.get).nullable)
- val expr = watermarkExpression(Some(keyExprWithWatermark),
eventTimeWatermarkForEviction)
- expr.map { e =>
- // V4 can skip keys at or below the previous watermark only if
late-input filtering
- // rejects new rows in that range on this same key. A watermark on
the other input's
- // equality key can drive eviction even when this input has no
watermark, or has one
- // on a different column. New rows can then pass late-input
filtering with keys
- // already eligible for eviction. V4 must scan from the beginning to
find them;
- // otherwise, outer joins can fail to emit null rows for these
unmatched inputs.
- val prevStateKeyWatermark =
- if (oneSideInputAttributes.find(_.metadata.contains(delayKey))
-
.exists(oneSideJoinKeys(joinKeyOrdinalForWatermark.get).semanticEquals)) {
- eventTimeWatermarkForLateEvents
- } else {
- None
- }
- // watermarkExpression only provides the expression when
eventTimeWatermarkForEviction
- // is defined.
- JoinStateKeyWatermarkPredicate(
- e,
- 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 =>
- StreamingJoinHelper.getStateValueWatermark(
- attributesToFindStateWatermarkFor =
AttributeSet(oneSideInputAttributes),
- attributesWithEventWatermark =
AttributeSet(otherSideInputAttributes),
- condition,
- eventTimeWatermarkForLateEvents).filter(_ <= lateWatermark)
+ ordinal, oneSideJoinKeys(ordinal).dataType,
oneSideJoinKeys(ordinal).nullable)
+ // The opposite watermark bounds this key, shifted by any constant in
the opposite key.
+ def keyWatermark(watermark: Option[Long]): Option[Long] =
+ StreamingJoinHelper.getStateKeyWatermark(
+ otherSideJoinKeys, otherSideInputAttributes, ordinal, watermark)
+ keyWatermark(eventTimeWatermarkForEviction).flatMap { stateWatermark =>
+ watermarkExpression(Some(keyExprWithWatermark),
Some(stateWatermark)).map { e =>
+ // V4 can skip keys at or below the previous watermark only if
late-input filtering
+ // rejects new rows in that range on this same key. A watermark on
the other input's
+ // equality key can drive eviction even when this input has no
watermark, or has one
+ // on a different column. New rows can then pass late-input
filtering with keys
+ // already eligible for eviction. V4 must scan from the beginning
to find them;
+ // otherwise, outer joins can fail to emit null rows for these
unmatched inputs.
+ val prevStateKeyWatermark =
+ if (oneSideInputAttributes.find(_.metadata.contains(delayKey))
+ .exists(oneSideJoinKeys(ordinal).semanticEquals)) {
+ // A cutoff shifted above the late-input watermark also needs
a full scan.
+ eventTimeWatermarkForLateEvents.flatMap { lateWatermark =>
+ keyWatermark(Some(lateWatermark)).filter(_ <= lateWatermark)
+ }
+ } else {
+ None
+ }
+ JoinStateKeyWatermarkPredicate(e, stateWatermark,
prevStateKeyWatermark)
+ }
}
- val inputAttributeWithWatermark =
oneSideInputAttributes.find(_.metadata.contains(delayKey))
- val expr = watermarkExpression(inputAttributeWithWatermark,
stateValueWatermark)
- expr.map { e =>
- // watermarkExpression only provides the expression when
eventTimeWatermarkForEviction
- // is defined
- JoinStateValueWatermarkPredicate(e, stateValueWatermark.get,
prevStateValueWatermark)
+ } else { // case 2 in the StreamingSymmetricHashJoinExec docs
+ // Future matches are limited by the opposite watermark. This input
needs no watermark;
+ // its event-time column may also have been pruned from the physical
join.
+ val otherSideEventTime =
otherSideInputAttributes.find(_.metadata.contains(delayKey))
+ getStateValueWatermarkForInput(oneSideInputAttributes,
otherSideInputAttributes,
+ condition, eventTimeWatermarkForEviction).flatMap { case (attribute,
watermark) =>
+ // Late filtering only constrains the input's event-time column. A
different indexed
+ // column can admit values below the previous cutoff and must be
scanned from the start.
+ val prevStateValueWatermark = eventTimeWatermarkForLateEvents.filter
{ _ =>
+ oneSideInputAttributes.find(_.metadata.contains(delayKey))
+ .exists(_.semanticEquals(attribute))
+ }.flatMap { lateWatermark =>
+ // Also scan from the start if the derived cutoff exceeds the
late-input watermark.
+
StreamingJoinHelper.getStateValueWatermark(AttributeSet(Seq(attribute)),
+ AttributeSet(otherSideEventTime.toSeq), condition,
Some(lateWatermark))
+ .filter(_ <= lateWatermark)
+ }
+ watermarkExpression(Some(attribute), Some(watermark)).map { e =>
+ JoinStateValueWatermarkPredicate(e, watermark,
prevStateValueWatermark)
+ }
}
- } else {
- None
}
}
val leftStateWatermarkPredicate =
- getOneSideStateWatermarkPredicate(leftAttributes, leftKeys,
rightAttributes)
+ getOneSideStateWatermarkPredicate(leftAttributes, leftKeys,
rightAttributes, rightKeys)
val rightStateWatermarkPredicate =
- getOneSideStateWatermarkPredicate(rightAttributes, rightKeys,
leftAttributes)
+ getOneSideStateWatermarkPredicate(rightAttributes, rightKeys,
leftAttributes, leftKeys)
JoinStateWatermarkPredicates(leftStateWatermarkPredicate,
rightStateWatermarkPredicate)
}
- private[join] def findJoinKeyOrdinalForWatermark(
+ /** Keep each cutoff attached to the column constrained by the join
condition. */
+ private def getStateValueWatermarkForInput(
+ inputAttributes: Seq[Attribute],
+ otherInputAttributes: Seq[Attribute],
+ condition: Option[Expression],
+ eventWatermark: Option[Long]): Option[(Attribute, Long)] = {
+ val eventTime = inputAttributes.find(_.metadata.contains(delayKey))
+ // Only the first marked column is checked for late input in compatibility
mode.
+ val otherEventTime =
otherInputAttributes.find(_.metadata.contains(delayKey))
+ // First try the watermarked column. If it has no inferable bound, try the
other timestamp
+ // columns in input schema order and use the first with a bound. This
makes the indexed column
+ // deterministic for a fixed input schema and join condition.
+ val candidates = eventTime.toSeq ++ inputAttributes.filter { attribute =>
+ attribute.dataType == TimestampType &&
!eventTime.exists(_.semanticEquals(attribute))
+ }
+ candidates.iterator.flatMap { attribute =>
+ StreamingJoinHelper.getStateValueWatermark(AttributeSet(Seq(attribute)),
+ AttributeSet(otherEventTime.toSeq), condition,
eventWatermark).map(attribute -> _)
+ }.take(1).toSeq.headOption
+ }
+
+ /**
+ * Conservatively prove that older state can use the current watermark
semantics. Without
+ * watermarks there is no affected state. Otherwise each side must have
exactly one event-time
+ * column, and its own event time must be the sole watermarked equality key
at the same ordinal.
+ * This excludes range bounds and retained event times with no eviction
bound. It also excludes
+ * a key computed from the event time by a constant, which older versions
evicted at the
+ * unshifted watermark. V4 additionally requires the selected equality key
timestamp to be
+ * provably non-null, because old V4 indexed null selected key timestamps
and timestamp
+ * eviction does not recheck the key predicate. A non-null window() key
qualifies: its end is
+ * computed from a non-null event time.
+ */
+ private[sql] def isWatermarkCheckpointCompatible(
+ leftAttributes: Seq[Attribute],
+ rightAttributes: Seq[Attribute],
leftKeys: Seq[Expression],
- rightKeys: Seq[Expression]): Option[Int] = {
- // Join keys of both sides generate rows of the same fields, that is, same
sequence of data
- // types. If one side (say left side) has a column (say timestamp) that
has a watermark on it,
- // then it will never consider joining keys that are < state key watermark
(i.e. event time
- // watermark). On the other side (i.e. right side), even if there is no
watermark defined,
- // there has to be an equivalent column (i.e., timestamp). And any right
side data that has the
- // timestamp < watermark will not match will not match with left side
data, as the left side get
- // filtered with the explicitly defined watermark. So, the watermark in
timestamp column in
- // left side keys effectively causes the timestamp on the right side to
have a watermark.
- // We will use the ordinal of the left timestamp in the left keys to find
the corresponding
- // right timestamp in the right keys.
- leftKeys.zipWithIndex.collectFirst {
- case (ne: NamedExpression, index) if ne.metadata.contains(delayKey) =>
index
- } orElse {
- rightKeys.zipWithIndex.collectFirst {
- case (ne: NamedExpression, index) if ne.metadata.contains(delayKey) =>
index
+ rightKeys: Seq[Expression],
+ stateFormatVersion: Int): Boolean = {
+ val leftEventTime = leftAttributes.filter(_.metadata.contains(delayKey))
+ val rightEventTime = rightAttributes.filter(_.metadata.contains(delayKey))
+
+ def watermarkKeyOrdinals(keys: Seq[Expression]): Seq[Int] = {
+ keys.zipWithIndex.collect {
+ case (key: NamedExpression, index) if key.metadata.contains(delayKey)
=> index
}
}
+
+ def selectedKeyTimestampCanBeNull(key: Attribute): Boolean = key.dataType
match {
+ // window() derives the end from a non-null event time, though
TimeWindow declares the
+ // field nullable.
+ case _: StructType if key.metadata.contains(TimeWindow.marker) =>
+ key.nullable
+ case struct: StructType =>
+ key.nullable || struct.fields.lift(1).forall(_.nullable)
+ case _ =>
+ key.nullable
+ }
+
+ val leftOrdinals = watermarkKeyOrdinals(leftKeys)
+ val rightOrdinals = watermarkKeyOrdinals(rightKeys)
+ if (leftEventTime.isEmpty && rightEventTime.isEmpty) {
+ leftOrdinals.isEmpty && rightOrdinals.isEmpty
+ } else if (leftEventTime.size == 1 && rightEventTime.size == 1) {
+ val leftOrdinal = StreamingJoinHelper.getEventTimeKeyOrdinal(leftKeys,
leftAttributes)
+ val rightOrdinal = StreamingJoinHelper.getEventTimeKeyOrdinal(rightKeys,
rightAttributes)
+ val alignedOwnEventTimeKeys = leftOrdinal.isDefined && leftOrdinal ==
rightOrdinal &&
Review Comment:
Thanks, the interval acceptance and the restored 2.4.0 and 3.5.1 restore
tests look right. I agree that comparing derivations through the current solver
is the wrong tool, since later PRs in the stack change constant-only, numeric
and negative-term bounds. On key-only joins: their output watermark matters
only to a stateful operator after the join. Without one, neither Spark version
evicts their state, so rejecting the checkpoint drops every buffered row, and
only a replay of the full input history can rebuild them. This review raises
that case together with whole-day intervals, which the exact-shift test still
rejects.
<!-- SPARK_DEV_REVIEW_REPLY
{"feedback_id":"inline:4523762425","thread_id":"inline:4523762425","verdict_sha256":"0042e4c7c6b7cb7775269472085f92208cfa538c4b2cb792572e86e16bb88411"}
-->
--
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]