HeartSaVioR commented on code in PR #60279:
URL: https://github.com/apache/spark/pull/60279#discussion_r4596394805


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -717,21 +727,105 @@ 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.
+    // The check takes the generated key and the input row, so the key is 
computed only once.
+    private[this] val isEvictionColumnNull: (UnsafeRow, UnsafeRow) => Boolean =
+      stateWatermarkPredicate match {
+        case Some(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
+          (key, _) => key.isNullAt(ordinal)
+        case Some(JoinStateValueWatermarkPredicate(LessThanOrEqual(column, _), 
_, _)) =>
+          // Test the compared column, not the predicate: the predicate holds 
the cutoff, which
+          // changes every batch and would generate and compile new code each 
time.
+          val isNull = Predicate.create(IsNull(column), inputAttributes)
+          (_, row) => isNull.eval(row)
+        case _ =>
+          (_, _) => false
+      }
+
+    // V1 to V3 eviction tests every stored row each batch, so it also removes 
a row whose
+    // eviction column is NULL. This version never stores such a row, but an 
older version did,
+    // and the row can never match. isEvictionColumnNull reads only the key 
for a key predicate
+    // and only the row for a value predicate.
+    private[this] val stateKeyEvictionFunc: UnsafeRow => Boolean =
+      key => stateKeyWatermarkPredicateFunc(key) || isEvictionColumnNull(key, 
null)

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.
   
   Added in 
[4f0f7f34db1](https://github.com/apache/spark/pull/60279/commits/4f0f7f34db1b10d05842dad17bc9aea64194621f).
 Four cases restore a NULL-key or NULL-time left row on state formats 2 and 3, 
as an older version stored it: a first run without watermarks and with 
constraint propagation off, which stores the row, then a restart with 
watermarks. They cover a left outer and an inner join on `leftKey = rightKey 
AND leftTime = rightTime`, and on the time interval of the existing tests. The 
left outer cases output the row padded with nulls, and the inner cases show by 
the state rows that the row is gone. A real Spark 4.3.0 state format 3 
checkpoint of a left outer join with a NULL-key left row covers the key path 
that returns rows, as the state format 4 fixture does for V4. With the NULL 
check removed from the key or the value eviction function, these cases fail.
   
   <!-- sp2k-review10 reply 4571551481 -->
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -4237,6 +4237,19 @@ object SQLConf {
       .checkValue(v => Set(1, 2, 3, 4).contains(v), "Valid versions are 1, 2, 
3, and 4")
       .createWithDefault(2)
 
+  val STREAMING_JOIN_CHECKPOINT_WATERMARK_SEMANTICS_VERSION =
+    buildConf("spark.sql.streaming.join.checkpointWatermarkSemanticsVersion")
+      .internal()
+      .doc("Checkpoint generation for stream-stream join watermark semantics, 
persisted in " +
+        "the offset log. Older generations are accepted only when the query 
plan proves that " +
+        "its state and output watermark semantics are unchanged. The 
generation validates " +

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.
   
   Fixed in 
[4f0f7f34db1](https://github.com/apache/spark/pull/60279/commits/4f0f7f34db1b10d05842dad17bc9aea64194621f),
 with your wording: older generations are accepted only when the query plan 
proves that the saved join state, and every stateful operator after the join 
that uses the affected event times, keep their meaning.
   
   <!-- sp2k-review10 reply 4571551485 -->
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/SymmetricHashJoinStateManager.scala:
##########
@@ -253,47 +254,47 @@ class SymmetricHashJoinStateManagerV4(
   protected val keySchema = StructType(
     joinKeys.zipWithIndex.map { case (k, i) => StructField(s"field$i", 
k.dataType, k.nullable) })
   protected val keyAttributes = toAttributes(keySchema)
-  private val eventTimeColIdxOpt = WatermarkSupport.findEventTimeColumnIndex(
-    inputValueAttributes,
-    // NOTE: This does not accept multiple event time columns. This is not the 
same with the
-    // operator which we offer the backward compatibility, but it involves too 
many layers to
-    // pass the information. The information is in SQLConf.
-    allowMultipleEventTimeColumns = false)
-
-  // When there is no event time column in the value and no watermark ordinal 
in the key,
+  private val valueTimestampColumnOrdinal = {
+    val eventTimeColIdx = WatermarkSupport.findEventTimeColumnIndex(
+      inputValueAttributes,
+      // NOTE: This does not accept multiple event time columns. This is not 
the same with the
+      // operator which we offer the backward compatibility, but it involves 
too many layers to
+      // pass the information. The information is in SQLConf.
+      allowMultipleEventTimeColumns = false)
+    // Validate event-time columns above even when eviction indexes a 
different timestamp.
+    stateValueWatermarkColumnOrdinal.orElse(eventTimeColIdx)
+  }
+
+  // When there is no indexed timestamp column in the value and no watermark 
ordinal in the key,
   // the secondary index (TsWithKey) will never be used for eviction. Skip 
writing to it
   // to avoid unnecessary RocksDB merge overhead.
   // TODO(SPARK-56536): This could be further optimized by also considering 
whether the state
-  //   watermark predicate is defined. Even when an event time column exists, 
the secondary index
-  //   is unused if eviction is not possible (e.g., only one side defines a 
watermark in a time
-  //   interval join). That would require propagating the predicate 
information here.
-  private val hasEventTime: Boolean =
-    eventTimeColIdxOpt.isDefined || joinKeyOrdinalForWatermark.isDefined
+  //   watermark predicate is defined. Even when an indexed timestamp column 
exists, the secondary
+  //   index is unused if eviction is not possible (e.g., only one side 
defines a watermark in a
+  //   time interval join). That would require propagating the predicate 
information here.
+  private val hasTimestampForEviction: Boolean =
+    valueTimestampColumnOrdinal.isDefined || 
joinKeyOrdinalForWatermark.isDefined
 
   private val random = new scala.util.Random(System.currentTimeMillis())
-  private val bucketCountForNoEventTime = 1024
-  private val extractEventTimeFn: UnsafeRow => Long = { row =>
-    eventTimeColIdxOpt match {
-      case Some(idx) =>
-        val attr = inputValueAttributes(idx)
-
-        if (attr.dataType.isInstanceOf[StructType]) {
-          // NOTE: We assume this is window struct, as same as 
WatermarkSupport.watermarkExpression
-          row.getStruct(idx, 2).getLong(1)
-        } else {
-          row.getLong(idx)
-        }
-
-      case _ =>
-        // When event time column is not 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.
-        random.nextInt(bucketCountForNoEventTime)
+  private val bucketCountWithoutTimestamp = 1024
+  // A null indexed timestamp makes the value-eviction predicate SQL-unknown, 
so V2 and V3 never

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.
   
   Fixed in 
[4f0f7f34db1](https://github.com/apache/spark/pull/60279/commits/4f0f7f34db1b10d05842dad17bc9aea64194621f).
 The comment now gives the reason of V4: a row whose indexed timestamp is NULL 
can never satisfy the bound on that column, so a side that evicts by it never 
stores one, and a side without an eviction predicate keeps such a row out of 
the timestamp index, so that timestamp eviction never removes it. It also says 
that V1 to V3 remove such a row by a separate NULL check.
   
   <!-- sp2k-review10 reply 4571551490 -->
   



##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinRangeEvictionSuite.scala:
##########
@@ -0,0 +1,183 @@
+/*
+ * 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.logging.log4j.Level
+
+import org.apache.spark.sql.Row
+import org.apache.spark.sql.catalyst.analysis.StreamingJoinHelper
+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
+
+@SlowSQLTest
+class StreamingJoinRangeEvictionSuite extends StreamTest {
+  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)
+  }
+
+  // V3 shares V2's eviction code. BETWEEN is replaced by the conjunction 
before planning, so it
+  // only adds coverage for the outer-join watermark check during analysis.
+  for {
+    version <- Seq(2, 4)
+    joinType <- Seq("inner", "left_outer", "right_outer")
+    shape <- Seq("between", "conjunction", "upper", "interval", "downstream")
+    if shape != "between" || joinType != "inner"
+  } {
+    test(s"range eviction uses bounded timestamp, V$version $joinType $shape") 
{
+      withJoinConf(version) {
+        val leftInput = MemoryStream[(Int, Long, Long)]
+        val rightInput = MemoryStream[(Int, Long)]
+        val left = leftInput.toDF().toDF("leftKey", "start", "end")
+          .select($"leftKey", timestamp_seconds($"start").as("leftTime"),
+            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 range = shape match {
+          case "between" | "downstream" => "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 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 output = joined.select($"leftKey", $"leftTime",
+          $"rightTime".cast("long").as("matchTime"))
+        val deduplicated = if (shape == "downstream") {
+          output.dropDuplicates("leftKey", "matchTime")
+        } else {
+          output
+        }
+        val result = deduplicated.select($"leftKey", $"matchTime", 
$"leftTime".cast("long"))
+        val matched = Row(1, 460L, 100L)
+        val unmatched = Row(2, null, 100L)
+        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 interval has not 
expired.
+          CheckNewAnswer(),
+          Execute { query =>
+            val join = query.lastExecution.executedPlan.collectFirst {
+              case j: StreamingSymmetricHashJoinExec => j
+            }.get
+            assert(join.eventTimeWatermarkForEviction.contains(340000L))
+            if (shape != "interval") {
+              assert(join.produceOutputWatermark(340000L).contains(0L))
+            }
+          },
+          AddData(rightInput, (1, 460L)),
+          CheckNewAnswer(matched),
+          StreamProgressLockedActions(Seq(
+            AddData(leftInput, (8, 1000L, 1600L)), AddData(rightInput, (9, 
1000L)))),
+          CheckNewAnswer(),
+          AddData(rightInput, (9, 1100L)),
+          CheckNewAnswer((if (joinType != "inner") Seq(unmatched) else 
Seq.empty): _*)
+        )
+      }
+    }
+  }
+
+  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 = MemoryStream[(Int, Long, Long)]
+        val rightInput = MemoryStream[(Int, Long)]
+        val left = leftInput.toDF().toDF("leftKey", "start", "end")
+          .select($"leftKey", timestamp_seconds($"start").as("leftTime"),
+            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("leftKey = rightKey AND rightTime <= expiry")
+        val joined = if (joinType == "right_outer") {
+          right.join(left, condition, joinType)
+        } else {
+          left.join(right, condition, joinType)
+        }
+        val result = joined.select($"leftKey", $"rightKey", 
$"leftTime".cast("long"))
+        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 (bound <- Seq("leftTime > rightTime + rightDelay",

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.
   
   Fixed in 
[4f0f7f34db1](https://github.com/apache/spark/pull/60279/commits/4f0f7f34db1b10d05842dad17bc9aea64194621f).
 The solver-log case now also runs in state format 4 with the extra conjunct 
`leftTime < rightTime + INTERVAL 1 HOUR`, which gives the left side a 
value-eviction predicate on its event time, so the range scan of the right 
joiner solves the bound that shifts by a column of the other input. The 
expected matches are unchanged.
   
   <!-- sp2k-review10 reply 4571551497 -->
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -296,6 +292,229 @@ object StreamingSymmetricHashJoinHelper extends Logging {
     JoinStateWatermarkPredicates(leftStateWatermarkPredicate, 
rightStateWatermarkPredicate)
   }
 
+  /** 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))
+    // 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))

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 keep our position: #60283 (SPARK-61348) rejects this shape at 
analysis, and the stack is meant to merge in order, as the list in the 
description says; the TODO and the description say that an outer join bounded 
only through a cast keeps its unmatched rows until then. Moving the rejection 
into this PR would pull most of the admission change of step 5 into step 1 and 
rework the steps in between. If you still want it here, tell us and we will 
weigh that cost.
   
   <!-- sp2k-review10 reply 4571551661 -->
   



-- 
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]

Reply via email to