spark-test commented on code in PR #60279:
URL: https://github.com/apache/spark/pull/60279#discussion_r4605182117


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala:
##########
@@ -721,14 +918,76 @@ 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(", ")
+        }
+        // In the default mode, 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(

Review Comment:
   **Blocking (P1):** `StreamingGlobalLimitExec`, which the planner uses for a 
limit over an append-mode stream, lands in this case whenever its input keeps 
an event-time column, although it never reads its input watermark. The tracer 
does not follow the limit either, so a stream-stream join below it counts both 
inputs as consumed.
   
   For an append-mode `left.join(right, expr("leftKey = rightKey")).limit(100)` 
with watermarks on `leftTime` and `rightTime` and both event times kept in the 
output, the key-only shortcut then no longer applies, and 
`isOwnEventTimeIntervalJoin` fails because neither input has a predicate, so by 
this review's reading of the code, restarting a checkpoint written before this 
change fails with `STREAMING_JOIN_CHECKPOINT_INCOMPATIBLE`. The same join 
without the limit resumes, as the suite's key-only resume case shows, and the 
base branch resumes both; a one-directional join on `rightTime <= leftTime + 
INTERVAL 5 SECONDS` followed by the limit is rejected the same way. The user 
then has to start a new checkpoint and replay the input, although the limit 
never reads the changed watermark.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60279#discussion_r4537966847).
   
   See **Shared repair plan 1** in the review body.



##########
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:
   Yes, we would still like it in this PR. Each PR of the stack merges to 
master on its own, so from this PR until SPARK-61348 lands, master accepts 
these outer joins and silently never emits their unmatched rows, which it 
emitted before this PR, and the TODO records the gap without preventing it. The 
rejection can stay narrow, failing at analysis only a left, right or full outer 
join whose preserved side has its own watermark and a bound only through a 
column that is not TIMESTAMP, and SPARK-61348 can then replace it with its own 
check.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4537966815","thread_id":"inline:4537966815","verdict_sha256":"f15363ed53a1d4aa87e3a8d3ee16ba2073ac9cced88f8522bb67f09ae9ff727b"}
 -->



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala:
##########
@@ -602,8 +618,25 @@ class IncrementalExecution(
         // The prevOffsetSeqMetadata.isDefined check guards against the first 
batch, where
         // watermark propagation yields Some(0) for late events even though no 
state has been
         // evicted yet, which would incorrectly skip entries at timestamp 0.
+        //
+        // On the first batch of a run, the late-events watermark comes from 
re-simulating the
+        // previous batch with this run's plan and semantics. An upstream 
stream-stream join's
+        // output watermark can then be above the one the previous batch 
evicted with, so this
+        // join scans from the start in that batch in two cases:
+        // - The checkpoint is pinned to older join watermark semantics. Older 
versions included
+        //   every bounded input in a join's output watermark; this version 
leaves out one that
+        //   the next stateful operator does not read. The pinned marker never 
advances, so this
+        //   recurs on the first batch of every run of such a checkpoint. 
Limiting it to the first
+        //   run after the upgrade would mean guessing which version ran the 
previous batch, and
+        //   a wrong guess skips rows that were never evicted.
+        // - Another stream-stream join is below this one. Its output 
watermark depends on the
+        //   plan above it (see withJoinOutputWatermarkSides), which can 
change between runs,
+        //   for example when a downstream operator reads another input's 
event time.
+        val hasJoinBelow =
+          
j.children.exists(_.exists(_.isInstanceOf[StreamingSymmetricHashJoinExec]))
         val prevBatchLateEventsWm =
-          if (prevOffsetSeqMetadata.isDefined && 
allowMultipleStatefulOperators) {
+          if (prevOffsetSeqMetadata.isDefined && 
allowMultipleStatefulOperators &&
+              !isFirstBatchWithOlderJoinWatermarkSemantics && !(isFirstBatch 
&& hasJoinBelow)) {

Review Comment:
   **Blocking (P1):** This drops only the join's own V4 scan start on the first 
batch of a run. The late-events watermark of the stateful operator after the 
join still comes from re-simulating the previous batch with this run's plan, 
including the `outputWatermarkSides` that the tracer now sets. So when a 
stream-stream join below an outer join narrows its output watermark to the 
input that the outer join reads, the operator after the outer join gets a 
higher late-events watermark than the previous run used, while the outer join 
still holds unmatched rows that the previous run kept below it.
   
   Take a Spark 4.3.0 checkpoint, with global watermark `W`, of `J0 = A inner 
join B on A.k = B.k AND B.t BETWEEN A.t AND A.t + INTERVAL 20 MINUTES` 
projected to B's columns, then `J1 = J0 left outer join D on B.k = D.k AND D.t 
BETWEEN B.t - INTERVAL 5 MINUTES AND B.t + INTERVAL 5 MINUTES` and an 
append-mode count by `window(B.t, '10 minutes')`. The older version forwarded 
`W - 20 minutes` from J0, so J1 kept left rows down to `W - 25 minutes` and the 
count filtered late rows there. By this review's reading of the code, the 
restart check accepts both joins, and in the first batch N of the new run the 
re-simulated batch N-1 narrows J0 to B, which gives J1 the input watermark 
`W(N-1)` and the count the late-events watermark `W(N-1) - 5 minutes`. J1 
evicts left rows up to `W(N) - 5 minutes` and emits the unmatched ones with 
`B.t` between `W(N-1) - 25` and `W(N-1) - 5` minutes padded with nulls; the 
count drops those whose window ends at or below `W(N-1) - 5 minutes` as late 
and then fin
 alizes those windows without them. The older version would have emitted these 
rows in later batches, while the count's late-events watermark was still below 
them.
   
   A plan change between runs that changes the traced inputs of the join below 
drops rows the same way on a checkpoint written by this version. Inner and left 
semi joins above are not affected, because every row they emit in that batch 
has a newer event time, and neither is a join with no stream-stream join below 
it.
   
   This extends existing discussions 
[1](https://github.com/apache/spark/pull/60279#discussion_r4537966830), 
[2](https://github.com/apache/spark/pull/60279#discussion_r4537966944).
   
   **Recommended change:** Record in the commit log, with each committed batch 
and keyed by state operator ID like the state checkpoint IDs, the inputs that 
each stream-stream join's output watermark held back for in that batch, and in 
the first batch of a run re-simulate the previous batch with the recorded 
inputs instead of this run's traced ones. When the previous batch has no record 
because a version before this change ran it, hold each join back for exactly 
the inputs whose eviction predicate bounds their own event time or event-time 
equality key, which is what the older version's minimum covered in every shape 
the restart check accepts. Keep this run's traced inputs for the current 
batch's eviction pass, carry the record through offline state repartition, and 
add chained-join restart tests to the stream-stream join checkpoint 
compatibility tests.
   
   **Why this works:** With the recorded inputs, the re-simulated previous 
batch gives every operator the output and input watermarks that the previous 
run used, so the late-events watermark of an aggregation or deduplication above 
an outer join equals the eviction watermark it used in that batch, and the rows 
that the outer join emits padded with nulls from older state stay above it. The 
current batch then moves to this run's watermarks as any later batch does, and 
the next batch reads its late-events watermark from the cached simulation of 
this one.
   
   **Scope:** Persist each stream-stream join's output-watermark inputs per 
committed batch and use them to re-simulate the previous batch in the first 
batch of a run.
   
   **Compatibility:** Within a run, every batch's watermarks, this run's traced 
inputs for the current batch, the restart check and the first-batch V4 scan 
resets stay as they are at the PR head, and the pinned semantics version still 
only validates.
   
   **Risks:** The commit entry gains a field that every commit log format 
version and every commit writer, including offline state repartition, must 
carry; a commit that loses it makes the next run fall back to the older output 
watermark for that batch, which can give an operator a late-events watermark 
below the one the previous batch evicted with and let late rows into finalized 
results. A build without the field reads such a commit and ignores it, so 
rolling the change back brings back the first-batch drop without breaking 
restarts.
   
   **Constraints:** The record must describe the inputs that the batch's own 
eviction pass used, not the inputs that a first batch replayed for the batch 
before it. A missing record may be read as a batch run by an older version only 
when the checkpoint is pinned to the older join watermark semantics; with the 
current semantics every commit must carry it. No batch may evict or emit with 
the older output watermark; the fallback applies only to the re-simulated 
previous batch.
   
   **Exclusions:**
   - Removing the first-batch V4 scan from the start for a join with another 
join below it, which an exact re-simulation no longer needs for correctness and 
which only costs one full scan per run.
   - Relaxing restart-check rejections that an exact re-simulation would make 
unnecessary.
   
   **Success:** In the first batch after restoring a checkpoint written before 
this change, of chained stream-stream joins with an outer join above and an 
append-mode aggregation after it, the aggregation counts every row that the 
outer join emits padded with nulls from state the older version kept. After a 
plan change between runs that changes which input of the lower join reaches the 
outer join above it, the first batch drops none of the rows that the outer join 
emits from state the previous run kept. In the first batch of a run, each 
stateful operator's late-events watermark equals the eviction watermark it used 
in the previous batch.
   
   **Verification:**
   - **Regression:** Restoring a checkpoint written before this change of an 
inner join on B.t BETWEEN A.t AND A.t + INTERVAL 20 MINUTES projected to B's 
columns, followed by a left outer join with D on B.t within 5 minutes of D.t 
and an append-mode window count over B.t, emits for every window the count that 
the same input gives without a restart, including the first batch after the 
restart.
   - **Regression:** With a checkpoint written by this version, changing 
between runs which input's event time of the lower join reaches the outer join 
above it, followed by an append-mode aggregation, keeps in every window count 
the rows that the outer join emits padded with nulls from state the previous 
run kept.
   - **Compatibility:** A restart without any plan or version change gives 
every operator the same first-batch late-events watermark and output as at the 
PR head, and a commit written before this change is still read.
   - **Inspection:** Every code path that writes a commit entry for a stateful 
query, including offline state repartition, carries the recorded join inputs 
forward.



##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinSuite.scala:
##########
@@ -2425,6 +2529,342 @@ abstract class StreamingLeftSemiJoinBase extends 
StreamingJoinSuite {
     }
   }
 
+  // A left semi join processes the right input before the left input. A right 
row at or below
+  // its eviction cutoff passes late filtering when it is above the 
late-events watermark, and
+  // the left rows of the same batch must still find it. Each case runs a 
batch whose
+  // late-events watermark is 100 seconds and whose eviction watermark is 
`watermark` seconds.
+  // (name, condition, left time, right time, watermark, state rows after the 
second batch and
+  // after the third)
+  for ((name, condition, leftTime, rightTime, watermark, rowsBefore, 
rowsAfter) <- Seq(
+      ("equal event times", "leftTime = rightTime", 102, 102, 105, 2L, 0L),
+      // The left key leftTime + 10 seconds of (7, 100) stays above the 
100-second cutoff.
+      ("a key shifted by less than the watermark step",
+        "leftTime + INTERVAL 10 SECONDS = rightTime", 120, 130, 150, 3L, 1L),
+      // A value cutoff of the watermark less 10 seconds and 1 ms: (1, 130) is 
below 139.999 s.
+      ("a time interval",
+        "leftTime BETWEEN rightTime - INTERVAL 10 SECONDS AND rightTime + 
INTERVAL 10 SECONDS",
+        125, 130, 150, 4L, 2L))) {
+    test(s"left semi join keeps a same-batch match between the watermarks: 
$name") {
+      withSQLConf(SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> 
"false") {
+        val leftInput = MemoryStream[(Int, Int)]
+        val rightInput = MemoryStream[(Int, Int)]
+        val left = leftInput.toDF()
+          .select($"_1".as("leftKey"), timestamp_seconds($"_2").as("leftTime"))
+          .withWatermark("leftTime", "0 seconds")
+        val right = rightInput.toDF()
+          .select($"_1".as("rightKey"), 
timestamp_seconds($"_2").as("rightTime"))
+          .withWatermark("rightTime", "0 seconds")
+        val joined = left.join(right, expr(s"leftKey = rightKey AND 
$condition"), "left_semi")
+          .select($"leftKey", $"leftTime".cast("int"))
+
+        testStream(joined)(
+          MultiAddData(leftInput, (7, 100))(rightInput, (8, 100)),
+          CheckNewAnswer(),
+          MultiAddData(leftInput, (7, watermark))(rightInput, (8, watermark)),
+          CheckNewAnswer(),
+          assertNumStateRows(total = rowsBefore, updated = 4),
+          MultiAddData(leftInput, (1, leftTime))(rightInput, (1, rightTime)),
+          CheckNewAnswer((1, leftTime)),
+          // The right row is stored for the left row to probe and removed at 
the end of the
+          // batch, together with the other rows at or below the cutoffs.
+          assertNumStateRows(total = rowsAfter, updated = 1))
+      }
+    }
+  }
+
+  // The right cutoff comes from a bound on rightExpiry. The right row (1, 
110, 160) matches the
+  // left row (1, 120) of the same batch and is evicted at its end, whether 
the cutoff is applied
+  // to rightExpiry or to rightTime. Storing only the right rows above the 
cutoff at the
+  // late-events watermark would drop this match when the cutoff is applied to 
rightTime.
+  test("left semi join keeps a same-batch match bounded by another right 
column") {
+    withSQLConf(SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> 
"false") {
+      val leftInput = MemoryStream[(Int, Int, Int)]
+      val rightInput = MemoryStream[(Int, Int, Int)]
+      val left = leftInput.toDF()
+        .select($"_1".as("leftKey"), timestamp_seconds($"_2").as("leftTime"))
+        .withWatermark("leftTime", "0 seconds")
+      val right = rightInput.toDF()
+        .select($"_1".as("rightKey"), timestamp_seconds($"_2").as("rightTime"),
+          timestamp_seconds($"_3").as("rightExpiry"))
+        .withWatermark("rightTime", "0 seconds")
+      val joined = left.join(right, expr("leftKey = rightKey AND " +
+        "rightExpiry >= leftTime + INTERVAL 30 SECONDS AND " +
+        "leftTime >= rightTime - INTERVAL 1 HOUR"), "left_semi")
+        .select($"leftKey", $"leftTime".cast("int"))
+
+      testStream(joined)(
+        MultiAddData(leftInput, (7, 100, 0))(rightInput, (8, 100, 100)),
+        CheckNewAnswer(),
+        MultiAddData(leftInput, (7, 150, 0))(rightInput, (8, 150, 150)),
+        CheckNewAnswer(),
+        assertNumStateRows(total = 3, updated = 4),
+        // The late-events watermark is 100 seconds, and the right cutoff at 
it is 130 seconds
+        // less 1 ms: above the right row's rightTime of 110 seconds, below 
its rightExpiry.
+        MultiAddData(leftInput, (1, 120, 0))(rightInput, (1, 110, 160)),
+        CheckNewAnswer((1, 120)),
+        assertNumStateRows(total = 2, updated = 1))
+    }
+  }
+
+  // With equal watermarks, a left row that passes late filtering has a time 
above the watermark,
+  // so a right row that the right cutoff evicts in its arrival batch cannot 
match it. Here the
+  // right cutoff applies to rightExpiry, the column that the condition 
bounds, so the right row
+  // stays in state and matches the later left row. The same-batch decision to 
skip or store an
+  // evicted right row is covered by the default-mode test above and the tests 
of the exact
+  // cutoffs below.
+  test("left semi join applies the right cutoff to the bounded right column 
when both " +
+      "watermarks are equal") {
+    withSQLConf(SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> "false",
+        SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key -> "false") {
+      val leftInput = MemoryStream[(Int, Int, Int)]
+      val rightInput = MemoryStream[(Int, Int, Int)]
+      val left = leftInput.toDF()
+        .select($"_1".as("leftKey"), timestamp_seconds($"_2").as("leftTime"))
+        .withWatermark("leftTime", "0 seconds")
+      val right = rightInput.toDF()
+        .select($"_1".as("rightKey"), timestamp_seconds($"_2").as("rightTime"),
+          timestamp_seconds($"_3").as("rightExpiry"))
+        .withWatermark("rightTime", "0 seconds")
+      val joined = left.join(right, expr("leftKey = rightKey AND " +
+        "rightExpiry >= leftTime + INTERVAL 30 SECONDS AND " +
+        "leftTime >= rightTime - INTERVAL 1 HOUR"), "left_semi")
+        .select($"leftKey", $"leftTime".cast("int"))
+
+      testStream(joined)(
+        MultiAddData(leftInput, (7, 100, 0))(rightInput, (8, 100, 100)),
+        CheckNewAnswer(),
+        // Both watermarks are 100 seconds, and the right cutoff is 130 
seconds less 1 ms on
+        // rightExpiry. The right row has a rightExpiry of 1000 seconds, so it 
is not evicted in
+        // its batch and the left row of the same batch finds it.
+        MultiAddData(leftInput, (1, 120, 0))(rightInput, (1, 110, 1000)),
+        CheckNewAnswer((1, 120)))

Review Comment:
   **Nit (P3):** This expected answer is the same whichever right column the 
cutoff tests. `getLeftSemiExactRightCutoffs` gives no exact cutoff for this 
condition: it skips the `rightExpiry` conjunct, and `leftTime >= rightTime - 
INTERVAL 1 HOUR` gives no lower bound on `rightTime`, so the store clause keeps 
any right row the batch evicts for the batch's left rows. If the right cutoff, 
130 seconds less 1 ms, were applied to `rightTime` as on the base branch, the 
right row at 110 seconds would be evicted in its batch, kept by the store 
clause for the left row, matched and removed at the end of the batch, and 
`CheckNewAnswer((1, 120))` would still pass. Only the state differs: with the 
cutoff on `rightExpiry` it holds the right row `(1, 110, 1000)` and the left 
row `(7, 100)`, and with the cutoff on `rightTime` only that left row, because 
`(8, 100, 100)` and `(1, 110, 1000)` are both evicted. An `assertNumStateRows` 
after this batch would tell them apart.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60279#discussion_r4597569720).
   
   See **Shared repair plan 2** in the review body.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala:
##########
@@ -630,6 +663,170 @@ 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, through windows built from it, which end after it, through 
constant intervals
+     * with no negative part added to it, which never move it backward, and 
into the one input of
+     * a node with several inputs, such as a stream-static join, that outputs 
it. It stops at a
+     * stream-stream join, at another operator that writes state or sets an 
event time, and at
+     * any node or expression 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
+        }
+      }
+
+      // The column that `expression` shifts by constant intervals with no 
negative part. Such a
+      // shift never moves a time backward, in any time zone.
+      def forwardShiftSource(expression: Expression): Option[Attribute] = {
+        def nonNegative(interval: Expression): Boolean = interval.foldable &&
+          Try(Option(interval.eval())).toOption.flatten.exists { value =>
+            interval.dataType match {
+              case _: DayTimeIntervalType => value.asInstanceOf[Long] >= 0
+              case _: YearMonthIntervalType => value.asInstanceOf[Int] >= 0

Review Comment:
   **Nit (P3):** The suite covers negative day-time shifts (`impressionTime - 
INTERVAL 1 SECOND` and `impressionTime + INTERVAL -1 SECOND`) and a positive 
year-month shift (`INTERVAL '0-1' YEAR TO MONTH`), but no case subtracts a 
year-month interval, and no case adds a calendar interval of either sign, such 
as `impressionTime + CAST('1 day -25 hours' AS INTERVAL)`. If this arm accepted 
a negative year-month value, or the calendar-interval arm ignored the sign of 
the microseconds, the tracer would narrow the join's output watermark for a 
column that falls below the bounded event time, by an hour for `1 day -25 
hours`, and the operator after the join would drop joined rows as late while 
every test still passed.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60279#discussion_r4597569654).
   
   **Verification:**
   - **Regression:** Consumer columns that subtract a year-month interval from 
the bounded event time, or add a calendar interval with a negative day or time 
part, keep the join's output watermark held back for both inputs, so the tests 
fail if either arm accepted a negative value.
   - **Behavior:** A consumer column shifted by a calendar interval whose 
months, days and microseconds are all non-negative narrows the output watermark 
to the bounded input, as a positive day-time shift does.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala:
##########
@@ -630,6 +663,170 @@ 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, through windows built from it, which end after it, through 
constant intervals
+     * with no negative part added to it, which never move it backward, and 
into the one input of
+     * a node with several inputs, such as a stream-static join, that outputs 
it. It stops at a
+     * stream-stream join, at another operator that writes state or sets an 
event time, and at
+     * any node or expression 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
+        }
+      }
+
+      // The column that `expression` shifts by constant intervals with no 
negative part. Such a
+      // shift never moves a time backward, in any time zone.
+      def forwardShiftSource(expression: Expression): Option[Attribute] = {
+        def nonNegative(interval: Expression): Boolean = interval.foldable &&
+          Try(Option(interval.eval())).toOption.flatten.exists { value =>
+            interval.dataType match {
+              case _: DayTimeIntervalType => value.asInstanceOf[Long] >= 0
+              case _: YearMonthIntervalType => value.asInstanceOf[Int] >= 0
+              case CalendarIntervalType =>
+                val i = value.asInstanceOf[CalendarInterval]
+                i.months >= 0 && i.days >= 0 && i.microseconds >= 0
+              case _ => false
+            }
+          }
+        expression match {
+          case a: Attribute => Some(a)
+          // The analyzer wraps timestamp + interval in a cast to the same 
timestamp type.
+          case Cast(child, TimestampType, _, _) if child.dataType == 
TimestampType =>
+            forwardShiftSource(child)
+          case TimestampAddInterval(start, interval, _) if 
nonNegative(interval) =>
+            forwardShiftSource(start)
+          case TimestampAddYMInterval(start, interval, _) if 
nonNegative(interval) =>
+            forwardShiftSource(start)
+          case _ => None
+        }
+      }
+
+      // The column of the child that a computed column stays at or above.
+      def computedSource(column: Attribute, expression: Expression): 
Option[Attribute] =
+        windowSource(column, expression).orElse(forwardShiftSource(expression))
+
+      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 =>
+                computedSource(alias.toAttribute, alias.child).toSeq
+                  .flatMap(passThrough(p.child, _))
+              // Any other column, such as one that subtracts an interval, 
truncates or calls a
+              // UDF, can fall below the event time it reads, which could then 
arrive late.
+              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 =>
+                  computedSource(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 =>

Review Comment:
   **Blocking (P1):** `StreamingGlobalLimitExec` is a `StateStoreWriter`, so a 
trace from a stateful operator after a limit stops here, although the limit 
only passes on a prefix of its input rows, outputs its child's attributes and 
forwards its input watermark.
   
   For `impressions.join(clicks, expr("clickAdId = impressionAdId AND clickTime 
<= impressionTime + INTERVAL 10 
SECONDS")).limit(1000).groupBy(window($"impressionTime", "10 
seconds")).count()` in append mode, with watermarks on both event times, the 
join keeps `outputWatermarkSides` at `None`, the unbounded click input 
contributes 0, and the limit forwards the join's output watermark of 0, so by 
this review's reading of the code the window count never emits while its state 
grows. Without the limit, the same count traces to the impression input and 
emits its windows, as the suite's 'output watermark follows the bounded input 
when only its event time is used' case expects. On the base branch the join 
forwarded the impression cutoff through the limit, and the count emitted 
correct windows, since no impression time the join emits falls below that 
cutoff. An older checkpoint of this query is also rejected on restart, because 
the untraced join counts both inputs as read.
   
   See **Shared repair plan 1** in the review body.



##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinSuite.scala:
##########
@@ -2425,6 +2529,342 @@ abstract class StreamingLeftSemiJoinBase extends 
StreamingJoinSuite {
     }
   }
 
+  // A left semi join processes the right input before the left input. A right 
row at or below
+  // its eviction cutoff passes late filtering when it is above the 
late-events watermark, and
+  // the left rows of the same batch must still find it. Each case runs a 
batch whose
+  // late-events watermark is 100 seconds and whose eviction watermark is 
`watermark` seconds.
+  // (name, condition, left time, right time, watermark, state rows after the 
second batch and
+  // after the third)
+  for ((name, condition, leftTime, rightTime, watermark, rowsBefore, 
rowsAfter) <- Seq(
+      ("equal event times", "leftTime = rightTime", 102, 102, 105, 2L, 0L),
+      // The left key leftTime + 10 seconds of (7, 100) stays above the 
100-second cutoff.
+      ("a key shifted by less than the watermark step",
+        "leftTime + INTERVAL 10 SECONDS = rightTime", 120, 130, 150, 3L, 1L),
+      // A value cutoff of the watermark less 10 seconds and 1 ms: (1, 130) is 
below 139.999 s.
+      ("a time interval",
+        "leftTime BETWEEN rightTime - INTERVAL 10 SECONDS AND rightTime + 
INTERVAL 10 SECONDS",
+        125, 130, 150, 4L, 2L))) {
+    test(s"left semi join keeps a same-batch match between the watermarks: 
$name") {
+      withSQLConf(SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> 
"false") {
+        val leftInput = MemoryStream[(Int, Int)]
+        val rightInput = MemoryStream[(Int, Int)]
+        val left = leftInput.toDF()
+          .select($"_1".as("leftKey"), timestamp_seconds($"_2").as("leftTime"))
+          .withWatermark("leftTime", "0 seconds")
+        val right = rightInput.toDF()
+          .select($"_1".as("rightKey"), 
timestamp_seconds($"_2").as("rightTime"))
+          .withWatermark("rightTime", "0 seconds")
+        val joined = left.join(right, expr(s"leftKey = rightKey AND 
$condition"), "left_semi")
+          .select($"leftKey", $"leftTime".cast("int"))
+
+        testStream(joined)(
+          MultiAddData(leftInput, (7, 100))(rightInput, (8, 100)),
+          CheckNewAnswer(),
+          MultiAddData(leftInput, (7, watermark))(rightInput, (8, watermark)),
+          CheckNewAnswer(),
+          assertNumStateRows(total = rowsBefore, updated = 4),
+          MultiAddData(leftInput, (1, leftTime))(rightInput, (1, rightTime)),
+          CheckNewAnswer((1, leftTime)),
+          // The right row is stored for the left row to probe and removed at 
the end of the
+          // batch, together with the other rows at or below the cutoffs.
+          assertNumStateRows(total = rowsAfter, updated = 1))
+      }
+    }
+  }
+
+  // The right cutoff comes from a bound on rightExpiry. The right row (1, 
110, 160) matches the
+  // left row (1, 120) of the same batch and is evicted at its end, whether 
the cutoff is applied
+  // to rightExpiry or to rightTime. Storing only the right rows above the 
cutoff at the
+  // late-events watermark would drop this match when the cutoff is applied to 
rightTime.
+  test("left semi join keeps a same-batch match bounded by another right 
column") {
+    withSQLConf(SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> 
"false") {
+      val leftInput = MemoryStream[(Int, Int, Int)]
+      val rightInput = MemoryStream[(Int, Int, Int)]
+      val left = leftInput.toDF()
+        .select($"_1".as("leftKey"), timestamp_seconds($"_2").as("leftTime"))
+        .withWatermark("leftTime", "0 seconds")
+      val right = rightInput.toDF()
+        .select($"_1".as("rightKey"), timestamp_seconds($"_2").as("rightTime"),
+          timestamp_seconds($"_3").as("rightExpiry"))
+        .withWatermark("rightTime", "0 seconds")
+      val joined = left.join(right, expr("leftKey = rightKey AND " +
+        "rightExpiry >= leftTime + INTERVAL 30 SECONDS AND " +
+        "leftTime >= rightTime - INTERVAL 1 HOUR"), "left_semi")
+        .select($"leftKey", $"leftTime".cast("int"))
+
+      testStream(joined)(
+        MultiAddData(leftInput, (7, 100, 0))(rightInput, (8, 100, 100)),
+        CheckNewAnswer(),
+        MultiAddData(leftInput, (7, 150, 0))(rightInput, (8, 150, 150)),
+        CheckNewAnswer(),
+        assertNumStateRows(total = 3, updated = 4),
+        // The late-events watermark is 100 seconds, and the right cutoff at 
it is 130 seconds
+        // less 1 ms: above the right row's rightTime of 110 seconds, below 
its rightExpiry.
+        MultiAddData(leftInput, (1, 120, 0))(rightInput, (1, 110, 160)),
+        CheckNewAnswer((1, 120)),
+        assertNumStateRows(total = 2, updated = 1))
+    }
+  }
+
+  // With equal watermarks, a left row that passes late filtering has a time 
above the watermark,
+  // so a right row that the right cutoff evicts in its arrival batch cannot 
match it. Here the

Review Comment:
   **Nit (P3):** This premise holds only when the right cutoff is exact. The 
suite's test 'left semi join stores a right row that its batch evicts under a 
bound with a truncating cast when both watermarks are equal' has its batch 
evict the right row at 160.2 seconds and still expects the left row at 100.6 
seconds to match it, and the comment at the left semi store decision says the 
derived cutoff is not exact for whole days in daylight-saving zones or for 
truncating casts. As written, a maintainer could conclude that the store clause 
is unnecessary with a single global watermark; limiting the sentence to an 
exact cutoff keeps it consistent with that test.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60279#discussion_r4597569720).
   
   See **Shared repair plan 2** in the review body.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -134,6 +135,9 @@ import org.apache.spark.util.{CompletionIterator, 
SerializableConfiguration}
  *                                 [[JoinStateWatermarkPredicates]]
  * @param left      Left child plan
  * @param right     Right child plan
+ * @param outputWatermarkSides Inputs whose event time reaches the next 
stateful operator; the
+ *                             output watermark is held back only for their 
state. None when
+ *                             unknown, which holds it back for both inputs.

Review Comment:
   **Nit (P3):** For a left semi join, `produceOutputWatermark` ignores this 
field and always takes the minimum of the input watermark and the left state 
watermark, while `withJoinOutputWatermarkSides` still sets it on traced left 
semi joins. So for a left semi join, `None` does not hold the output watermark 
back for the right input, and `Some(Set(RightSide))` does not bring in the 
right state watermark, although this doc states both without an exception. A 
maintainer could rely on the field to hold back a left semi join's right input, 
or read the restart check's left semi exception as inconsistent with it; saying 
that a left semi join reads only its left state watermark, whatever the field 
holds, would match the code.
   
   **Verification:**
   - **Inspection:** The parameter documentation says that a left semi join 
uses only the input watermark and its left state watermark whatever the field 
holds, and still describes the field's effect for the other join types as the 
output watermark code applies it.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala:
##########
@@ -630,6 +661,134 @@ 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, through windows built from it, which end after it, and into 
the one input of
+     * a node with several inputs, such as a stream-static join, that outputs 
it. It stops at a
+     * stream-stream 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 =>

Review Comment:
   Thanks. Following constant intervals with no negative part covers the 
shifted column from this thread, and subtracted and negative intervals still 
hold the join back as they should. This review still raises the greatest() 
case. An inner join drops a row whose eviction column is NULL, so behind an 
inner join greatest() of the bounded input's event time and constants never 
falls below that event time, and holding the join back for both inputs there 
makes a downstream operator that progressed before this PR stop emitting. 
Following such a greatest() only into an inner join keeps the conservative 
fallback where it is needed: an outer join can emit that event time as NULL, 
for example on rows it pads with nulls, and greatest() then returns the 
constant, which the narrowed watermark could pass. timestampadd() with a 
non-negative constant amount never moves the event time backward either, and 
this review raises it together with greatest(). The compatibility tests that 
use greatest() as a
 n untraced column can use an identity UDF instead. This review also raises 
that the year-month and calendar-interval arms of the new sign check have no 
test with a negative value.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4597569654","thread_id":"inline:4597569654","verdict_sha256":"f15363ed53a1d4aa87e3a8d3ee16ba2073ac9cced88f8522bb67f09ae9ff727b"}
 -->



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