HeartSaVioR commented on code in PR #60279:
URL: https://github.com/apache/spark/pull/60279#discussion_r4546991624
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala:
##########
@@ -167,6 +170,16 @@ class IncrementalExecution(
private val allowMultipleStatefulOperators: Boolean =
sparkSession.sessionState.conf.getConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE)
+ /**
+ * Whether this is the first batch of a run that restores a checkpoint
pinned to older
+ * stream-stream join watermark semantics. Such a batch re-simulates the
previous batch with
+ * this version's output watermarks, which the older version may not have
evicted with.
+ */
+ private lazy val isFirstBatchWithOlderJoinWatermarkSemantics: Boolean =
isFirstBatch &&
Review Comment:
> [!NOTE]
> **DISCLAIMER:** This comment was written by an LLM: Claude Opus 5.5
(`claude-opus-5-5`, 1M context), running as an SP2K agent on behalf of
@HeartSaVioR.
Thanks. We keep the reset on the first batch of every run of such a
checkpoint, and the comment at the reset now says so. The pinned marker never
advances, so Spark cannot tell which version ran the previous batch. Limiting
the reset to the first run after the upgrade would mean guessing, and a wrong
guess would skip rows that were never evicted. The cost is one scan from the
start in the first batch of each run. A test now restarts an older checkpoint
twice and checks that neither run's first batch has a scan start. The PR
description will say that this applies to every later run, not only the first
one.
<!-- sp2k-review3 reply 4537966858 -->
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -843,12 +926,12 @@ case class StreamingSymmetricHashJoinExec(
nonLateRows.flatMap { row =>
val thisRow = row.asInstanceOf[UnsafeRow]
- // If this row fails the pre join filter, that means it can never
satisfy the full join
- // condition no matter what other side row it's matched with. This
allows us to avoid
- // adding it to the state, and generate an outer join row immediately
(or do nothing in
- // the case of inner join).
- if (preJoinFilter(thisRow)) {
- val key = keyGenerator(thisRow)
+ // If this row fails the pre join filter, or its eviction column is
NULL, that means it can
+ // never satisfy the full join condition no matter what other side row
it's matched with.
+ // This allows us to avoid adding it to the state, and generate an
outer join row
+ // immediately (or do nothing in the case of inner join).
+ val key = if (preJoinFilter(thisRow)) keyGenerator(thisRow) else null
+ if (key != null && !isEvictionColumnNull(key, thisRow)) {
Review Comment:
> [!NOTE]
> **DISCLAIMER:** This comment was written by an LLM: Claude Opus 5.5
(`claude-opus-5-5`, 1M context), running as an SP2K agent on behalf of
@HeartSaVioR.
Thanks. Fixed in
[c984d5cd38b](https://github.com/apache/spark/pull/60279/commits/c984d5cd38be5c8c24dd2120235af9ceb2db4dfc).
V1 to V3 eviction now also removes a stored row whose eviction column is NULL.
It uses the same null check as the arrival path. These formats test every
stored row in each batch, so no state migration is needed. V4 already evicts
such rows in the first-batch scan from the start. A new test stores a NULL-time
left row in V2 and V3 state, as Spark 4.3 did, restarts, and checks that the
first batch emits the row with nulls. Without the fix, the row stays in state.
The existing NULL range-end tests still pass.
<!-- sp2k-review3 reply 4537966865 -->
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala:
##########
@@ -602,8 +615,15 @@ class IncrementalExecution(
// The prevOffsetSeqMetadata.isDefined check guards against the first
batch, where
// watermark propagation yields Some(0) for late events even though no
state has been
// evicted yet, which would incorrectly skip entries at timestamp 0.
+ //
+ // On the first batch after restoring a checkpoint with older join
watermark semantics,
+ // the late-events watermark comes from re-simulating the previous
batch with this
+ // version's output watermarks. It can be above the watermark that the
older version
+ // evicted with, for example when this version leaves an unbounded
input out of an
Review Comment:
> [!NOTE]
> **DISCLAIMER:** This comment was written by an LLM: Claude Opus 5.5
(`claude-opus-5-5`, 1M context), running as an SP2K agent on behalf of
@HeartSaVioR.
Thanks, you are right. Fixed in
[c984d5cd38b](https://github.com/apache/spark/pull/60279/commits/c984d5cd38be5c8c24dd2120235af9ceb2db4dfc).
The comment now names the cases that can raise the re-simulated watermark.
After an upgrade, this version leaves a bounded input out of an upstream join's
output watermark when the next stateful operator does not read it. Between
runs, a plan change above an upstream join can change which inputs it holds
back for. The comment also says that the reset for an older checkpoint recurs
on every run, because the pinned marker does not advance.
<!-- sp2k-review3 reply 4537966944 -->
##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinCheckpointCompatibilitySuite.scala:
##########
@@ -0,0 +1,576 @@
+/*
+ * 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.file.Files
+
+import scala.jdk.CollectionConverters._
+import scala.util.Using
+
+import org.apache.hadoop.fs.Path
+
+import org.apache.spark.sql.{AnalysisException, DataFrame, Row}
+import org.apache.spark.sql.catalyst.expressions.{Alias, Attribute,
AttributeReference, Cast, Expression, GreaterThan}
+import org.apache.spark.sql.catalyst.plans.logical.EventTimeWatermark
+import org.apache.spark.sql.execution.streaming.checkpointing.{OffsetMap,
OffsetSeq, OffsetSeqLog}
+import
org.apache.spark.sql.execution.streaming.operators.stateful.join.{StreamingSymmetricHashJoinExec,
StreamingSymmetricHashJoinHelper}
+import
org.apache.spark.sql.execution.streaming.operators.stateful.join.StreamingSymmetricHashJoinHelper.{JoinStateKeyWatermarkPredicate,
JoinStateValueWatermarkPredicate, LeftSide, RightSide}
+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.sql.types.{IntegerType, LongType, MetadataBuilder,
StructField, StructType, TimestampType}
+import org.apache.spark.tags.SlowSQLTest
+import org.apache.spark.util.Utils
+
+@SlowSQLTest
+class StreamingJoinCheckpointCompatibilitySuite extends StreamTest {
+ import testImplicits._
+
+ private val markerKey =
SQLConf.STREAMING_JOIN_CHECKPOINT_WATERMARK_SEMANTICS_VERSION.key
+ private val currentMarker =
+
SQLConf.STREAMING_JOIN_CHECKPOINT_WATERMARK_SEMANTICS_VERSION.defaultValue.get.toString
+
+ private def setMarker(checkpoint: String, marker: Option[String]): Unit = {
+ def update(conf: Map[String, String]): Map[String, String] = {
+ (conf - markerKey) ++ marker.map(markerKey -> _)
+ }
+ val offsetsPath = checkpoint + "/offsets"
+ 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 =
update(m.conf))))
+ case o: OffsetMap =>
+ o.copy(metadata = o.metadata.copy(conf = update(o.metadata.conf)))
+ }
+ val path = new Path(offsetsPath, batchId.toString)
+ assert(path.getFileSystem(spark.sessionState.newHadoopConf()).delete(path,
false))
+ assert(log.add(batchId, updated))
+ }
+
+ private def snapshot(directory: File): Map[String, Seq[Byte]] = {
+ Using.resource(Files.walk(directory.toPath)) { paths =>
+ paths.iterator().asScala.filter(Files.isRegularFile(_)).map { path =>
+ directory.toPath.relativize(path).toString ->
Files.readAllBytes(path).toSeq
+ }.toMap
+ }
+ }
+
+ private def pinnedMarker(checkpoint: String): Option[String] = {
+ new OffsetSeqLog(spark, checkpoint +
"/offsets").getLatest().get._2.metadataOpt.get
+ .conf.get(markerKey)
+ }
+
+ private def markerAt(checkpoint: String, batchId: Long): Option[String] = {
+ new OffsetSeqLog(spark, checkpoint +
"/offsets").get(batchId).get.metadataOpt.get
+ .conf.get(markerKey)
+ }
+
+ private def withJoinConf(version: Int, logVersion: Int)(f: => Unit): Unit = {
+ withSQLConf(
+ SQLConf.STREAMING_JOIN_STATE_FORMAT_VERSION.key -> version.toString,
+ SQLConf.STREAMING_OFFSET_LOG_FORMAT_VERSION.key -> logVersion.toString,
+ SQLConf.STATE_STORE_PROVIDER_CLASS.key ->
classOf[RocksDBStateStoreProvider].getName,
+ SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> "false")(f)
+ }
+
+ private def joinInputs(shape: String): (MemoryStream[(Int, Int)],
+ MemoryStream[(Int, Int)], DataFrame) = {
+ val leftInput = MemoryStream[(Int, Int)]
+ val rightInput = MemoryStream[(Int, Int)]
+ val leftData = leftInput.toDF().toDF("leftKey", "time")
+ .select($"leftKey", timestamp_seconds($"time").as("leftTime"),
+ timestamp_seconds($"time" + 10).as("expiry"))
+ val rightData = rightInput.toDF().toDF("rightKey", "time")
+ .select($"rightKey", timestamp_seconds($"time").as("rightTime"))
+ val left = if (Seq("equality", "expiry", "pruned expiry", "unbounded")
+ .contains(shape)) {
+ leftData.withWatermark("leftTime", "100 seconds")
+ } else {
+ leftData
+ }
+ val right = if (shape != "no watermark") {
+ rightData.withWatermark("rightTime", "100 seconds")
+ } else {
+ rightData
+ }
+ val condition = shape match {
+ case "range" => "leftKey = rightKey AND leftTime > rightTime - INTERVAL
5 SECONDS"
+ case "expiry" => "leftKey = rightKey AND rightTime BETWEEN leftTime AND
expiry"
+ case "pruned expiry" => "leftKey = rightKey AND rightTime <= expiry"
+ case "unbounded" => "leftKey = rightKey"
+ case _ => "leftKey = rightKey AND leftTime = rightTime"
+ }
+ val joined = left.join(right, expr(condition))
+ val result = if (shape == "unbounded") {
+ // A stateful operator after this key-only join reads its output
watermark.
+ joined.select($"leftKey", $"rightKey", $"leftTime".cast("long"),
+ $"rightTime".cast("long")).dropDuplicates()
+ } else {
+ joined.select($"leftKey", $"rightKey")
+ }
+ (leftInput, rightInput, result)
+ }
+
+ test("checkpoint compatibility requires one aligned own-event-time equality
key") {
+ val watermarkMetadata = new MetadataBuilder()
+ .putLong(EventTimeWatermark.delayKey, 0L).build()
+ val leftId = AttributeReference("leftId", IntegerType)()
+ val rightId = AttributeReference("rightId", IntegerType)()
+ val leftTime = AttributeReference("leftTime", TimestampType,
+ metadata = watermarkMetadata)()
+ val rightTime = AttributeReference("rightTime", TimestampType,
+ metadata = watermarkMetadata)()
+ val compatible =
StreamingSymmetricHashJoinHelper.isWatermarkCheckpointCompatible(
+ _: Seq[Attribute], _: Seq[Attribute], _: Seq[Expression], _:
Seq[Expression], None,
+ consumedSides = Set(LeftSide, RightSide))
+
+ assert(compatible(Seq(leftId), Seq(rightId), Seq(leftId), Seq(rightId)))
+ assert(compatible(Seq(leftId, leftTime), Seq(rightId, rightTime),
+ Seq(leftId, leftTime), Seq(rightId, rightTime)))
+ assert(!compatible(Seq(leftId, leftTime), Seq(rightId, rightTime),
+ Seq(leftId, leftTime), Seq(rightTime, rightId)))
+ assert(!compatible(Seq(leftId, leftTime), Seq(rightId, rightTime),
+ Seq(leftId, leftTime, leftTime), Seq(rightId, rightTime, rightTime)))
+ assert(!compatible(Seq(leftId, leftTime), Seq(rightId, rightTime),
+ Seq(leftId), Seq(rightId)))
+ assert(!compatible(Seq(leftId, leftTime), Seq(rightId),
+ Seq(leftId, leftTime), Seq(rightId, rightId)))
+ assert(!compatible(Seq(leftId), Seq(rightId, rightTime),
+ Seq(leftId, leftId), Seq(rightId, rightTime)))
+ assert(!compatible(Seq(leftTime, rightTime), Seq(rightTime),
+ Seq(leftTime), Seq(rightTime)))
+ assert(!compatible(Seq(leftTime), Seq(rightTime, leftTime),
+ Seq(leftTime), Seq(rightTime)))
+ // Metadata alone must not select an earlier key or hide a computed
watermarked key.
+ val computed = Alias(leftTime, "computed")()
+ assert(!compatible(Seq(leftTime), Seq(rightTime),
+ Seq(computed, leftTime), Seq(rightTime, rightTime)))
+ assert(!compatible(Seq(leftId), Seq(rightId), Seq(computed), Seq(rightId)))
+
+ // A key-only join is accepted only when no stateful operator after it
reads its output
+ // watermark. Another condition, or a key that uses an event time, makes
it not key-only.
+ val notConsumed =
StreamingSymmetricHashJoinHelper.isWatermarkCheckpointCompatible(
+ _: Seq[Attribute], _: Seq[Attribute], _: Seq[Expression], _:
Seq[Expression],
+ _: Option[Expression], consumedSides = Set.empty)
+ val leftInput = Seq(leftId, leftTime)
+ val rightInput = Seq(rightId, rightTime)
+ assert(notConsumed(leftInput, rightInput, Seq(leftId), Seq(rightId), None))
+ assert(!notConsumed(leftInput, rightInput, Seq(leftId), Seq(rightId),
+ Some(GreaterThan(leftId, rightId))))
+ assert(!notConsumed(leftInput, rightInput, Seq(leftId, Cast(leftTime,
LongType)),
+ Seq(rightId, Cast(rightTime, LongType)), None))
+ assert(!notConsumed(leftInput, rightInput, Seq(leftId, computed),
Seq(rightId, rightTime),
+ None))
+
+ // Ordering time windows is excluded even when nothing reads the output
watermark: older
+ // versions derived an ordering bound for whole windows that this version
removes.
+ val windowType = StructType(Seq(
+ StructField("start", TimestampType), StructField("end", TimestampType)))
+ val leftWindow = AttributeReference("leftWindow", windowType,
+ metadata = watermarkMetadata)()
+ val rightWindow = AttributeReference("rightWindow", windowType,
+ metadata = watermarkMetadata)()
+ assert(!notConsumed(Seq(leftId, leftWindow), Seq(rightId, rightWindow),
Seq(leftId),
+ Seq(rightId), Some(GreaterThan(leftWindow, rightWindow))))
+ }
+
+ for {
+ version <- Seq(1, 2, 3, 4)
+ logVersion <- Seq(1, 2)
+ // Every marker below the current one takes the same rejection branch.
+ oldMarker <- Seq(None, Some("0"), Some((currentMarker.toInt -
1).toString)).distinct
+ shape <- Seq("range", "expiry", "pruned expiry", "unbounded")
+ } {
+ test(s"reject old $shape checkpoint, V$version log=$logVersion
old=$oldMarker") {
+ withJoinConf(version, logVersion) {
+ val (leftInput, rightInput, joined) = joinInputs(shape)
+ withTempDir { checkpointDir =>
+ val checkpoint = checkpointDir.getCanonicalPath
+ testStream(joined)(
+ StartStream(checkpointLocation = checkpoint),
+ MultiAddData(leftInput, (1, 10))(rightInput, (1, 10)),
+ CheckNewAnswer(if (shape == "unbounded") Row(1, 1, 10L, 10L)
+ else Row(1, 1)),
+ StopStream)
+ // Emulate old offset metadata. State is written by the current
implementation;
Review Comment:
> [!NOTE]
> **DISCLAIMER:** This comment was written by an LLM: Claude Sonnet 5.5
(`claude-sonnet-5-5`, 1M context) and Claude Opus 5.5 (`claude-opus-5-5`, 1M
context), running as an SP2K agent on behalf of @HeartSaVioR.
Thanks.
[c984d5cd38b](https://github.com/apache/spark/pull/60279/commits/c984d5cd38be5c8c24dd2120235af9ceb2db4dfc)
adds a checkpoint that Spark 4.3.0 wrote in state format 4. It is a left outer
interval join with a NULL-time row at timestamp 0, and the new test in
`StreamingJoinCheckpointCompatibilitySuite` resumes it. The first batch after
the restart emits the null-padded row, and the next batch emits nothing more.
The test fails if we turn off the older-version scan reset.
For the chained joins, we did not add a second Spark 4.3.0 fixture. A 4.3.0
checkpoint carries the older marker, so the first batch of every run already
scans every V4 join from the start, chained or not. That is the reset the
single-join fixture tests on real 4.3.0 state. The new reset for joins with a
stream-stream join below them matters for a checkpoint that this version wrote,
after a plan change between runs. A new test covers that case: it chains two V4
joins, removes a stream-static join between them, and fails without the reset.
<!-- sp2k-review3 reply 4537966873 -->
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala:
##########
@@ -878,3 +1060,13 @@ class IncrementalExecution(
}.exists(_ == true)
}
}
+
+/**
+ * A stateful operator that compares its input watermark with an event-time
column carrying the
+ * event time `eventTime` of one input, `side`, of the stream-stream join
`joinOperatorId`.
+ */
+private[runtime] case class JoinWatermarkConsumer(
+ consumer: SparkPlan,
Review Comment:
> [!NOTE]
> **DISCLAIMER:** This comment was written by an LLM: Claude Sonnet 5.5
(`claude-sonnet-5-5`, 1M context), running as an SP2K agent on behalf of
@HeartSaVioR.
Thanks. We are keeping the fields. The next PR in the stack (#60280) uses
`consumer` and `eventTime` in `checkJoinOutputWatermarkConsumers` to pick the
aggregation and name the event time in the error. If we remove them here,
#60280 adds them back. Both fields are unused only in this PR.
<!-- sp2k-review3 reply 4537966879 -->
--
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]