spark-test commented on code in PR #60667:
URL: https://github.com/apache/spark/pull/60667#discussion_r4626507785
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -262,27 +262,34 @@ object StreamingSymmetricHashJoinHelper extends Logging {
prevStateKeyWatermark)
}
} else if (isWatermarkDefinedOnInput) { // case 2 in the
StreamingSymmetricHashJoinExec docs
- val stateValueWatermark = StreamingJoinHelper.getStateValueWatermark(
- attributesToFindStateWatermarkFor =
AttributeSet(oneSideInputAttributes),
- attributesWithEventWatermark =
AttributeSet(otherSideInputAttributes),
- condition,
- eventTimeWatermarkForEviction)
- // A row can pass late-input filtering but already be eligible for
eviction in this batch.
- // When the previous join-derived state cutoff is ahead of the
late-input watermark, a new
- // row can fall at or below that cutoff. V4 must scan from the
beginning to find such rows.
- val prevStateValueWatermark = eventTimeWatermarkForLateEvents.flatMap
{ lateWatermark =>
- StreamingJoinHelper.getStateValueWatermark(
- attributesToFindStateWatermarkFor =
AttributeSet(oneSideInputAttributes),
- attributesWithEventWatermark =
AttributeSet(otherSideInputAttributes),
- condition,
- eventTimeWatermarkForLateEvents).filter(_ <= lateWatermark)
- }
- val inputAttributeWithWatermark =
oneSideInputAttributes.find(_.metadata.contains(delayKey))
- val expr = watermarkExpression(inputAttributeWithWatermark,
stateValueWatermark)
- expr.map { e =>
- // watermarkExpression only provides the expression when
eventTimeWatermarkForEviction
- // is defined
- JoinStateValueWatermarkPredicate(e, stateValueWatermark.get,
prevStateValueWatermark)
+ val eventTime =
oneSideInputAttributes.find(_.metadata.contains(delayKey))
+ // The legacy mode with a single global watermark keeps applying a
cutoff on any column of
+ // this input to the event time.
+ def solve(watermark: Option[Long]): Option[(Attribute, Long)] =
+ if (useFirstEventTimeColumn) {
+ StreamingJoinHelper.getStateValueWatermark(
+ attributesToFindStateWatermarkFor =
AttributeSet(oneSideInputAttributes),
+ attributesWithEventWatermark =
AttributeSet(otherSideInputAttributes),
+ condition,
+ watermark).map(eventTime.get -> _)
+ } else {
+
StreamingJoinHelper.getStateValueWatermarkColumn(oneSideInputAttributes,
Review Comment:
Thanks for the update. A follow-up stacked on the SPARK-62001 guard does not
help if this PR merges before that follow-up does: a query with a stateful
operator after such a join would then silently drop rows that master delivers,
such as the unmatched row for key 2 in your reproduction, which master emitted
and counted. So this stays blocking for this PR. Please either add the guard
for inputs evicted by a column other than their event time here, or land the
SPARK-62001 guard first and add its follow-up for this case to this PR, so that
this change never ships without that guard.
<!-- SPARK_DEV_REVIEW_REPLY
{"feedback_id":"inline:4615752059","thread_id":"inline:4615752059","verdict_sha256":"939dd9600385059026835fd5bfad9c9f55d7116c355d631a43f8dfc48b0a2524"}
-->
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -710,18 +740,30 @@ case class StreamingSymmetricHashJoinExec(
Predicate.create(Literal(false), Seq.empty).eval _ // false = do not
remove if no predicate
}
- private[this] val stateValueWatermarkPredicateFunc =
stateWatermarkPredicate match {
- case Some(JoinStateValueWatermarkPredicate(expr, _, _)) =>
- Predicate.create(expr, inputAttributes).eval _
- case _ =>
- Predicate.create(Literal(false), Seq.empty).eval _ // false = do not
remove if no predicate
- }
-
private[this] var updatedStateRowsCount = 0
private[this] var numRemovedFromOtherSideDuringJoinCount = 0
private[this] val allowMultipleStatefulOperators: Boolean =
conf.getConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE)
+ // When the join condition bounds the column that the value predicate
tests, a row with a NULL
+ // in it can never match, and `column <= cutoff` never holds for it. The
legacy mode, and the
+ // default mode for an input bounded only through a column cast to
TIMESTAMP, test the event
+ // time, which the condition need not bound.
+ private[this] val isEvictionColumnNull: UnsafeRow => Boolean =
stateWatermarkPredicate match {
+ case Some(JoinStateValueWatermarkPredicate(LessThanOrEqual(column, _),
_, _, true)) =>
+ Predicate.create(IsNull(column), inputAttributes).eval _
+ case _ => _ => false
+ }
+
+ // Such a row is not stored, but an earlier version or the legacy mode can
have stored one.
+ private[this] val stateValueWatermarkPredicateFunc =
stateWatermarkPredicate match {
+ case Some(JoinStateValueWatermarkPredicate(expr, _, _, _)) =>
+ val predicate = Predicate.create(expr, inputAttributes)
+ (row: UnsafeRow) => predicate.eval(row) || isEvictionColumnNull(row)
Review Comment:
**Non-blocking (P2):** This OR evicts stored rows with a NULL eviction
column only on state formats 1 to 3, which test every stored value. State
format 4 evicts by ranges of its index without evaluating this predicate: it
stores a NULL event time at index timestamp 0, and for an input evicted by its
event time every scan after a restart starts above 0, at the whole-input cutoff
at the late-events watermark in the first batch of a run and at the event
time's own cutoff in later batches, while the restart check passes because the
column is the event time. By the review's reading of the code, a state format 4
left outer join on `rightTime BETWEEN leftTime AND leftTime + INTERVAL 10
MINUTES`, restarted from a checkpoint written before this change that holds a
left row with a NULL leftTime stored after the late-events watermark passed 10
minutes, keeps that row in state for good and never emits its null-padded row,
while on state format 2 the same upgrade evicts and emits it at the fir
st eviction.
This extends existing discussions
[1](https://github.com/apache/spark/pull/60667#discussion_r4615752076),
[2](https://github.com/apache/spark/pull/60667#discussion_r4615752153).
**Recommended change:** Make the first batch of a run also evict, on state
format 4, the index entries at timestamp 0 of an input that the default mode
evicts by its event time because the condition bounds it, so rows with a NULL
event time that an earlier version stored there leave state and an outer join
emits them, as on state formats 1 to 3. Extend the migration note's sentence on
such rows to state format 4, and add a stream-stream join restart test from a
state format 4 checkpoint written before this change, such as a fixture like
the existing 4.3-written one, plus a join state watermark helper test.
**Why this works:** getStateWatermarkPredicates records on the value
predicate that the batch's eviction must also cover index timestamp 0 when it
is the first batch of a run, the column is the event time, the condition bounds
it, and the scan start lies at or above 0; OneSideHashJoiner's state format 4
branches then evict that single timestamp, the range above -1 microsecond up to
0, before the usual range from the scan start, and removeAndReturnOldState
returns those rows so an outer join emits them as unmatched. Later batches need
nothing more, because the NULL rule keeps new rows with a NULL column out of
state.
**Compatibility:** Eviction of rows with a non-NULL event time, the
first-batch whole-input start and the later-batch event-time start stay as the
change makes them.
**Risks:** Each restart adds one point scan of index timestamp 0 per state
format 4 input evicted by its bounded event time, a negligible cost that also
runs for inputs holding no such rows. After the upgrade, outer joins on state
format 4 emit, in the first batch, the null-padded rows of restored rows with a
NULL event time, which earlier versions never emitted; the migration note has
to say so.
**Constraints:** Apply it only when the default mode picked the event time
because the condition bounds it; on the fallback for an input bounded only
through a column cast to TIMESTAMP, where such a row can still match, and in
the legacy mode, which keeps the earlier behavior, a row with a NULL event time
keeps the base handling. Keep the first-batch whole-input start and the
later-batch event-time start for every other entry of the index.
**Exclusions:**
- Rows with a NULL event time on the cast-bounded fallback, which can still
match and whose eviction belongs to SPARK-62044.
**Verification:**
- **Regression:** On state format 4, a left outer time-interval join
restarted from a checkpoint written before this change, holding a left row with
a NULL event time stored after the scan start passed timestamp 0, emits that
row's null-padded row in the first batch after the restart and keeps no state
row for it.
- **Compatibility:** The same restart without NULL event times produces the
same output and state as before the repair, and with the cast-bounded fallback
or in the legacy mode a stored row with a NULL event time is kept as on the
base branch.
- **Behavior:** The value predicate asks for the timestamp-0 eviction only
in the first batch of a run, for a picked event time the condition bounds, when
its scan start lies at or above 0.
- **Inspection:** The 4.4-to-4.5 Structured Streaming migration note says
that state format 4, like state formats 1 to 3, evicts after the upgrade the
rows with a NULL eviction column that a checkpoint of an earlier version holds.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -73,12 +73,15 @@ object StreamingSymmetricHashJoinHelper extends Logging {
}
/**
* Predicate for watermark on state values. See
[[JoinStateKeyWatermarkPredicate]] for
- * the semantics of `stateWatermark` and `prevStateWatermark`.
+ * the semantics of `stateWatermark` and `prevStateWatermark`.
`conditionBoundsColumn` is true
Review Comment:
**Nit (P3):** The flag is set only when the default mode's pick chose the
column (solve, lines 282-289 of this file), not whenever the condition bounds
it: with allowMultiple set to false, `rightTime BETWEEN leftTime AND leftTime +
INTERVAL 10 MINUTES` bounds leftTime, yet the flag stays false. The comment
above the row screen in StreamingSymmetricHashJoinExec.scala (lines 888-891)
likewise says that a NULL eviction column rules out any match, which does not
hold on the cast-bounded fallback: under `CAST(leftDate AS TIMESTAMP) >=
rightTime` a row with a NULL leftTime still matches, as the new test expects
Row(1, 100L, null). A maintainer who trusts either comment could apply the NULL
rule to a column the condition does not bound and bring back the dropped
matches the last commit fixed. Saying in both places that the rule applies only
to a column the default mode picked because the condition bounds it, and that
the legacy mode and the cast-bounded fallback leave the flag false, wou
ld close that gap.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60667#discussion_r4622801640).
**Verification:**
- **Inspection:** The conditionBoundsColumn doc and the comment above the
row screen in storeAndJoinWithOtherSide say that the rule applies only when the
default mode picked the column because the condition bounds it, and the doc
says that the legacy mode and the cast-bounded fallback leave the flag false.
##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinRangeEvictionSuite.scala:
##########
@@ -0,0 +1,577 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.streaming
+
+import java.io.File
+import java.nio.charset.StandardCharsets.UTF_8
+import java.nio.file.Files
+
+import org.apache.hadoop.fs.Path
+import org.apache.logging.log4j.Level
+
+import org.apache.spark.sql.{AnalysisException, DataFrame, Row}
+import org.apache.spark.sql.catalyst.analysis.StreamingJoinHelper
+import org.apache.spark.sql.execution.streaming.checkpointing.{OffsetMap,
OffsetSeq, OffsetSeqLog}
+import
org.apache.spark.sql.execution.streaming.operators.stateful.join.StreamingSymmetricHashJoinExec
+import org.apache.spark.sql.execution.streaming.runtime.MemoryStream
+import org.apache.spark.sql.execution.streaming.state.RocksDBStateStoreProvider
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.tags.SlowSQLTest
+import org.apache.spark.util.Utils
+
+@SlowSQLTest
+class StreamingJoinRangeEvictionSuite extends StateStoreMetricsTest {
+ import testImplicits._
+
+ private def withJoinConf(version: Int)(f: => Unit): Unit = {
+ withSQLConf(
+ SQLConf.STREAMING_JOIN_STATE_FORMAT_VERSION.key -> version.toString,
+ SQLConf.STATE_STORE_PROVIDER_CLASS.key ->
classOf[RocksDBStateStoreProvider].getName,
+ SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> "false")(f)
+ }
+
+ // The left input has the event time leftTime and another TIMESTAMP column
expiry. A negative
+ // start or end gives a NULL leftTime or expiry.
+ private def joinWithExpiry(range: String, joinType: String)
+ : (MemoryStream[(Int, Long, Long)], MemoryStream[(Int, Long)],
DataFrame) = {
+ val leftInput = MemoryStream[(Int, Long, Long)]
+ val rightInput = MemoryStream[(Int, Long)]
+ val left = leftInput.toDF().toDF("leftKey", "start", "end")
+ .select($"leftKey", when($"start" >= 0,
timestamp_seconds($"start")).as("leftTime"),
+ when($"end" >= 0, timestamp_seconds($"end")).as("expiry"))
+ .withWatermark("leftTime", "60 seconds")
+ val right = rightInput.toDF().toDF("rightKey", "time")
+ .select($"rightKey", timestamp_seconds($"time").as("rightTime"))
+ .withWatermark("rightTime", "60 seconds")
+ val condition = expr(s"leftKey = rightKey AND $range")
+ val joined = if (joinType == "right_outer") {
+ right.join(left, condition, joinType)
+ } else {
+ left.join(right, condition, joinType)
+ }
+ val result = joined.select($"leftKey",
$"rightTime".cast("long").as("matchTime"),
+ $"leftTime".cast("long"))
+ (leftInput, rightInput, result)
+ }
+
+ // State format 3 shares the eviction code of format 2.
+ for {
+ version <- Seq(2, 4)
+ joinType <- Seq("inner", "left_outer", "right_outer")
+ shape <- Seq("between", "conjunction", "upper", "interval")
+ } {
+ test(s"range eviction uses the bounded column, V$version $joinType
$shape") {
+ withJoinConf(version) {
+ val range = shape match {
+ case "between" => "rightTime BETWEEN leftTime AND expiry"
+ case "conjunction" => "rightTime >= leftTime AND rightTime <= expiry"
+ case "interval" => "rightTime BETWEEN leftTime AND leftTime +
INTERVAL 10 MINUTES"
+ case _ => "rightTime <= expiry"
+ }
+ val (leftInput, rightInput, result) = joinWithExpiry(range, joinType)
+ testStream(result)(
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (1, 100L, 700L), (2, 100L, 700L)),
AddData(rightInput, (9, 100L)))),
+ CheckNewAnswer(),
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (8, 400L, 1000L)), AddData(rightInput, (9,
400L)))),
+ CheckNewAnswer(),
+ AddData(rightInput, (9, 400L)),
+ // The watermark has passed the start time, but the range has not
expired.
+ CheckNewAnswer(),
+ Execute { query =>
+ val join = query.lastExecution.executedPlan.collectFirst {
+ case j: StreamingSymmetricHashJoinExec => j
+ }.get
+ assert(join.eventTimeWatermarkForEviction.contains(340000L))
+ },
+ AddData(rightInput, (1, 460L)),
+ CheckNewAnswer(Row(1, 460L, 100L)),
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (8, 1000L, 1600L)), AddData(rightInput, (9,
1000L)))),
+ CheckNewAnswer(),
+ AddData(rightInput, (9, 1100L)),
+ CheckNewAnswer((if (joinType != "inner") Seq(Row(2, null, 100L))
else Nil): _*)
+ )
+ }
+ }
+ }
+
+ for {
+ version <- Seq(2, 3, 4)
+ joinType <- Seq("left_outer", "right_outer")
+ } {
+ test(s"range eviction includes newly admitted expired values, V$version
$joinType") {
+ withJoinConf(version) {
+ val (leftInput, rightInput, result) = joinWithExpiry("rightTime <=
expiry", joinType)
+ testStream(result)(
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (8, 100L, 700L)), AddData(rightInput, (9,
100L)))),
+ CheckNewAnswer(),
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (8, 400L, 1000L)), AddData(rightInput, (9,
400L)))),
+ CheckNewAnswer(),
+ AddData(rightInput, (9, 400L)), CheckNewAnswer(),
+ // The start passes late filtering, but expiry is below the previous
eviction cutoff.
+ AddData(leftInput, (3, 460L, 200L)), CheckNewAnswer(Row(3, null,
460L)),
+ AddData(rightInput, (9, 500L)), CheckNewAnswer())
+ }
+ }
+ }
+
+ for {
+ version <- Seq(2, 4)
+ joinType <- Seq("left_outer", "right_outer")
+ } {
+ test(s"a row whose range-eviction column is NULL is emitted on arrival,
V$version $joinType") {
+ withJoinConf(version) {
+ val (leftInput, rightInput, result) =
+ joinWithExpiry("rightTime BETWEEN leftTime AND expiry", joinType)
+ testStream(result)(
+ // The row can never match, so it is not stored, although the next
eviction would remove
+ // it.
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (1, 100L, -1L), (2, 100L, 700L)),
AddData(rightInput, (2, 150L)))),
+ CheckNewAnswer(Row(1, null, 100L), Row(2, 150L, 100L)),
+ assertNumStateRows(total = 2, updated = 2))
+ }
+ }
+ }
+
+ for (version <- Seq(2, 4)) {
+ test(s"a row whose event time is NULL is emitted on arrival, V$version") {
+ withJoinConf(version) {
+ val (leftInput, rightInput, result) = joinWithExpiry(
+ "rightTime BETWEEN leftTime AND leftTime + INTERVAL 10 MINUTES",
"left_outer")
+ testStream(result)(
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (1, -1L, 700L), (2, 100L, 700L)),
AddData(rightInput, (2, 150L)))),
+ CheckNewAnswer(Row(1, null, null), Row(2, 150L, 100L)),
+ assertNumStateRows(total = 2, updated = 2))
+ }
+ }
+ }
+
+ // The condition bounds the left input only through leftDate cast to
TIMESTAMP, so the left
+ // input is evicted by leftTime with the cutoff from leftDate, as in earlier
versions. A negative
+ // start gives a NULL leftTime, which the condition does not reference.
+ private def joinWithDate(joinType: String)
+ : (MemoryStream[(Int, Long, Int)], MemoryStream[(Int, Long)], DataFrame)
= {
+ val leftInput = MemoryStream[(Int, Long, Int)]
+ val rightInput = MemoryStream[(Int, Long)]
+ val left = leftInput.toDF().toDF("leftKey", "start", "day")
+ .select($"leftKey", when($"start" >= 0,
timestamp_seconds($"start")).as("leftTime"),
+ date_add(lit("1970-01-01").cast("date"), $"day").as("leftDate"))
+ .withWatermark("leftTime", "60 seconds")
+ val right = rightInput.toDF().toDF("rightKey", "time")
+ .select($"rightKey", timestamp_seconds($"time").as("rightTime"))
+ .withWatermark("rightTime", "60 seconds")
+ val result = left.join(right,
+ expr("leftKey = rightKey AND CAST(leftDate AS TIMESTAMP) >= rightTime"),
joinType)
+ .select($"leftKey", $"rightTime".cast("long").as("matchTime"),
$"leftTime".cast("long"))
+ (leftInput, rightInput, result)
+ }
+
+ for {
+ version <- Seq(2, 4)
+ joinType <- Seq("inner", "left_outer")
+ } {
+ test(s"an input bounded only through a cast column keeps the earlier
eviction, " +
+ s"V$version $joinType") {
+ withJoinConf(version) {
+ val (leftInput, rightInput, result) = joinWithDate(joinType)
+ testStream(result)(
+ // The left row with a NULL leftTime and a leftDate of one day
matches.
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (1, -1L, 1), (2, 100L, 0)), AddData(rightInput,
(1, 100L)))),
+ CheckNewAnswer(Row(1, 100L, null)),
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (8, 400L, 0)), AddData(rightInput, (1, 400L)))),
+ CheckNewAnswer(Row(1, 400L, null)),
+ // The cutoff on leftTime is 340 s. State format 4 indexed the NULL
leftTime as 0 and
+ // evicted it in the last batch.
+ AddData(rightInput, (1, 500L)),
+ CheckNewAnswer(
+ (if (version == 2) Seq(Row(1, 500L, null)) else Nil) ++
+ (if (joinType == "left_outer") Seq(Row(2, null, 100L)) else
Nil): _*))
+ }
+ }
+ }
+
+ // The legacy mode stores rows by the earlier rule: it evicts by the event
time, with the cutoff
+ // from expiry, and keeps a row whose event time is NULL.
+ for (version <- Seq(2, 4)) {
+ test(s"range eviction in the legacy mode keeps the earlier behavior,
V$version") {
+ withJoinConf(version) {
+ withSQLConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key -> "false") {
+ val (leftInput, rightInput, result) =
+ joinWithExpiry("rightTime BETWEEN leftTime AND expiry",
"left_outer")
+ testStream(result)(
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (1, 100L, 700L), (2, 100L, 700L), (3, -1L,
700L)),
+ AddData(rightInput, (9, 100L)))),
+ CheckNewAnswer(),
+ assertNumStateRows(total = 4, updated = 4),
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (8, 400L, 1000L)), AddData(rightInput, (9,
400L)))),
+ // State format 4 indexes a NULL event time as 0.
+ CheckNewAnswer((if (version == 4) Seq(Row(3, null, null)) else
Nil): _*),
+ AddData(rightInput, (9, 400L)),
+ CheckNewAnswer(Row(1, null, 100L), Row(2, null, 100L)),
+ AddData(rightInput, (1, 460L)),
+ CheckNewAnswer())
+ }
+ }
+ }
+ }
+
+ // An earlier version, like the legacy mode, stored a row whose expiry is
NULL and evicted it by
+ // leftTime.
+ for (version <- Seq(2, 3)) {
+ test(s"a stored row whose range-eviction column is NULL is evicted,
V$version") {
+ withJoinConf(version) {
+ withTempDir { checkpoint =>
+ val (leftInput, rightInput, result) =
+ joinWithExpiry("rightTime BETWEEN leftTime AND expiry",
"left_outer")
+ withSQLConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key -> "false")
{
+ testStream(result)(
+ StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (1, 100L, -1L)), AddData(rightInput, (9,
100L)))),
+ CheckNewAnswer(),
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (8, 400L, 1000L)), AddData(rightInput, (9,
400L)))),
+ CheckNewAnswer(),
+ StopStream)
+ }
+ testStream(result)(
+ StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+ AddData(rightInput, (9, 400L)),
+ CheckNewAnswer(Row(1, null, 100L)))
+ }
+ }
+ }
+ }
+
+ // In state format 4, the extra conjunct gives the right side a value
predicate on rightTime, so
+ // that the range scan of the right joiner solves the bound that shifts by a
column.
+ for {
+ bound <- Seq("leftTime > rightTime + rightDelay",
+ "CAST(leftTime AS BIGINT) + leftOffset > CAST(rightTime AS BIGINT)")
+ version <- Seq(2, 4)
+ } {
+ test(s"range eviction does not log solver errors for other columns:
$bound, V$version") {
+ val logAppender = new LogAppender("stream-stream join state constraints")
+ withLogAppender(logAppender,
+ loggerNames =
Seq(StreamingJoinHelper.getClass.getName.stripSuffix("$")),
+ level = Some(Level.WARN)) {
+ withJoinConf(version) {
+ val leftInput = MemoryStream[(Int, Long, Long)]
+ val rightInput = MemoryStream[(Int, Long, Int)]
+ val left = leftInput.toDF().toDF("leftKey", "time", "leftOffset")
+ .select($"leftKey", timestamp_seconds($"time").as("leftTime"),
$"leftOffset")
+ .withWatermark("leftTime", "0 seconds")
+ val right = rightInput.toDF().toDF("rightKey", "time", "delay")
+ .select($"rightKey", timestamp_seconds($"time").as("rightTime"),
+ ($"delay" * expr("INTERVAL 1 SECOND")).as("rightDelay"))
+ .withWatermark("rightTime", "0 seconds")
+ val extra = if (version == 4) " AND leftTime < rightTime + INTERVAL
1 HOUR" else ""
+ val joined = left.join(right, expr(s"leftKey = rightKey AND
$bound$extra"))
+ .select($"leftKey", $"leftTime".cast("long"),
$"rightTime".cast("long"))
+ testStream(joined)(
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (1, 20L, 0L)), AddData(rightInput, (1, 10L,
5)))),
+ CheckNewAnswer(Row(1, 20L, 10L)),
+ AddData(rightInput, (2, 30L, 1)),
+ CheckNewAnswer())
+ }
+ }
+ // A per-row column leaves the bound unknown, which is not an error.
+ assert(!logAppender.loggingEvents.exists(
+ _.getMessage.getFormattedMessage.contains("Error trying to extract
state constraint")))
+ }
+ }
+
+ private val indexVersionKey =
SQLConf.STREAMING_JOIN_STATE_V4_INDEX_VERSION.key
+
+ private def indexVersion(checkpoint: File): Option[String] = {
+ new OffsetSeqLog(spark, new File(checkpoint,
"offsets").getCanonicalPath).getLatest().get._2
+ .metadataOpt.get.conf.get(indexVersionKey)
+ }
+
+ // Removes the V4 index version from the latest offset log entry, as older
versions wrote it.
+ private def removeIndexVersion(checkpoint: File): Unit = {
+ val offsetsPath = new File(checkpoint, "offsets").getCanonicalPath
+ val log = new OffsetSeqLog(spark, offsetsPath)
+ val (batchId, offsets) = log.getLatest().get
+ val updated = offsets match {
+ case o: OffsetSeq =>
+ o.copy(metadataOpt = o.metadataOpt.map(m => m.copy(conf = m.conf -
indexVersionKey)))
+ case o: OffsetMap =>
+ o.copy(metadata = o.metadata.copy(conf = o.metadata.conf -
indexVersionKey))
+ }
+ val path = new Path(offsetsPath, batchId.toString)
+ assert(path.getFileSystem(spark.sessionState.newHadoopConf()).delete(path,
false))
+ assert(log.add(batchId, updated))
+ }
+
+ // Copies a bundled checkpoint and points the copied operator metadata at
the state schema files
+ // of the copy. The bundled metadata names them under the placeholder
directory /checkpoint.
+ private def copyCheckpointFixture(name: String, checkpoint: File): Unit = {
+ Utils.copyDirectory(
+ new File(getClass.getResource(s"/structured-streaming/$name/").toURI),
checkpoint)
+ val metadataDir = new File(checkpoint, "state/0/_metadata/v2")
+ metadataDir.listFiles().filter(f => f.isFile &&
!f.getName.startsWith(".")).foreach { file =>
+ val metadata = new String(Files.readAllBytes(file.toPath), UTF_8)
+ val updated = metadata.replace("file:/checkpoint/", new
Path(checkpoint.toURI).toString + "/")
+ assert(updated != metadata, s"No state schema file is named in $file")
+ Files.write(file.toPath, updated.getBytes(UTF_8))
+ }
+ }
+
+ test("V4 restart from an older checkpoint keeps evicting by the event time")
{
+ withJoinConf(4) {
+ withTempDir { checkpoint =>
+ val (leftInput, rightInput, result) = joinWithExpiry(
+ "rightTime BETWEEN leftTime AND leftTime + INTERVAL 10 MINUTES",
"left_outer")
+ testStream(result)(
+ StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (1, 100L, 700L), (2, 100L, 700L)),
AddData(rightInput, (9, 100L)))),
+ CheckNewAnswer(),
+ StopStream)
+ assert(indexVersion(checkpoint) === Some("1"))
+ removeIndexVersion(checkpoint)
+ testStream(result)(
+ StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+ AddData(rightInput, (1, 160L)),
+ CheckNewAnswer(Row(1, 160L, 100L)),
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (8, 1000L, 1600L)), AddData(rightInput, (9,
1000L)))),
+ CheckNewAnswer(),
+ // The cutoff on leftTime is 340 s.
+ AddData(rightInput, (9, 1000L)),
+ CheckNewAnswer(Row(2, null, 100L)),
+ StopStream)
+ assert(indexVersion(checkpoint) === Some("0"))
+ }
+ }
+ }
+
+ // The legacy mode orders the state by the event time.
+ for (legacyFirst <- Seq(true, false)) {
+ test("V4 restart fails when the legacy mode changes and the condition
bounds another " +
+ s"column, legacy first=$legacyFirst") {
+ withJoinConf(4) {
+ withTempDir { checkpoint =>
+ val (leftInput, rightInput, result) =
+ joinWithExpiry("rightTime BETWEEN leftTime AND expiry",
"left_outer")
+ withSQLConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key ->
(!legacyFirst).toString) {
+ testStream(result)(
+ StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (1, 100L, 700L)), AddData(rightInput, (9,
100L)))),
+ CheckNewAnswer(),
+ StopStream)
+ }
+ assert(indexVersion(checkpoint) === Some(if (legacyFirst) "0" else
"1"))
+ withSQLConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key ->
legacyFirst.toString) {
+ testStream(result)(
+ StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+ AddData(rightInput, (9, 400L)),
+ ExpectFailure[AnalysisException] { e =>
+ checkError(
+ e.asInstanceOf[AnalysisException],
+ condition =
"STREAMING_JOIN_STATE_V4_CHECKPOINT_INCOMPATIBLE",
+ parameters = Map("side" -> "left", "column" -> "`expiry`"))
+ })
+ }
+ // The failed restart keeps the recorded version.
+ assert(indexVersion(checkpoint) === Some(if (legacyFirst) "0" else
"1"))
+ }
+ }
+ }
+ }
+
+ // The legacy mode, like earlier versions, evicted left rows only up to the
lower cutoff from
+ // expiry, so the V4 scan after the restart must start at or below that
cutoff.
+ test("V4 restart evicts rows between the earlier and the new cutoff") {
+ withJoinConf(4) {
+ withTempDir { checkpoint =>
+ val (leftInput, rightInput, result) = joinWithExpiry("leftTime >= " +
+ "rightTime - INTERVAL 10 SECONDS AND expiry >= rightTime - INTERVAL
100 SECONDS",
+ "left_outer")
+ withSQLConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key -> "false") {
+ testStream(result)(
+ StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (1, 900L, 5000L), (8, 1000L, 5000L)),
+ AddData(rightInput, (9, 1000L)))),
+ CheckNewAnswer(),
+ // The watermark is 940 s, and the cutoff from expiry keeps
leftTime 900 s.
+ AddData(rightInput, (9, 1000L)),
+ CheckNewAnswer(),
+ StopStream)
+ }
+ testStream(result)(
+ StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+ AddData(rightInput, (9, 1300L)),
+ CheckNewAnswer(Row(1, null, 900L)))
+ }
+ }
+ }
+
+ // Within a run, the V4 scan of the left input starts at the event time's
own cutoff, which is
Review Comment:
**Nit (P3):** The test checks only join output, which is the same with the
whole-input start, so it cannot tell whether the scan really starts at the
event time's own cutoff. By the review's reading of the code, if the
isFirstBatch argument at IncrementalExecution.scala:618 is dropped or set to
true, the left predicate's prevStateWatermark becomes 839999 ms instead of
929999 ms in the batches whose late-events watermark is 940 s, but no left row
lies between those starts then: the row at 900 s was already evicted in the
second batch and the row at 1000 s lies above both, so the same rows are
emitted and the test still passes while each later batch re-scans the
already-evicted entries. Asserting that start in a later batch, read from
lastExecution as StreamingJoinV4Suite's extractPrevWatermarks does, would make
the test fail when the wiring regresses.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60667#discussion_r4622801674).
**Verification:**
- **Regression:** In a state format 4 join run over several batches, the
left value predicate's scan start in a later batch of the run equals the event
time's own cutoff at the late-events watermark, and the check fails when
IncrementalExecution passes true for isFirstBatch or drops the argument.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -722,6 +744,16 @@ case class StreamingSymmetricHashJoinExec(
private[this] val allowMultipleStatefulOperators: Boolean =
conf.getConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE)
+ // The join condition bounds the column that the value predicate tests, so
a row with a NULL
+ // in it can never match, and the predicate never evicts it. The legacy
mode tests the event
+ // time even when the condition bounds another column.
+ private[this] val isEvictionColumnNull: UnsafeRow => Boolean =
stateWatermarkPredicate match {
Review Comment:
Thanks, the fix holds on state formats 1 to 3. State format 4 can still keep
rows with a NULL event time that an earlier version stored, so it is affected
after all; this review raises that separately.
<!-- SPARK_DEV_REVIEW_REPLY
{"feedback_id":"inline:4615752076","thread_id":"inline:4615752076","verdict_sha256":"939dd9600385059026835fd5bfad9c9f55d7116c355d631a43f8dfc48b0a2524"}
-->
--
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]