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


##########
common/utils/src/main/resources/error/error-conditions.json:
##########
@@ -8165,6 +8165,41 @@
     ],
     "sqlState" : "55019"
   },
+  "STREAMING_JOIN_CHECKPOINT_INCOMPATIBLE" : {
+    "message" : [
+      "Cannot reuse the checkpoint for the stream-stream join with condition 
<joinCondition>. Watermarked columns: left [<leftWatermarkColumns>], right 
[<rightWatermarkColumns>].",
+      "This Spark version changes how watermarks determine which rows can 
still match. Spark cannot verify that rows saved by the previous version can be 
reused safely for this join. Start the query with a new checkpoint and replay 
the required input, accounting for previously written results to avoid 
duplicates and correct any missing or incorrect output."
+    ],
+    "sqlState" : "0A000"
+  },
+  "STREAMING_JOIN_UNBOUNDED_DOWNSTREAM_EVENT_TIME" : {
+    "message" : [
+      "The append-mode aggregation after a stream-stream join uses the event 
time <eventTime> of the join's <side> input, but the join has no bound on that 
event time for the state of that input, so it holds back its output watermark 
and the aggregation would never emit results."
+    ],
+    "subClass" : {
+      "TIME_CONSTRAINT" : {
+        "message" : [
+          "Add a time constraint that limits how late a matching <otherSide> 
row can arrive, aggregate the event time of an input whose state the join can 
bound. A bound on the event time comes from an equality key that shifts the 
other input's event time by an exact interval (under one day, or timestampadd 
in hours, minutes or seconds), or from a range condition used in place of a 
shifted equality. To run the query anyway, set <config> to false."

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 
[ab59957f358](https://github.com/apache/spark/pull/60280/commits/ab59957f3582d270164fd563b24f31603ff5e54c).
 The `TIME_CONSTRAINT` and `WATERMARK_AND_TIME_CONSTRAINT` messages now join 
their two remedies with "or", so they read as alternatives, as the 
`_OR_UPDATE_MODE` variants do.
   
   <!-- sp2k-review11 reply 4598159117 -->
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -705,33 +715,150 @@ object UnsupportedOperationChecker extends Logging {
       plan = operator)
   }
 
-  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
-        }
+  private def checkForStreamStreamJoinWatermark(
+      join: Join,
+      eventTimeLags: EventTimeLags): Unit = {
+    val keys = ExtractEquiJoinKeys.unapply(join)
+    val leftKeys = keys.map(_._2).getOrElse(Nil)
+    val rightKeys = keys.map(_._3).getOrElse(Nil)
+
+    // TODO(SPARK-61347): this accepts a range bound on an input without its 
own watermark,
+    //   which eviction does not finalize yet.
+    // TODO(SPARK-61348): this also accepts a range bound on a column that is 
not TIMESTAMP,
+    //   which eviction never finalizes.
+    // TODO(SPARK-61349): this also accepts a bound that uses only constants, 
which does not
+    //   follow the other input's watermark and so cannot finalize unmatched 
state.
+    def canEvictState(
+        stateInput: LogicalPlan,
+        otherInput: LogicalPlan,
+        otherKeys: Seq[Expression]): Boolean = {
+      // Any watermarked column of the other input can bound state: each 
planned input keeps one
+      // distinct watermarked column when multiple stateful operators are 
allowed, or execution
+      // fails at start, and in legacy mode its lag lowers the cutoff.
+      StreamingJoinHelper.getStateKeyWatermarkOrdinal(
+        otherKeys, otherInput.output, Some(eventTimeLags)).isDefined ||
+        
StreamingJoinHelper.getStateValueWatermarkForLags(stateInput.outputSet, 
otherInput.output,
+          join.condition, Some(1000000), Some(eventTimeLags)).isDefined
+    }
+
+    // The rule of Spark versions before 4.4: a watermarked equality key, or a 
range bound that the
+    // solver finds for a finalized input. Disabling the finalization check 
never goes below it.
+    def admittedBeforeFinalizationCheck: Boolean = {
+      def hasRangeBound(stateInput: LogicalPlan, otherInput: LogicalPlan): 
Boolean =
+        StreamingJoinHelper.getStateValueWatermark(stateInput.outputSet, 
otherInput.outputSet,
+          join.condition, Some(1000000)).isDefined
+      (leftKeys ++ rightKeys).exists {
+        case a: AttributeReference => 
a.metadata.contains(EventTimeWatermark.delayKey)
+        case _ => false
+      } || (join.joinType match {
+        case LeftOuter | LeftSemi => hasRangeBound(join.left, join.right)

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 
[ab59957f358](https://github.com/apache/spark/pull/60280/commits/ab59957f3582d270164fd563b24f31603ff5e54c).
 `UnsupportedOperationsSuite` has a legacy-mode left outer and a left semi test 
whose only bound is `leftTime >= rightShifted`, where `rightShifted` is the 
right event time shifted back by a day, a lag that analysis cannot bound. By 
default each fails analysis with the error that names the conf, and with the 
finalization check disabled each passes with the warning. Returning false from 
the left outer and left semi range arm makes the second half fail, which I 
checked.
   
   <!-- sp2k-review11 reply 4598159155 -->
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -17,36 +17,720 @@
 
 package org.apache.spark.sql.catalyst.analysis
 
+import java.util.Locale
+
+import scala.util.Try
 import scala.util.control.NonFatal
 
 import org.apache.spark.internal.Logging
 import org.apache.spark.internal.LogKeys._
+import org.apache.spark.sql.catalyst.InternalRow
 import org.apache.spark.sql.catalyst.expressions._
-import org.apache.spark.sql.catalyst.planning.ExtractEquiJoinKeys
-import org.apache.spark.sql.catalyst.plans.logical.{EventTimeWatermark, 
LogicalPlan}
+import org.apache.spark.sql.catalyst.plans.{InnerLike, LeftOuter, RightOuter}
+import org.apache.spark.sql.catalyst.plans.logical.{Expand, Join, LogicalPlan, 
Project, UnaryNode, Union}
 import org.apache.spark.sql.catalyst.plans.logical.EventTimeWatermark._
-import org.apache.spark.sql.catalyst.util.DateTimeConstants.MICROS_PER_DAY
+import org.apache.spark.sql.catalyst.util.DateTimeConstants.{MICROS_PER_DAY, 
MICROS_PER_HOUR, MICROS_PER_MILLIS, MICROS_PER_MINUTE, MICROS_PER_SECOND}
 import org.apache.spark.sql.types._
 import org.apache.spark.unsafe.types.CalendarInterval
 
+/**
+ * How far below a column that can filter its stream-stream join input's late 
rows one of the
+ * input's watermarked columns can be, for an equality key or a range 
condition on it: at most
+ * `micros` where the plan relates the two columns; by an amount that the plan 
does not bound when
+ * `unbounded`; and by an amount that it does not show when `unrelated`, 
because it does not relate
+ * the two. A window column is compared by its end, as eviction and late 
filtering compare it.
+ */
+case class EventTimeLag(micros: Long, unrelated: Boolean, unbounded: Boolean) {
+  def max(other: EventTimeLag): EventTimeLag = EventTimeLag(math.max(micros, 
other.micros),
+    unrelated || other.unrelated, unbounded || other.unbounded)
+
+  /**
+   * The cutoff for the other input's equality key when this input's watermark 
is `watermark`.
+   * A key that the plan does not relate keeps the Spark 4.3 cutoff.
+   */
+  def keyWatermark(watermark: Long): Option[Long] =
+    if (unbounded) None else Some(watermark - EventTimeLag.ceilMillis(micros))
+
+  /**
+   * The watermark to substitute for the column in a range condition. Spark 
4.3 substituted the
+   * watermark for every watermarked column; this does so only where the plan 
bounds the lag.
+   */
+  def rangeWatermark(watermark: Long): Option[Long] =
+    if (unbounded || unrelated) None else Some(watermark - 
EventTimeLag.ceilMillis(micros))
+}
+
+object EventTimeLag {
+  val zero: EventTimeLag = EventTimeLag(0L, unrelated = false, unbounded = 
false)
+  val unrelated: EventTimeLag = EventTimeLag(0L, unrelated = true, unbounded = 
false)
+  val unbounded: EventTimeLag = EventTimeLag(0L, unrelated = false, unbounded 
= true)
+
+  private def ceilMillis(micros: Long): Long =
+    micros / MICROS_PER_MILLIS + (if (micros % MICROS_PER_MILLIS == 0) 0 else 
1)

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 
[ab59957f358](https://github.com/apache/spark/pull/60280/commits/ab59957f3582d270164fd563b24f31603ff5e54c).
 `StreamingJoinHelperSuite` checks `keyWatermark` and `rangeWatermark` at a 
watermark of 10,000 ms: a lag of 500 microseconds gives 9,999 ms, 1,000 gives 
9,999, 1,500 gives 9,998, 2,000 gives 9,998 and zero gives 10,000. Replacing 
`ceilMillis` with plain division makes it fail, which I checked.
   
   <!-- sp2k-review11 reply 4598159163 -->
   



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