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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala:
##########
@@ -721,14 +869,69 @@ class IncrementalExecution(
 
     override def apply(plan: SparkPlan): SparkPlan = {
       val planWithStateOpId = plan transform composedRule
+      // Validate the checkpoint-pinned semantics before writing state 
metadata or opening state,
+      // including a restart retrying an incomplete batch zero.
+      if (isFirstBatchWithOlderJoinWatermarkSemantics) {
+        def watermarkColumns(input: SparkPlan): String = {
+          val columns = input.output.filter(
+            _.metadata.contains(EventTimeWatermark.delayKey))
+          if (columns.isEmpty) "none" else columns.map(_.name).mkString(", ")
+        }
+        // A join's output watermark reaches every stateful operator above it. 
One that uses its
+        // input watermark reads the inputs that the tracer names, or both 
inputs when it cannot
+        // be traced. An operator uses it when an input carries an event-time 
column, when it
+        // fires event-time timeouts, or when it passes the watermark to user 
code, as
+        // transformWithState does in every time mode. The join's output 
watermark changes
+        // nothing for any other operator, such as an update-mode count on a 
key.
+        def usesInputWatermark(operator: StatefulOperator): Boolean = operator 
match {
+          case _: TransformWithStateExec | _: TransformWithStateInPySparkExec 
=> true
+          case f: FlatMapGroupsWithStateExec if f.timeoutConf == 
EventTimeTimeout => true
+          case f: FlatMapGroupsInPandasWithStateExec if f.timeoutConf == 
EventTimeTimeout => true
+          case _ => operator.children.exists(
+            _.output.exists(_.metadata.contains(EventTimeWatermark.delayKey)))
+        }
+        val joinsBelowStatefulOperators = planWithStateOpId.collect {
+          case s: StatefulOperator if usesInputWatermark(s) => 
s.children.flatMap(_.collect {
+            case j: StreamingSymmetricHashJoinExec => 
j.stateInfo.map(_.operatorId)
+          }.flatten)
+        }.flatten.toSet
+        val tracedSides = joinWatermarkConsumers(planWithStateOpId)
+          .groupMap(_.joinOperatorId)(_.side)
+        def consumedSides(j: StreamingSymmetricHashJoinExec): Set[JoinSide] =
+          j.stateInfo.map(_.operatorId) match {
+            case Some(id) if joinsBelowStatefulOperators.contains(id) =>
+              tracedSides.get(id).map(_.toSet).getOrElse(Set(LeftSide, 
RightSide))

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 
[4f0f7f34db1](https://github.com/apache/spark/pull/60279/commits/4f0f7f34db1b10d05842dad17bc9aea64194621f),
 as you suggested. The restart check now counts an input only where its state 
watermark reaches a later operator through the join's output watermark. With 
`spark.sql.streaming.statefulOperator.allowMultiple=false` it counts no input, 
because every operator reads the batch watermark and none reads the join's 
output watermark. For a left semi join it never counts the right input, because 
the join's output watermark reads only the left state watermark. The eviction 
rules of the check are unchanged.
   
   Tests, each restarting a checkpoint without the semantics marker: a 
one-directional left semi join followed by a window count over a column that 
the tracer cannot follow resumes, and the same operator after an inner join is 
still rejected; a key-only join followed by a window count, in append and 
update mode, resumes with `allowMultiple=false` and is still rejected in update 
mode with `allowMultiple=true`; one-directional and month-interval joins 
followed by deduplication on either event time resume with 
`allowMultiple=false`. A key-only inner join followed by a processing-time 
`transformWithState` is still rejected.
   
   <!-- sp2k-review10 reply 4571551475 -->
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala:
##########
@@ -630,6 +660,124 @@ class IncrementalExecution(
       watermarkPropagator.propagate(currentBatchId, plan, 
watermarkForCurrBatch)
     }
 
+    /**
+     * Find, for each stateful operator that applies its input watermark to an 
event-time column,
+     * which stream-stream join inputs' event times that column carries. The 
walk follows the
+     * column down through nodes that pass it on unchanged, to the same 
position in every input
+     * of a union, and through windows built from it, which end after it. It 
stops at a join, at
+     * another operator that writes state or sets an event time, and at any 
node it does not
+     * recognize; a join that no traced column reaches holds back for both 
inputs.
+     */
+    private def joinWatermarkConsumers(plan: SparkPlan): 
Seq[JoinWatermarkConsumer] = {
+      def eventTime(output: Seq[Attribute]): Option[Attribute] =
+        output.find(_.metadata.contains(EventTimeWatermark.delayKey))
+
+      // A time or session window built from one column, plus constants, ends 
after that column.
+      def windowSource(window: Attribute, expression: Expression): 
Option[Attribute] = {
+        val isWindow = window.metadata.contains(TimeWindow.marker) ||
+          window.metadata.contains(SessionWindow.marker)
+        expression.references.toSeq match {
+          case Seq(source) if isWindow => Some(source)
+          case _ => None
+        }
+      }
+
+      def passThrough(child: SparkPlan, attribute: Attribute): Seq[(Long, 
JoinSide, Attribute)] =
+        child.output.find(_.exprId == 
attribute.exprId).toSeq.flatMap(findJoinSides(child, _))
+
+      def findJoinSides(
+          node: SparkPlan,
+          attribute: Attribute): Seq[(Long, JoinSide, Attribute)] = {
+        node match {
+          case j: StreamingSymmetricHashJoinExec =>
+            val side = if (eventTime(j.left.output).exists(_.exprId == 
attribute.exprId)) {
+              Some(LeftSide)
+            } else if (eventTime(j.right.output).exists(_.exprId == 
attribute.exprId)) {
+              Some(RightSide)
+            } else {
+              None
+            }
+            j.stateInfo.map(_.operatorId).zip(side).map { case (id, s) => (id, 
s, attribute) }
+              .toSeq
+          case p: ProjectExec =>
+            p.projectList.find(_.exprId == attribute.exprId).toSeq.flatMap {
+              case a: Attribute => passThrough(p.child, a)
+              case Alias(a: Attribute, _) => passThrough(p.child, a)
+              case alias: Alias =>
+                windowSource(alias.toAttribute, 
alias.child).toSeq.flatMap(passThrough(p.child, _))
+              case _ => Nil
+            }
+          case e: ExpandExec =>
+            // A sliding window is one projection per window; each must carry 
the same column.
+            val index = e.output.indexWhere(_.exprId == attribute.exprId)
+            val traced = e.projections.map { projection =>
+              projection.lift(index).toSeq.flatMap {
+                case a: Attribute => passThrough(e.child, a)
+                case expression =>
+                  windowSource(e.output(index), 
expression).toSeq.flatMap(passThrough(e.child, _))
+              }
+            }
+            if (traced.nonEmpty && traced.forall(_.nonEmpty) && 
traced.distinct.size == 1) {
+              traced.head
+            } else {
+              Nil
+            }
+          case u: UnionExec =>
+            val index = u.output.indexWhere(_.exprId == attribute.exprId)
+            if (index < 0) Nil else u.children.flatMap(c => findJoinSides(c, 
c.output(index)))
+          case _: StateStoreWriter | _: EventTimeWatermarkExec | _: 
UpdateEventTimeColumnExec =>
+            Nil
+          case u: UnaryExecNode if u.output.exists(_.exprId == 
attribute.exprId) =>
+            passThrough(u.child, attribute)
+          case _ => Nil

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 
[4f0f7f34db1](https://github.com/apache/spark/pull/60279/commits/4f0f7f34db1b10d05842dad17bc9aea64194621f).
 The tracer now follows a node with more than one input into the one input that 
outputs the traced column under the same expression ID. A stream-static join 
passes each streaming column through that way, or as NULL on rows that it pads, 
and a static input never outputs a streaming column, so the rule needs no list 
of join classes. If no input or more than one input outputs the column, the 
tracer still stops, and the join holds back for both inputs, as before. 
Stream-stream joins, unions and state writers keep their own cases.
   
   Tests: an append-mode window count behind a broadcast hash, a sort merge and 
a broadcast nested loop stream-static join. Over the impression time, the join 
follows the impression input and the windows are emitted. Over the click time, 
the join holds back at 0. The chained-join compatibility test now reads the 
click time through the stream-static join in the first run and the impression 
time in the second, and still checks that the downstream join scans from the 
start after that change. The restart check reads the same tracer, so older 
checkpoints of such queries are judged on the traced input only.
   
   <!-- sp2k-review10 reply 4571551493 -->
   



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -296,6 +293,258 @@ 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)] = {
+    // TODO(SPARK-61348): the analysis check admits a range bound on a column 
that is not

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).
 The TODO at the eviction candidates now also names SPARK-61508: an inner or 
left semi join side bounded only through such a cast column has no eviction 
predicate, keeps its rows for the life of the query until eviction through the 
cast is supported, and projecting the column to TIMESTAMP before the join 
bounds that state.
   
   <!-- sp2k-review10 reply 4571551463 -->
   



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelperSuite.scala:
##########
@@ -48,6 +50,34 @@ class StreamingJoinHelperSuite extends AnalysisTest {
     }
   }
 
+  test("state watermark extraction ignores columns outside both attribute 
sets") {
+    val leftTime = AttributeReference("leftTime", TimestampType)()
+    val leftOffset = AttributeReference("leftOffset", LongType)()
+    val metadata = new MetadataBuilder().putLong(EventTimeWatermark.delayKey, 
1000).build()
+    val rightTime = AttributeReference("rightTime", TimestampType, metadata = 
metadata)()
+    val rightDelay = AttributeReference("rightDelay", DayTimeIntervalType())()
+    val conditions = Seq(
+      leftTime > TimestampAddInterval(rightTime, rightDelay),
+      leftTime.cast(LongType) + leftOffset > rightTime.cast(LongType))
+    val logAppender = new LogAppender("state watermark extraction")
+    withLogAppender(logAppender, level = Some(Level.WARN)) {
+      conditions.foreach { condition =>
+        withClue(condition.sql) {
+          // The first condition reaches the references check through the V4 
range scan and the
+          // left semi exact cutoff, which pass only the opposite event time; 
eviction passes 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 
[4f0f7f34db1](https://github.com/apache/spark/pull/60279/commits/4f0f7f34db1b10d05842dad17bc9aea64194621f).
 The comment now says that the first condition reaches the references check 
only through the V4 range scan, which passes just the two event times, and only 
when another conjunct gives a side a value-eviction predicate on its own event 
time. It also says that the left semi exact cutoff keeps only conjuncts shifted 
by literal intervals, so a shift by the column `rightDelay` never reaches the 
solver there, and keeps the explanation of eviction for both conditions.
   
   <!-- sp2k-review10 reply 4571551465 -->
   



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