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


##########
docs/streaming/apis-on-dataframes-and-datasets.md:
##########
@@ -1433,8 +1451,31 @@ regarding watermark delays and whether data will be 
dropped or not.
 
 Additional details on supported joins:
 
+- For stream-stream outer and semi joins, an equality key counts as the time 
constraint in the
+  table above when it is the other input's event time, or that event time 
shifted by constant
+  intervals, such as `leftTime = rightTime + INTERVAL 10 MINUTES`. A key 
shifted backward by whole
+  days, months or years, such as `leftTime = rightTime - INTERVAL 1 DAY`, or 
truncated from the
+  other input's event time, such as `leftTime = CAST(CAST(rightTime AS BIGINT) 
AS TIMESTAMP)`,
+  does not count. When both inputs have watermarks, a time range condition 
between the two event
+  times, as in the time-interval join example above, can bound such a join 
instead.
+
 - Joins can be cascaded, that is, you can do `df1.join(df2, ...).join(df3, 
...).join(df4, ....)`.
 
+- For stream-stream outer and semi joins, the time constraint that finalizes 
an input's rows must
+  bound that input by the other input's event time, either through an equality 
key on that event
+  time or its time window, or through a range condition on a timestamp column 
of the input. A
+  range condition may also compare the input's time window as a whole with the 
other input's,
+  such as `leftWindow > rightWindow`, when the input's windows last at least 
as long as the
+  other input's. A range condition on a column of another type does not 
qualify: a numeric
+  column, such as `n > CAST(rightTime AS BIGINT)`, a DATE or TIMESTAMP_NTZ 
column, or a time
+  window shorter than the other input's.
+
+- A stream-stream inner join cleans up an input's state only with such a time 
constraint. For
+  example, an inner join whose only time constraint is `leftWindow > 
rightWindow`, with 10-second
+  left windows and 20-second right windows, keeps every left row in its state 
and holds back its
+  output watermark for the left input, so a stateful operator after the join 
that uses the left
+  windows cannot emit results.

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 
[11638546d59](https://github.com/apache/spark/pull/60283/commits/11638546d5997f303277c62edcdf73bf67a4a34f),
 in both the programming guide and the migration guide. They now say that an 
append-mode aggregation over the held-back windows fails at start. Other 
stateful operators that use them keep their rows and do not emit results that 
wait for the watermark, such as event-time timeouts. Update-mode aggregations 
and deduplication still emit rows.
   
   <!-- sp2k-review3 reply 4537867106 -->
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -66,13 +301,23 @@ object StreamingJoinHelper extends PredicateHelper with 
Logging {
    * @param attributesWithEventWatermark  attributes of the other side which 
has a watermark column
    * @param joinCondition                 join condition
    * @param eventWatermark                watermark defined on the input event 
data
+   * @param exactForUnwatermarkedColumns  whether a column without its own 
watermark gets no
+   *                                      cutoff from a condition that the 
solver counts
+   *                                      inexactly. State eviction and the 
admission check set
+   *                                      it, so they agree.
+   * @param baseAdmissionRules            whether to skip the checks that 
Spark 4.4 added to the

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 
[11638546d59](https://github.com/apache/spark/pull/60283/commits/11638546d5997f303277c62edcdf73bf67a4a34f).
 The doc now says the flag skips only the check that the bounded column is a 
TIMESTAMP column or a time window. It does not skip the inexact-arithmetic 
check for columns without their own watermark. That check follows 
`exactForUnwatermarkedColumns`, so a caller that wants the result of earlier 
versions leaves it false too.
   
   <!-- sp2k-review3 reply 4537867122 -->
   



##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinNumericWatermarkSuite.scala:
##########
@@ -0,0 +1,330 @@
+/*
+ * 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.{AnalysisException, DataFrame, Row}
+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 StreamingJoinNumericWatermarkSuite extends StreamTest {
+  import testImplicits._
+
+  private val timestampRule = "A time range condition must bound a TIMESTAMP 
column"
+
+  // Analysis rejects the plan before any state format is used. Each bound 
below is exact, with
+  // no truncating cast and no whole days, so only the TIMESTAMP-column rule 
rejects it.
+  test("left outer join cannot use a numeric state field for range eviction") {
+    val leftInput = MemoryStream[(Int, Long, Long)]
+    val rightInput = MemoryStream[(Int, Long)]
+    val left = leftInput.toDF().toDF("leftKey", "n", "time")
+      .select($"leftKey", $"n", timestamp_seconds($"time").as("lt"))
+      .withWatermark("lt", "1 second")
+    val right = rightInput.toDF().toDF("rightKey", "time")
+      .select($"rightKey", timestamp_seconds($"time").as("rt"))
+      .withWatermark("rt", "1 second")
+    val joined = left.join(right,
+      expr("leftKey = rightKey AND n > CAST(rt AS DOUBLE)"), "left_outer")
+      .select($"leftKey", $"n", $"lt")
+
+    val error = intercept[AnalysisException] {
+      testStream(joined)(
+        AddData(leftInput, (1, 20L, 20L)),
+        CheckNewAnswer())
+    }
+    assert(error.getMessage.contains("a watermark on the right input and a 
time constraint"))
+    assert(error.getMessage.contains(timestampRule))
+  }
+
+  // Earlier versions admitted this join, so disabling the finalization check 
runs it. The left
+  // state is never evicted, so the matched left row emits no null-padded row 
later.

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 
[11638546d59](https://github.com/apache/spark/pull/60283/commits/11638546d5997f303277c62edcdf73bf67a4a34f).
 The test now adds a left row `(2, 50)` that never matches and moves the 
eviction watermark to 99 seconds. It expects no output, so a left state that 
was evicted by the cutoff solved for `n` would emit that row with nulls and 
fail the test. We also changed the cast to `DOUBLE`, so the bound is exact and 
the suite comment is true again.
   
   <!-- sp2k-review3 reply 4537867130 -->
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -224,98 +230,334 @@ 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 when the opposite key is 
that input's event
+        // time, possibly shifted by constant intervals: by the shift for an 
exact interval, and
+        // unshifted for whole days, months or years that never move a time 
backward. See
+        // StreamingJoinHelper.getStateKeyWatermark for which shifts qualify.
+        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)] = {
+    // TODO(SPARK-61349): a conjunct that uses only constants still caps the 
cutoff, so it can
+    //   stop eviction.
+    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
+    // and time-window 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. The solver
+    // gives a cutoff for no other column, so the admission check, which tries 
every column,
+    // accepts the same bounds.
+    val candidates = eventTime.toSeq ++ inputAttributes.filter { attribute =>
+      StreamingJoinHelper.canTakeRangeCutoff(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.
   
   Fixed in 
[11638546d59](https://github.com/apache/spark/pull/60283/commits/11638546d5997f303277c62edcdf73bf67a4a34f).
 We added a test with your example: the left input is watermarked on `lt` and 
holds a 10-second window over the unwatermarked `ot`, joined on `lw > rw`. It 
checks that the unmatched left window comes out with nulls once the watermark 
passes it, in formats 2 and 4. If we remove the window branch from 
`canTakeRangeCutoff`, both tests fail.
   
   <!-- sp2k-review3 reply 4537867136 -->
   



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