HeartSaVioR commented on code in PR #60282:
URL: https://github.com/apache/spark/pull/60282#discussion_r4528814470
##########
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(
+ 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,
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.
Confirmed on this commit, and master has the same gap. SPARK-61348 (#60283),
the next PR in this stack, closes it: the shared solver gives a cutoff only
when the constrained column is TIMESTAMP, so outer and semi joins bounded
through DATE, TIMESTAMP_NTZ or other cast columns fail analysis, and admission
and eviction follow one rule. #60283 adds tests for the DATE and TIMESTAMP_NTZ
forms of `orderDate >= rt - INTERVAL 7 DAYS`, and its guide and migration text
name these types
([f885a5a0876](https://github.com/apache/spark/pull/60283/commits/f885a5a08766d0a1ce402ab9dff35dce9af28b98)).
<!-- sp2k-review1 reply 4523762375 -->
##########
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:
> [!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.
Both cases are fixed by the next two PRs in this stack: SPARK-61348 (#60283)
for non-TIMESTAMP bounds and SPARK-61349 (#60284) for constant-only bounds.
This PR's description lists them as deferred to those tickets. A TODO here
would be deleted by the very next commit, so I did not add one.
<!-- sp2k-review1 reply 4523762383 -->
##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinEqualityWatermarkSuite.scala:
##########
@@ -0,0 +1,277 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.streaming
+
+import org.apache.spark.sql.Row
+import
org.apache.spark.sql.execution.streaming.operators.stateful.join.StreamingSymmetricHashJoinExec
+import
org.apache.spark.sql.execution.streaming.operators.stateful.join.StreamingSymmetricHashJoinHelper.{JoinStateKeyWatermarkPredicate,
JoinStateValueWatermarkPredicate}
+import org.apache.spark.sql.execution.streaming.runtime.MemoryStream
+import org.apache.spark.sql.execution.streaming.state.RocksDBStateStoreProvider
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.internal.SQLConf
+
+class StreamingJoinEqualityWatermarkSuite extends StreamTest {
+ import testImplicits._
+
+ for {
+ version <- Seq(2, 3, 4)
+ restart <- Seq(false, true)
+ } {
+ test(s"equality eviction follows the opposite watermark, V$version
restart=$restart") {
+ withSQLConf(
+ SQLConf.STREAMING_JOIN_STATE_FORMAT_VERSION.key -> version.toString,
+ SQLConf.STATE_STORE_PROVIDER_CLASS.key ->
classOf[RocksDBStateStoreProvider].getName,
+ SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> "false") {
+ val leftInput = MemoryStream[(Int, Int)]
+ val rightInput = MemoryStream[(Int, Int)]
+ val left = leftInput.toDF().toDF("a", "b")
+ .select(timestamp_seconds($"a").as("la"),
timestamp_seconds($"b").as("lb"))
+ .withWatermark("la", "10 seconds")
+ val right = rightInput.toDF().toDF("a", "b")
+ .select(timestamp_seconds($"a").as("ra"),
timestamp_seconds($"b").as("rb"))
+ .withWatermark("rb", "10 seconds")
+ val joined = left.join(right, expr("la = ra AND lb = rb"),
"full_outer")
+ .select($"la".cast("int"), $"lb".cast("int"),
+ $"ra".cast("int"), $"rb".cast("int"))
+ withTempDir { checkpoint =>
+ val restartActions = if (restart) {
+ Seq(StopStream, StartStream(checkpointLocation =
checkpoint.getCanonicalPath))
+ } else {
+ Nil
+ }
+ testStream(joined)((Seq(
+ StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+ MultiAddData(leftInput, (5, 50))(rightInput, (80, 50)),
+ CheckNewAnswer(),
+ MultiAddData(leftInput, (60, 100))(rightInput, (70, 50)),
+ CheckNewAnswer(),
+ AddData(leftInput, (70, 100)),
+ // At watermark 40, left (5, 50) can still match fresh right input
on rb=50.
+ CheckNewAnswer()) ++ restartActions ++ Seq(
+ AddData(rightInput, (5, 50)),
+ CheckNewAnswer(Row(5, 50, 5, 50)),
+ // Fresh on la, but already expired on lb: V4 must visit it below
the old cutoff.
+ AddData(leftInput, (90, 10)),
+ CheckNewAnswer(Row(90, 10, null, null)),
+ MultiAddData(leftInput, (200, 200))(rightInput, (200, 200)),
+ CheckNewAnswer(Row(200, 200, 200, 200)),
+ MultiAddData(leftInput, (210, 210))(rightInput, (210, 210)),
+ CheckNewAnswer(Row(210, 210, 210, 210), Row(60, 100, null, null),
+ Row(70, 100, null, null), Row(null, null, 80, 50), Row(null,
null, 70, 50))
+ )): _*)
+ }
+ }
+ }
+ }
+
+ test("V4 window equality retains state for future unwatermarked input") {
+ withSQLConf(
+ SQLConf.STREAMING_JOIN_STATE_FORMAT_VERSION.key -> "4",
+ SQLConf.STATE_STORE_PROVIDER_CLASS.key ->
classOf[RocksDBStateStoreProvider].getName) {
+ val leftInput = MemoryStream[Int]
+ val rightInput = MemoryStream[Int]
+ val left = leftInput.toDF()
+ .select($"value".as("key"), timestamp_seconds($"value").as("time"))
+ .withWatermark("time", "10 seconds")
+ .select($"key", window($"time", "10 seconds"))
+ val right = rightInput.toDF()
+ .select($"value".as("key"), timestamp_seconds($"value").as("time"))
+ .select($"key", window($"time", "10 seconds"))
+ val joined = left.join(right, Seq("key", "window"))
+ .select($"key", $"window.end".cast("long"))
+ testStream(joined)(
+ AddData(leftInput, 1), CheckNewAnswer(),
+ AddData(rightInput, 1), CheckNewAnswer(Row(1, 10L)),
+ AddData(leftInput, 25), CheckNewAnswer(),
+ StopStream, StartStream(),
+ // The right input has no late filter; its old window must still find
left state.
+ AddData(rightInput, 1), CheckNewAnswer(Row(1, 10L)),
+ AddData(leftInput, 5), CheckNewAnswer())
+ }
+ }
+
+ for {
+ version <- Seq(2, 3, 4)
+ offset <- Seq(10, -10)
+ } {
+ test(s"equality on a shifted opposite event time evicts state, V$version
offset=$offset") {
+ withSQLConf(
+ SQLConf.STREAMING_JOIN_STATE_FORMAT_VERSION.key -> version.toString,
+ SQLConf.STATE_STORE_PROVIDER_CLASS.key ->
classOf[RocksDBStateStoreProvider].getName,
+ SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> "false") {
+ val leftInput = MemoryStream[(Int, Int)]
+ val rightInput = MemoryStream[(Int, Int)]
+ val left = leftInput.toDF().toDF("lk", "lt")
+ .select($"lk", timestamp_seconds($"lt").as("lt"))
+ .withWatermark("lt", "10 seconds")
+ val right = rightInput.toDF().toDF("rk", "rt")
+ .select($"rk", timestamp_seconds($"rt").as("rt"))
+ .withWatermark("rt", "10 seconds")
+ // A left row matches the right row whose time is `offset` seconds
earlier.
+ val joined = left.join(right,
+ expr(s"lk = rk AND lt = rt + INTERVAL $offset SECONDS"),
"left_outer")
+ .select($"lk", $"lt".cast("int"), $"rk", $"rt".cast("int"))
+ testStream(joined)(
+ MultiAddData(leftInput, (1, 100 + offset), (2, 90 + offset), (3, 145
+ offset))(
+ rightInput, (9, 50)),
+ CheckNewAnswer(),
+ AddData(rightInput, (1, 100)),
+ CheckNewAnswer(Row(1, 100 + offset, 1, 100)),
+ MultiAddData(leftInput, (9, 300))(rightInput, (9, 150)),
+ // At watermark 90, a future right row can still have time 90.
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.
Agreed, fixed in SPARK-61345 (#60280,
[c4bdbf09fdb](https://github.com/apache/spark/pull/60280/commits/c4bdbf09fdbea72fee5ab22ad03b839f1d9d7a37)).
The comments now give each cutoff as the watermark plus the offset, less the 1
ms the solver subtracts for `>=`. They no longer say that a later right row can
have time 90.
<!-- sp2k-review1 reply 4523762390 -->
##########
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:
> [!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.
Agreed, fixed in SPARK-61345 (#60280), where the rule came from
([c4bdbf09fdb](https://github.com/apache/spark/pull/60280/commits/c4bdbf09fdbea72fee5ab22ad03b839f1d9d7a37)).
A shift that never moves a time backward, such as whole days, months or years,
now gets the opposite watermark itself as the key cutoff, as on master, and no
event-time bound. This holds in every session time zone. So `lt = rt + INTERVAL
1 DAY` in America/Los_Angeles evicts inner-join state again, and its left
outer, left semi and full outer forms pass analysis. A shift that can move a
time backward, such as `- INTERVAL 1 DAY`, still gets no bound. A
`timestampadd` key is not recognized; writing the key as `rt + INTERVAL 1 HOUR`
gives it a bound.
<!-- sp2k-review1 reply 4523762397 -->
--
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]