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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -198,13 +477,80 @@ object StreamingJoinHelper extends PredicateHelper with 
Logging {
       }
     }.reduceLeft(Add(_, _))
 
+    // Callers can pass only the constrained column and the opposite event 
time, so a term on any
+    // other column passes the occurrence check above. Its value is unknown 
here.
+    if (exprWithWatermarkSubstituted.references.nonEmpty) {
+      logDebug(s"Failed to extract state constraint: unresolved 
$exprWithWatermarkSubstituted")
+      return None
+    }
+
     // Calculate the constraint value
     logInfo(log"Final expression to evaluate " +
       log"constraint:\t${MDC(WATERMARK_CONSTRAINT, 
exprWithWatermarkSubstituted)}")
     val constraintValue = 
exprWithWatermarkSubstituted.eval().asInstanceOf[java.lang.Double]
     Some((Double2double(constraintValue) / 1000.0).toLong)
   }
 
+  /** Whether a column of a join input can take a range cutoff: TIMESTAMP, or 
a time window. */
+  def canTakeRangeCutoff(column: Attribute): Boolean =
+    column.dataType == TimestampType || windowDuration(column).isDefined
+
+  /** The length of the windows in a column built by window(), when the column 
records it. */
+  private def windowDuration(column: Attribute): Option[Long] = {
+    val metadata = column.metadata
+    if (metadata.contains(TimeWindow.marker) && 
metadata.contains(TimeWindow.durationKey)) {
+      Some(metadata.getLong(TimeWindow.durationKey))

Review Comment:
   Thanks, verified at 11638546d59: a union now keeps the window length only 
when every child records the same one, in both the analyzed plan and UnionExec, 
so a union of different window lengths no longer passes its first child's 
length to the join. This review raises a related problem: the same rule also 
removes the cutoff for unions whose children all pass the length rule, which 
Spark 4.3.0 evicts correctly.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4537867101","thread_id":"inline:4537867101","verdict_sha256":"5272f42ece6e70e30948c5f9d16aad204bf060cf7eb62c0e9853c61b0353f5ec"}
 -->



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/TimeWindow.scala:
##########
@@ -187,6 +187,25 @@ case class TimeWindow(
 
 object TimeWindow {
   val marker = "spark.timeWindow"
+  // Window length in microseconds, recorded next to the marker. A 
stream-stream join compares
+  // it to decide whether an ordering of two window columns can evict state.
+  val durationKey = "spark.timeWindow.durationUs"
+
+  /**
+   * The metadata of a union's output column, given the children's columns at 
its position: the
+   * first child's, which a union keeps, but without the window length unless 
every child records
+   * the same one. Otherwise a join would read the first child's length for 
every child's rows.
+   */
+  def unionOutputMetadata(columns: Seq[Attribute]): Metadata = {
+    val first = columns.head.metadata
+    def sameDuration(metadata: Metadata): Boolean =
+      metadata.contains(durationKey) && metadata.getLong(durationKey) == 
first.getLong(durationKey)
+    if (first.contains(durationKey) && !columns.tail.forall(c => 
sameDuration(c.metadata))) {

Review Comment:
   **Blocking (P1):** This drops the window length whenever the children's 
lengths differ, which also removes the cutoff when every child's windows are 
safe on their own.
   
   By this review's reading of the code: take `lw = window(lt, "20 seconds")` 
on the left and a right input `c.union(d)` whose children select `window(ct, 
"10 seconds")` and `window(dt, "5 seconds")` over watermarked times, joined 
`left_outer` on `lk = rk AND lw > rw`. The base branch and Spark 4.3.0 admit 
this join and evict each 20-second left window by its end, which is safe: every 
later 5- or 10-second right window ends above the watermark, so it starts after 
every evicted 20-second window. Here `rw` records no length, so 
`isWindowEvictionSafe(lw, rw)` is false and the join fails analysis by default. 
As an inner join it keeps every left window for the life of the query and holds 
back its output watermark for the left input.
   
   Every union test in the PR includes a child that fails the rule, so none of 
them catches this. Dropping the length is what the previous review recommended, 
but each child's length is known, so the merged column can still carry a bound 
that holds for every child.
   
   This extends existing discussions 
[1](https://github.com/apache/spark/pull/60283#issuecomment-6816324299), 
[2](https://github.com/apache/spark/pull/60283#discussion_r4537867101).
   
   **Recommended change:** Record a window column's shortest and longest window 
length instead of a single length: window() resolution records its window 
length as both and window_time() removes both, the union merge keeps the 
smallest shortest and the largest longest of its children and records neither 
when any child records none, and the solver gives a whole-window comparison a 
cutoff when the stored column's shortest window lasts at least as long as the 
other column's longest. This replaces the union rule the PR states, which keeps 
a length only when every child records the same one. 6ffda93fc12 added the 
recorded length, which a union then took from its first child, and 11638546d59 
replaced that by dropping the length whenever the children differ, so that such 
a union gives no cutoff for a whole-window comparison. Start from 6ffda93fc12's 
recording where window() is resolved and from the union helper that 11638546d59 
added, which already serves the logical and the physical union.
  Add window function tests for the lengths a union records, and stream-stream 
join tests over unions whose children all pass the length rule, on either input.
   
   **Why this works:** A union's rows are its children's rows, so the smallest 
shortest and the largest longest child length bound the window length of every 
row in the merged column. Comparing the stored column's shortest with the other 
column's longest applies the length rule to every pair of windows the two 
columns can hold: it holds for a union only when every child would pass, and it 
fails whenever any child could fail or a child records no length. For a single 
window() column both lengths are equal, so its rule is unchanged.
   
   **Scope:** Replace the single recorded window length with a shortest and a 
longest length, which window() resolution writes, the union merge combines and 
the join's cutoff solver compares.
   
   **Compatibility:** A single window() column, a union of equal windows, and a 
union with a child that records no length give the same cutoffs as now in the 
analysis check and in eviction, and the merged column keeps every other 
metadata key of its first child.
   
   **Risks:** Every window column's schema shows the shortest and longest 
lengths instead of the current single length, in Dataset schemas and in sink 
and state schemas that keep field metadata; the state schema check ignores 
field metadata, so restarts proceed, and tests that read the current key change 
with it. Unions whose children all pass the length rule take a cutoff again, so 
an inner join over them evicts again and an outer join outputs their unmatched 
windows; reverting the merge and comparison changes restores the current 
behavior.
   
   **Constraints:** Keep every other metadata key of the first child's column, 
including the window marker and the watermark delay key. Give no cutoff when 
either compared column records no length, as for session windows and window 
columns of tables that earlier versions created. Keep the V4 range-scan offsets 
limited to TIMESTAMP event-time columns.
   
   **Exclusions:**
   - A cutoff lowered by the difference of the window lengths for stored 
windows shorter than the other input's, which the PR defers to SPARK-61510.
   - Lengths that a column takes from a stored or supplied schema, which the 
fix that keeps recorded lengths query-local removes.
   
   **Success:** With 20-second left windows and a right input that is a union 
of 10-second and 5-second windows, a left outer join bounded only by lw > rw 
passes analysis and outputs each unmatched left window once the watermark 
passes its end, and the inner join evicts those windows. A union whose children 
record different lengths records the smallest shortest and the largest longest 
of them, in the analyzed plan and in the physical union, and a union with a 
child that records no length records none. A union with a child whose windows 
are shorter than the other input's longest, or, on the watermarked side, longer 
than the stored windows' shortest, still gives no cutoff.
   
   **Verification:**
   - **Regression:** A stream-stream left outer join whose only left bound is 
lw > rw, with 20-second left windows and a right union of 10-second and 
5-second windows over watermarked times, passes analysis and outputs each 
unmatched left window once the watermark passes its end, and the inner join 
with the same bound removes those windows from state, in every supported state 
format.
   - **Behavior:** A stored-side union of 20-second and 30-second windows 
against 10-second windows takes a cutoff, while a union with a child shorter 
than the other input's windows, or a watermarked-side union with a child longer 
than the stored windows, still fails analysis as an outer join and, as an inner 
join, still outputs the match that eviction would lose.
   - **Compatibility:** A single window() column, a union of equal windows and 
a union with a child that records no length give the same admission and 
eviction results as before the change, and the merged column keeps its first 
child's other metadata in both the logical and the physical union.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -66,13 +752,27 @@ 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 check that the 
bounded column is a
+   *                                      TIMESTAMP column or a time window, 
which Spark 4.4
+   *                                      added to the solver. It does not 
skip the inexact
+   *                                      arithmetic check for columns without 
their own
+   *                                      watermark, which 
exactForUnwatermarkedColumns alone
+   *                                      controls; leave that false too for 
the result of
+   *                                      earlier versions. Only the admission 
rule that stays
+   *                                      in force with the finalization check 
disabled sets it.

Review Comment:
   **Nit (P3):** The restart compatibility check's older-version solve also 
passes `baseAdmissionRules = true` (`givesNoBound` in 
`StreamingSymmetricHashJoinHelper.isOwnEventTimeIntervalJoin`), so this caller 
list is incomplete, and changing what the flag skips would also change which 
older checkpoints restart.
   
   ```suggestion
      *                                      earlier versions. Two callers set 
it: the admission rule
      *                                      that stays in force with the 
finalization check
      *                                      disabled, and the restart 
compatibility check's solve
      *                                      of the bound that older versions 
derived.
   ```
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60283#discussion_r4537867122).
   
   **Verification:**
   - **Inspection:** Every call that sets baseAdmissionRules is one that the 
flag's documentation names, and the documentation names no caller that does not 
set it.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -198,13 +932,80 @@ object StreamingJoinHelper extends PredicateHelper with 
Logging {
       }
     }.reduceLeft(Add(_, _))
 
+    // Callers can pass only the constrained column and the opposite event 
time, so a term on any
+    // other column passes the occurrence check above. Its value is unknown 
here.
+    if (exprWithWatermarkSubstituted.references.nonEmpty) {
+      logDebug(s"Failed to extract state constraint: unresolved 
$exprWithWatermarkSubstituted")
+      return None
+    }
+
     // Calculate the constraint value
     logInfo(log"Final expression to evaluate " +
       log"constraint:\t${MDC(WATERMARK_CONSTRAINT, 
exprWithWatermarkSubstituted)}")
     val constraintValue = 
exprWithWatermarkSubstituted.eval().asInstanceOf[java.lang.Double]
     Some((Double2double(constraintValue) / 1000.0).toLong)
   }
 
+  /** Whether a column of a join input can take a range cutoff: TIMESTAMP, or 
a time window. */
+  def canTakeRangeCutoff(column: Attribute): Boolean =
+    column.dataType == TimestampType || windowDuration(column).isDefined
+
+  /** The length of the windows in a column built by window(), when the column 
records it. */
+  private def windowDuration(column: Attribute): Option[Long] = {
+    val metadata = column.metadata
+    if (metadata.contains(TimeWindow.marker) && 
metadata.contains(TimeWindow.durationKey)) {

Review Comment:
   **Blocking (P1):** This treats the recorded length as true of every row in 
the column, but the key is ordinary field metadata that outlives the query that 
set it.
   
   By this review's reading of the code: create a parquet table with 
`saveAsTable` from a batch `groupBy($"lk", window($"ts", "20 
seconds")).count()`, then append a batch `groupBy($"lk", window($"ts", "10 
seconds")).count()`. Table creation stores the window column's metadata, the 
append keeps that schema, and `spark.readStream.table` builds the stream's 
columns and each micro-batch from it, so the column records 20 seconds for 
every row. Inner-join that stream, which has no watermark, on `lk = rk AND lw > 
rw` with a stream whose `rw = window($"t", "15 seconds", "1 second")` over a 
watermarked `t`. `isWindowEvictionSafe` passes 20 seconds against 15, and value 
eviction now tries window columns on an input without a watermark, so the 
stored 10-second window [90 s, 100 s) is evicted once the watermark reaches 100 
s. The later right window [86 s, 101 s) is not late and orders below it, so 
that match is lost. The base branch never value-evicts an input without a 
watermarked column and ou
 tputs the match. A schema copied from a window DataFrame into 
`readStream.schema(...)` reaches the same code.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60283#discussion_r4523339214).
   
   **Recommended change:** Keep a recorded window length query-local. Remove 
the length in the shared conversion that builds a relation's columns from a 
schema, and where view resolution and Dataset.to apply a stored or supplied 
schema's metadata, keep the column's own recorded length rather than the 
schema's. Only window() resolution in the running query, and union merges of 
its columns, then give a column a length, so a window column read from a table, 
from files or under a supplied schema is treated like a window of unknown 
length. No commit in this PR limits where a trusted length may come from; 
6ffda93fc12 added the length and the solver's use of it. Add stream-stream join 
tests over window columns read from a table and under a supplied schema, and 
window function tests for the lengths such columns record.
   
   **Why this works:** A trusted length must describe every row of its column, 
and only window() resolution in the running query guarantees that. Removing the 
length wherever a relation's columns are built from a schema, and wherever a 
stored or supplied schema's metadata would replace a column's own, leaves it 
only on columns whose windows the running query builds. The solver then finds 
no length on any other column and gives a whole-window comparison against it no 
cutoff, and runtime eviction, which takes its cutoffs from the same solver, 
keeps that input's rows.
   
   **Scope:** Remove recorded window lengths where columns are built from, or 
take their metadata from, a stored or supplied schema.
   
   **Compatibility:** Joins over window() columns built in the running query, 
including through unions and views, keep the cutoffs they get now, and 
window_time() keeps working on window columns read from tables.
   
   **Risks:** A stream-stream join whose stored side compares a window column 
read from a table, from files or under a supplied schema with the other input's 
windows gets no cutoff, even when every stored window happens to be long 
enough: an outer or left semi join bounded only that way fails analysis by 
default and an inner join keeps that input's state, as already happens for 
window columns of tables that earlier versions created; reverting the 
conversion change restores the current trust. Dataset schemas of relations 
built from such schemas no longer show the length, although the stored schema 
still records it.
   
   **Constraints:** Keep the window marker and every other metadata key on 
columns built from a schema, so window_time() and other readers of stored 
window columns keep working. Keep the lengths that window() resolution records 
in the running query, and union merges of them, on every path to the join, 
including each micro-batch's re-aliasing of its source. Remove exactly the 
length keys that the window-length representation defines, including the 
shortest and longest lengths that the union fix records.
   
   **Exclusions:**
   - Metadata that a user attaches to a column by hand, through Column.as with 
metadata or Dataset.withMetadata, which the repair takes as given, as it does 
for the window marker and the watermark delay key.
   - Removing the length from the schemas that table creation and connector 
writes store; once relations remove it on read, a stored length has no effect.
   
   **Success:** A parquet table created from 20-second windows and appended 
with 10-second windows, read with readStream.table and inner-joined on lk = rk 
AND lw > rw with 15-second right windows sliding by 1 second, keeps the 
10-second window [90 s, 100 s) after the eviction watermark passes 100 s and 
outputs its match with the right window [86 s, 101 s). A window column read 
from a table, from files or under a schema given to readStream.schema or 
createDataFrame records no length but keeps the window marker. A window() 
column built in the running query keeps its recorded lengths and its cutoff 
through projections, unions, views and each micro-batch's re-aliasing of its 
source.
   
   **Verification:**
   - **Regression:** An inner stream-stream join on lk = rk AND lw > rw, whose 
left input streams a table created from 20-second windows and appended with 
10-second windows and whose right input has 15-second windows sliding by 1 
second, still outputs the match of the 10-second window [90 s, 100 s) with the 
right window [86 s, 101 s) after the eviction watermark passes 100 s, and the 
left outer join with that bound fails analysis by default.
   - **Behavior:** A stream read under a schema copied from a window DataFrame 
gives a whole-window comparison no cutoff, and Dataset.to with such a schema, 
like a view whose stored schema records a different length, keeps the column's 
own recorded length rather than the schema's.
   - **Compatibility:** Window columns built by window() in the running query 
keep their recorded lengths and cutoffs through projections, unions, views and 
a file source's micro-batches, and window_time() still works on a window column 
read from a table.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -198,13 +932,80 @@ object StreamingJoinHelper extends PredicateHelper with 
Logging {
       }
     }.reduceLeft(Add(_, _))
 
+    // Callers can pass only the constrained column and the opposite event 
time, so a term on any
+    // other column passes the occurrence check above. Its value is unknown 
here.
+    if (exprWithWatermarkSubstituted.references.nonEmpty) {
+      logDebug(s"Failed to extract state constraint: unresolved 
$exprWithWatermarkSubstituted")
+      return None
+    }
+
     // Calculate the constraint value
     logInfo(log"Final expression to evaluate " +
       log"constraint:\t${MDC(WATERMARK_CONSTRAINT, 
exprWithWatermarkSubstituted)}")
     val constraintValue = 
exprWithWatermarkSubstituted.eval().asInstanceOf[java.lang.Double]
     Some((Double2double(constraintValue) / 1000.0).toLong)
   }
 
+  /** Whether a column of a join input can take a range cutoff: TIMESTAMP, or 
a time window. */
+  def canTakeRangeCutoff(column: Attribute): Boolean =
+    column.dataType == TimestampType || windowDuration(column).isDefined
+
+  /** The length of the windows in a column built by window(), when the column 
records it. */
+  private def windowDuration(column: Attribute): Option[Long] = {
+    val metadata = column.metadata
+    if (metadata.contains(TimeWindow.marker) && 
metadata.contains(TimeWindow.durationKey)) {
+      Some(metadata.getLong(TimeWindow.durationKey))
+    } else {
+      None
+    }
+  }
+
+  /**
+   * Whether evicting `stateWindow` by its end is safe when a range condition 
compares it, as a
+   * whole, with `watermarkWindow`, the other input's watermarked time window. 
Ordering windows
+   * compares their starts first. A window evicted at a cutoff no higher than 
the watermark
+   * starts at least its own duration before the watermark, while a later 
window of the other
+   * input ends above the watermark, so it starts less than its own duration 
before it. When the
+   * stored windows last at least as long as the other input's, every later 
window therefore
+   * starts after every evicted window and orders above it. Shorter stored 
windows get no cutoff.

Review Comment:
   **Nit (P3):** The lowered cutoff for shorter stored windows is deferred to 
SPARK-61510 only in the PR description and a reply, so a reader of this rule 
sees the missing cutoff as final rather than as a tracked trade-off; the stack 
marks its other deferrals with TODOs.
   
   ```suggestion
      * starts after every evicted window and orders above it. Shorter stored 
windows get no cutoff.
      * TODO(SPARK-61510): give shorter stored windows a cutoff lowered by the 
difference of the two
      *   window lengths. Until then an inner join keeps their state, and an 
outer or left semi join
      *   bounded only that way fails analysis.
   ```
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60283#issuecomment-6816324299).
   
   **Verification:**
   - **Inspection:** The window-length rule's documentation names SPARK-61510 
in a TODO that states the planned cutoff, lowered by the difference of the two 
window lengths, and what such windows do until then, and it matches how the 
rule compares window lengths after any change to how they are recorded.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -224,98 +238,392 @@ 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, eventTimeLags)
       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, 
eventTimeLags)
+        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.
+        getStateValueWatermarkForInput(oneSideInputAttributes, 
otherSideInputAttributes, condition,
+          eventTimeWatermarkForEviction, eventTimeLags).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.getStateValueWatermarkForLags(AttributeSet(Seq(attribute)),
+              otherSideInputAttributes, condition, Some(lateWatermark), 
eventTimeLags)
+              .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],
+      eventTimeLags: Option[EventTimeLags]): Option[(Attribute, Long)] = {
+    // TODO(SPARK-61508): an inner or left semi join side that is bounded only 
through a column
+    //   that is not TIMESTAMP, cast to TIMESTAMP, has no eviction predicate, 
so it keeps its rows
+    //   for the life of the query until eviction through the cast is 
supported. Projecting the
+    //   column to TIMESTAMP before the join bounds that state.
+    // 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))
+    // 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) &&
+        !eventTime.exists(_.semanticEquals(attribute))
+    }
+    candidates.iterator.flatMap { attribute =>
+      
StreamingJoinHelper.getStateValueWatermarkForLags(AttributeSet(Seq(attribute)),
+        otherInputAttributes, condition, eventWatermark, eventTimeLags,
+        exactForUnwatermarkedColumns = true).map(attribute -> _)
+    }.take(1).toSeq.headOption
+  }
+
+  /**
+   * Get the equality-key ordinal at which a V4 state manager stores and looks 
up a side's rows.
+   * A side evicted by key uses the key that the opposite input's watermark 
bounds. Any other side
+   * stores each row at its own event time, unless it is evicted on another 
column. When that
+   * event time is an equality key, its ordinal gives the same stored 
timestamps and lets a lookup
+   * read one timestamp instead of scanning every timestamp of the key.
+   */
+  def getStateKeyOrdinalForLookup(
+      oneSideAttributes: Seq[Attribute],
+      oneSideKeys: Seq[Expression],
+      otherSideAttributes: Seq[Attribute],
+      otherSideKeys: Seq[Expression],
+      predicate: Option[JoinStateWatermarkPredicate]): Option[Int] = {
+    def storesRowsAtKey(ordinal: Int): Boolean = predicate match {
+      case Some(p: JoinStateValueWatermarkPredicate) =>
+        p.expr.references.forall(_.semanticEquals(oneSideKeys(ordinal)))
+      case _ => true
+    }
+    StreamingJoinHelper.getStateKeyWatermarkOrdinal(otherSideKeys, 
otherSideAttributes).orElse(
+      StreamingJoinHelper.getEventTimeKeyOrdinal(oneSideKeys, 
oneSideAttributes)
+        .filter(storesRowsAtKey))
+  }
+
+  /**
+   * Conservatively prove that older state can use the current watermark 
semantics. Without
+   * watermarks there is no affected state. An input that neither version 
evicts keeps the same
+   * rows, but its state watermark in the join's output watermark changed, so 
such an input is
+   * accepted only when no stateful operator after the join reads it: 
`consumedSides` names the
+   * inputs whose state watermark reaches a later operator through the join's 
output watermark,
+   * both when that operator cannot be traced, and none when no stateful 
operator follows, with a
+   * single global watermark, or for the right input of a left semi join. A 
key-only join, with
+   * no other condition and no equality key that uses an event time, is 
evicted by neither
+   * version, and V4 reads its rows by key prefix. Otherwise each side must 
have exactly one
+   * event-time column, and either its own event time must be the sole 
watermarked equality key
+   * at the same ordinal, or the join must be a time-interval join on the 
event times (see
+   * [[isOwnEventTimeIntervalJoin]]). This excludes other range bounds. A key 
computed from the
+   * event time by a constant is accepted only when it shifts the event time 
forward, the other
+   * input's key at that ordinal is its own event time, no other equality key 
uses an event time,
+   * and no stateful operator after the join reads the shifted input's event 
time. Older versions
+   * evicted both sides at the unshifted watermark at that ordinal. For a 
forward shift, that is
+   * the cutoff this version uses for the shifted side, and at or below the 
one it uses for the
+   * other side, which can no longer match rows at or below it, and both 
versions store V4 rows
+   * at that ordinal. Only the shifted input's bound in the output watermark 
changes. Older
+   * versions evicted a backward shift before its last match. A NULL selected 
key does not change
+   * the semantics: such a row can never match.
+   * Old V4 state indexed it at timestamp 0 under its own key, and the first 
batch after the
+   * restart scans V4 state from the start, so it evicts the row and a 
preserved side emits it
+   * unless an older version already joined it. V1 to V3 test every stored row 
each batch and
+   * also evict such a row.
+   */
+  private[sql] def isWatermarkCheckpointCompatible(
+      leftAttributes: Seq[Attribute],
+      rightAttributes: Seq[Attribute],
       leftKeys: Seq[Expression],
-      rightKeys: Seq[Expression]): Option[Int] = {
-    // Join keys of both sides generate rows of the same fields, that is, same 
sequence of data
-    // types. If one side (say left side) has a column (say timestamp) that 
has a watermark on it,
-    // then it will never consider joining keys that are < state key watermark 
(i.e. event time
-    // watermark). On the other side (i.e. right side), even if there is no 
watermark defined,
-    // there has to be an equivalent column (i.e., timestamp). And any right 
side data that has the
-    // timestamp < watermark will not match will not match with left side 
data, as the left side get
-    // filtered with the explicitly defined watermark. So, the watermark in 
timestamp column in
-    // left side keys effectively causes the timestamp on the right side to 
have a watermark.
-    // We will use the ordinal of the left timestamp in the left keys to find 
the corresponding
-    // right timestamp in the right keys.
-    leftKeys.zipWithIndex.collectFirst {
-      case (ne: NamedExpression, index) if ne.metadata.contains(delayKey) => 
index
-    } orElse {
-      rightKeys.zipWithIndex.collectFirst {
-        case (ne: NamedExpression, index) if ne.metadata.contains(delayKey) => 
index
+      rightKeys: Seq[Expression],
+      condition: Option[Expression],
+      consumedSides: Set[JoinSide]): Boolean = {
+    val leftEventTime = leftAttributes.filter(_.metadata.contains(delayKey))
+    val rightEventTime = rightAttributes.filter(_.metadata.contains(delayKey))
+    val keyOnly = condition.isEmpty && !(leftKeys ++ rightKeys).exists { key =>
+      key.references.exists(_.metadata.contains(delayKey)) || (key match {
+        case named: NamedExpression => named.metadata.contains(delayKey)
+        case _ => false
+      })
+    }
+
+    def watermarkKeyOrdinals(keys: Seq[Expression]): Seq[Int] = {
+      keys.zipWithIndex.collect {
+        case (key: NamedExpression, index) if key.metadata.contains(delayKey) 
=> index
       }
     }
+
+    val leftOrdinals = watermarkKeyOrdinals(leftKeys)
+    val rightOrdinals = watermarkKeyOrdinals(rightKeys)
+    if (leftEventTime.isEmpty && rightEventTime.isEmpty) {
+      leftOrdinals.isEmpty && rightOrdinals.isEmpty
+    } else if (keyOnly && consumedSides.isEmpty) {
+      true
+    } else if (leftEventTime.size == 1 && rightEventTime.size == 1) {
+      val leftOrdinal = StreamingJoinHelper.getEventTimeKeyOrdinal(leftKeys, 
leftAttributes)
+      val rightOrdinal = StreamingJoinHelper.getEventTimeKeyOrdinal(rightKeys, 
rightAttributes)
+      val alignedOwnEventTimeKeys = leftOrdinal.isDefined && leftOrdinal == 
rightOrdinal &&
+        leftOrdinals == leftOrdinal.toSeq && rightOrdinals == 
rightOrdinal.toSeq
+      // One input's own event-time key paired with a forward shift of the 
other input's.
+      def forwardShiftedKey(
+          ownOrdinal: Option[Int],
+          ownWatermarkOrdinals: Seq[Int],
+          shiftedKeys: Seq[Expression],
+          shiftedAttributes: Seq[Attribute],
+          shiftedWatermarkOrdinals: Seq[Int],
+          shiftedSide: JoinSide): Boolean = ownOrdinal.exists { ordinal =>
+        ownWatermarkOrdinals == Seq(ordinal) && 
shiftedWatermarkOrdinals.isEmpty &&
+          StreamingJoinHelper.isForwardShiftOfEventTime(shiftedKeys(ordinal), 
shiftedAttributes) &&
+          leftKeys.indices.filter(_ != ordinal).forall { i =>
+            !(leftKeys(i).references ++ rightKeys(i).references)
+              .exists(_.metadata.contains(delayKey))
+          } && !consumedSides(shiftedSide)
+      }
+      alignedOwnEventTimeKeys ||
+        forwardShiftedKey(leftOrdinal, leftOrdinals, rightKeys, 
rightAttributes, rightOrdinals,
+          RightSide) ||
+        forwardShiftedKey(rightOrdinal, rightOrdinals, leftKeys, 
leftAttributes, leftOrdinals,
+          LeftSide) ||
+        isOwnEventTimeIntervalJoin(leftAttributes, rightAttributes, leftKeys, 
rightKeys,
+          condition, leftEventTime.head, rightEventTime.head, consumedSides)
+    } else {
+      false
+    }
+  }
+
+  /**
+   * Whether every ordering conjunct compares the two inputs' TIMESTAMP event 
times, each only cast
+   * or offset by constants (see [[StreamingJoinHelper.isConstantOffsetOf]]), 
or gives no bound to
+   * either input in either version, and each event time either gets a range 
bound or gets none and
+   * is not in `consumedSides`. Each half of a BETWEEN counts as one conjunct, 
as the solver reads
+   * it. Older versions and this one solve such conjuncts the same way for 
columns with their own
+   * watermark, and older versions solved every column of an input but then 
found bounds only in the
+   * same conjuncts, so they derived the same value predicates, scan starts 
and V4 index columns,
+   * and neither evicts an input that gets no bound. Old V4 stored a null 
event time at timestamp 0
+   * under the row's own key; both versions scan that entry the same way. No 
equality key may use an
+   * event time: older versions evicted both sides of such a key at the 
unshifted watermark, which
+   * [[isWatermarkCheckpointCompatible]] accepts only for a forward shift 
whose shifted input no
+   * later stateful operator reads. Time windows are excluded: this version 
still derives the older

Review Comment:
   **Nit (P3):** This PR is SPARK-61348, and at this head the older ordering 
bound is derived only for stored windows that last at least as long as the 
other input's; shorter windows and windows without a recorded length get none. 
This comment, and the matching one on the time-window case in 
`StreamingJoinCheckpointCompatibilitySuite`, still describe that removal as a 
later change, so neither says why the check also rejects older checkpoints of 
windows that keep the older bound. What the corrected text should say depends 
on the restart-check question under Decision challenges.
   
   **Verification:**
   - **Inspection:** The restart check's documentation and the comment on its 
time-window compatibility case describe the rule the check applies to time 
windows at this head and why, consistent with the cutoff solver's window-length 
rule, and refer to no later change that this one already made.



##########
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:
   Thanks, verified at 11638546d59: the doc now names the one check the flag 
skips and says that the inexact-arithmetic rule stays under 
exactForUnwatermarkedColumns. This review raises a related problem in the same 
doc: it says that only the admission rule used with the finalization check 
disabled sets the flag, but the restart compatibility check also sets it.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4537867122","thread_id":"inline:4537867122","verdict_sha256":"5272f42ece6e70e30948c5f9d16aad204bf060cf7eb62c0e9853c61b0353f5ec"}
 -->



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