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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -186,6 +186,15 @@ object StreamingJoinHelper extends PredicateHelper with 
Logging {
       return None
     }
 
+    // The cutoff must rise with the watermark: `watermark + c < leftTime`. 
Without the watermark
+    // term, or with `-watermark`, later rightTime values can still match old 
leftTime values.
+    val watermarkTerms = terms.filter(_.references.exists { a =>
+      attributesWithEventWatermark.contains(a) && a.metadata.contains(delayKey)
+    })
+    if (watermarkTerms.size != 1 || 
watermarkTerms.head.isInstanceOf[UnaryMinus]) {

Review Comment:
   Thanks for reproducing it. With #60667 stacked, the reproduced case is fixed 
in the default mode, but the same eviction by a cutoff solved for another 
column remains in the legacy mode and for bounds through a TIMESTAMP_NTZ, DATE 
or numeric column in the default mode, where the new check still removes the 
cap. This review raises that as a finding.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4615301912","thread_id":"inline:4615301912","verdict_sha256":"d2c750a9a39a2060eb5d07a6ac67e88c770c8ebfbbab98be53ed3fa1f3bde45b"}
 -->



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -186,6 +209,16 @@ object StreamingJoinHelper extends PredicateHelper with 
Logging {
       return None
     }
 
+    // The cutoff must rise with the watermark: `watermark + c < leftTime`. 
Without the watermark
+    // term, the cutoff never rises and caps the other conjuncts' cutoffs. 
With `-watermark`, the
+    // cutoff falls, and later rightTime values can still match old leftTime 
values.
+    val watermarkTerms = terms.filter(_.references.exists { a =>
+      attributesWithEventWatermark.contains(a) && a.metadata.contains(delayKey)
+    })
+    if (watermarkTerms.size != 1 || 
watermarkTerms.head.isInstanceOf[UnaryMinus]) {

Review Comment:
   **Blocking (P1):** `collectTerms` passes a cast to a numeric type through as 
if it were exact (`StreamingJoinHelper.scala:288-290`). By the review's reading 
of the code, a left outer join with 1-second watermarks on `leftKey = rightKey 
AND CAST(lt AS LONG) >= CAST(rt AS LONG) - 5 AND CAST(lt AS LONG) > 10` gets a 
left cutoff of 34.499 s at a watermark of 39.5 s once this check drops the 
constant, so it evicts the left row (1, lt = 34.2 s) and emits it with nulls, 
although a right row (1, rt = 39.6 s) arriving in the next batch still matches 
it: 34 >= 39 - 5 after truncation. On the base branch the constant held the 
cutoff at 10 s and the match was emitted. The same happens with a negative-sign 
conjunct such as `CAST(lt AS LONG) + CAST(rt AS LONG) > 100` wherever its 
falling cutoff held the minimum. The follow-up planned for SPARK-61381 would 
fix this, but nothing keeps these joins correct until it lands.
   
   **Recommended change:** In getStateValueWatermark, when a conjunct that 
keeps a cutoff under the new rule passes a column through a cast that 
truncates, such as `CAST(lt AS LONG)`, take the minimum with the base branch's 
rule for that condition, so a constant-only or negative-sign conjunct keeps 
capping the inexact cutoff as on the base branch, and add a TODO there naming 
SPARK-61381. Conditions whose remaining bounds pass no column through such a 
cast keep the new rule. Add solver cases and join tests for both.
   
   **Why this works:** The base branch's minimum hid the inexact cutoff 
whenever a constant-only or negative-sign conjunct held it lower, so restoring 
that minimum only where a remaining bound is inexact returns exactly those 
joins to their base-branch eviction and output watermark, while every condition 
whose remaining bounds are exact keeps the new rule. Because every caller reads 
the same minimum, an input's eviction cutoff, state format 4 previous bound and 
output watermark stay on one rule.
   
   **Risks:** Joins whose remaining bound passes through a truncating cast keep 
the base branch's behavior, including a constant-only cap that withholds outer 
null rows and a negative-sign cutoff that can evict rows that still match, 
until SPARK-61381 lands. There is no flag; reverting the change brings back 
eviction by the inexact cutoff alone.
   
   **Constraints:** The analysis result does not change, because the base 
branch's rule gives a cutoff whenever the new rule does. Every caller reads the 
same minimum for a condition, so an input's eviction cutoff, state format 4 
previous bound and state watermark cannot diverge.
   
   **Exclusions:**
   - Fixing the inexact bound itself for joins without a constant-only or 
negative-sign conjunct (SPARK-61381), which the author defers.
   
   **Verification:**
   - **Regression:** On state formats 2 to 4, a left outer join bounded through 
`CAST(lt AS LONG) >= CAST(rt AS LONG) - 5` with a constant-only conjunct on lt, 
and the same join with a negative-sign conjunct in place of the constant, emit 
the match of a left row whose truncated time a later right row still satisfies 
instead of a null row.
   - **Behavior:** The solver returns the base branch's minimum for a condition 
with a truncating-cast bound beside a constant-only or negative-sign conjunct, 
and the new rule's minimum for a condition whose remaining bounds pass no 
column through such a cast, including `lt > rt - INTERVAL 5 SECONDS AND CAST(lt 
AS LONG) > 10`.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -186,6 +209,16 @@ object StreamingJoinHelper extends PredicateHelper with 
Logging {
       return None
     }
 
+    // The cutoff must rise with the watermark: `watermark + c < leftTime`. 
Without the watermark
+    // term, the cutoff never rises and caps the other conjuncts' cutoffs. 
With `-watermark`, the
+    // cutoff falls, and later rightTime values can still match old leftTime 
values.
+    val watermarkTerms = terms.filter(_.references.exists { a =>
+      attributesWithEventWatermark.contains(a) && a.metadata.contains(delayKey)
+    })
+    if (watermarkTerms.size != 1 || 
watermarkTerms.head.isInstanceOf[UnaryMinus]) {

Review Comment:
   **Blocking (P1):** Per-column selection only tries the event time and 
TIMESTAMP columns (`StreamingJoinHelper.scala:126-141`), so when the only 
rising bound is on another column type, the default mode falls back to the 
whole-input solve and pairs its result with the event time 
(`StreamingSymmetricHashJoinHelper.scala:264-283`); the legacy mode always 
takes that path. There the cutoff left after this check was solved for the 
other column. By the review's reading of the code, take a left outer join with 
1-second watermarks on `leftKey = rightKey AND CAST(lntz AS TIMESTAMP) > rt - 
INTERVAL 5 SECONDS AND CAST(lt AS LONG) > 10`, where lntz is a TIMESTAMP_NTZ 
copy of lt + 100 s. At a watermark of 39 s the left cutoff on lt is 34 s, so 
the left row (1, lt = 20 s) is evicted and emitted with nulls, and a later 
right row (1, rt = 50 s) no longer finds it although 120 s > 45 s. On the base 
branch the minimum is 10 s, the row stays, and the match is emitted. In the 
legacy mode the earlier ex
 ample with a TIMESTAMP column fails the same way, so the stacked migration 
entry's statement that the legacy mode keeps the earlier behavior does not hold 
for this rule.
   
   This extends existing discussions 
[1](https://github.com/apache/spark/pull/60664#issuecomment-6993123416), 
[2](https://github.com/apache/spark/pull/60664#discussion_r4615301912).
   
   **Recommended change:** On the whole-input path of 
getStateWatermarkPredicates (the legacy mode, and the default mode when 
per-column selection finds no column), keep the new rule only when it leaves no 
cutoff or the condition bounds the input's event time under it; otherwise solve 
that input's cutoff with the base branch's rule, which keeps constant-only and 
negative-sign conjuncts in the minimum, through an option of 
getStateValueWatermark that returns the base branch's minimum. Use the same 
choice for that input's state format 4 previous bound and for its state 
watermark in getStateWatermark, which has to mirror per-column selection so 
that only inputs on the whole-input path change. Say in the comment above the 
fallback in StreamingSymmetricHashJoinHelper.scala (lines 266-268) and in the 
migration-guide entry that such joins keep the earlier cutoff until their 
bounded column can evict by itself, and add solver cases for both rules and 
join tests in the legacy mode and on the d
 efault-mode fallback. The default-mode fallback came in 3aaff10de1a, which 
gives no reason in its message and replaced the analysis rejection that 
d0a9623720e had for outer and semi joins bounded only through such columns.
   
   **Why this works:** The base branch's minimum was what kept a cutoff solved 
for another column from evicting rows that later rows still match. Restoring it 
only where a cutoff is applied to the event time without bounding it returns 
those joins to their base-branch eviction, while every input whose cutoff is 
solved for the column it evicts by, or that has no cutoff left, keeps the new 
rule. The base branch's rule gives a cutoff whenever the new rule does, so a 
join that passes analysis still evicts.
   
   **Compatibility:** Inputs whose cutoff is solved for the column they are 
evicted by, or that have no cutoff left under the new rule, keep the new rule 
unless a remaining bound is inexact through a truncating cast, so the analysis 
result, per-column eviction and the state format 4 probe ranges otherwise stay 
as this PR defines them.
   
   **Risks:** Joins on the whole-input path whose remaining cutoffs were all 
solved for another column keep the base branch's eviction, including a 
constant-only cap that withholds outer null rows and a negative-sign cutoff 
that can evict rows that still match, until their bounded column can evict by 
itself. There is no flag; reverting the change brings back eviction by an 
uncapped cutoff solved for another column.
   
   **Constraints:** For each input, the eviction cutoff, the state format 4 
previous bound and the state watermark used for the output watermark take the 
same rule, or the bound or the output watermark can exceed what that input 
evicts. This repair uses the base branch's rule only on the whole-input path; 
the analysis check, per-column selection and the state format 4 probe range 
keep the new rule except where the truncating-cast and restart repairs apply 
the base branch's minimum.
   
   **Exclusions:**
   - Evicting inputs bounded only through TIMESTAMP_NTZ, DATE or numeric 
columns by those columns, which the stacked change defers.
   - Bounds through truncating casts (SPARK-61381) and the output watermark of 
inputs evicted by another TIMESTAMP column (SPARK-62001), which separate 
repairs cover.
   - State format 4 rows that the base-branch rule left in state before a 
restart (SPARK-62038).
   
   **Verification:**
   - **Regression:** On state formats 2 to 4 in the default mode, a left outer 
join bounded through a TIMESTAMP_NTZ or DATE column cast to TIMESTAMP, with a 
constant-only conjunct on the event time, keeps a left row that a later right 
row matches through that column and emits the match instead of a null row, and 
so does the same join with a negative-sign conjunct in place of the constant.
   - **Regression:** In the legacy mode, a left outer join whose rising bound 
is on a second TIMESTAMP column of the left input and that has a constant-only 
conjunct on the event time keeps the left row and emits the match.
   - **Behavior:** In the legacy mode, both examples in the PR description 
return the rows that the default mode returns.
   - **Behavior:** For an input that keeps the base branch's cutoff, the join's 
output watermark and the state format 4 previous bound do not exceed that 
cutoff.
   - **Compatibility:** For a join bounded only through another column with no 
constant-only or negative-sign conjunct, the eviction cutoff, the state format 
4 previous bound and the join's output watermark equal those before the change.
   - **Behavior:** On the whole-input path the solver gives a constant-only or 
negative-sign conjunct a cutoff only when that path asks for the base branch's 
minimum, and the analysis check still rejects new outer and semi joins whose 
only range condition has these forms.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -262,27 +262,44 @@ object StreamingSymmetricHashJoinHelper extends Logging {
             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)
+        val eventTime = 
oneSideInputAttributes.find(_.metadata.contains(delayKey))
+        // The legacy mode with a single global watermark keeps applying a 
cutoff on any column of
+        // this input to the event time. So does the default mode when the 
condition bounds no
+        // TIMESTAMP column, such as through a DATE column cast to TIMESTAMP 
only.
+        def solve(watermark: Option[Long]): Option[(Attribute, Long)] = {
+          def wholeInput = eventTime.flatMap { e =>
+            StreamingJoinHelper.getStateValueWatermark(
+              attributesToFindStateWatermarkFor = 
AttributeSet(oneSideInputAttributes),
+              attributesWithEventWatermark = 
AttributeSet(otherSideInputAttributes),
+              condition,
+              watermark).map(e -> _)
+          }
+          if (useFirstEventTimeColumn) {
+            wholeInput
+          } else {
+            
StreamingJoinHelper.getStateValueWatermarkColumn(oneSideInputAttributes,

Review Comment:
   **Blocking (P1):** This call makes the left input of a join on `rightTime 
BETWEEN leftTime AND expiry` evict by expiry, while `produceOutputWatermark` 
(`StreamingSymmetricHashJoinExec.scala:1170-1185`) still reports the cutoff 
that `getStateWatermark` solves for expiry 
(`StreamingSymmetricHashJoinHelper.scala:182-199`) as a bound on leftTime. By 
the review's reading of the code, add a count per 10-minute window of leftTime 
in append mode after a left outer join on that condition: an unmatched left row 
with leftTime 100 s and expiry 700 s is emitted with nulls only once the 
watermark passes 700 s, when the join's output watermark is about 700 s, so the 
aggregation, which filters late rows against it, drops the row after finalizing 
its window without it. On the base branch the row was evicted by leftTime and 
emitted at a watermark of about 100 s, and the aggregation counted it. With 
`AND CAST(leftTime AS LONG) > 10` added, the base branch held the output 
watermark at 10 s, and this 
 PR's rule moves the join to eviction by expiry, so a deduplication on leftTime 
after it now drops a joined row whose right row arrives at 650 s for leftTime 
100 s.
   
   **Recommended change:** For an input that getStateWatermarkPredicates evicts 
by a column other than its event time, cap that input's state watermark in 
produceOutputWatermark at the minimum event time of the rows its state kept 
after the previous batch's eviction, as reported by the join's state managers, 
so the output watermark never passes a row the join can still emit 
(SPARK-62001); inputs evicted by their event time keep the state watermark that 
getStateWatermark solves. Make getStateWatermark follow the same per-input 
column choice as getStateWatermarkPredicates, update the stacked 
migration-guide entry, and add tests with a stateful operator after such a join.
   
   **Why this works:** An input evicted by another column can hold rows of any 
event time below that column's cutoff, so no bound derived from the condition 
alone is safe for it. The minimum event time it actually keeps is a bound that 
holds by construction, and capping the state watermark at it keeps every later 
output of that input at or above the output watermark, while inputs evicted by 
their event time already report a bound on what they keep.
   
   **Risks:** Operators after such a join advance only as far as the oldest 
buffered row of the input evicted by another column, so a row with a far expiry 
delays their results. The cap lags the eviction by one batch, and a restart 
needs the value recorded with the state or recomputed before its first batch. 
State format 4 orders its index by the eviction column, so it needs a scan or a 
second index to find the minimum event time it keeps. There is no flag; 
reverting the change brings back output below the output watermark.
   
   **Constraints:** The cap applies only to inputs evicted by a column other 
than their event time, so joins that evict every input by its event time keep 
their output watermark. getStateWatermark and getStateWatermarkPredicates take 
the same per-input column choice, so the output watermark follows the eviction 
that runs.
   
   **Verification:**
   - **Regression:** On state formats 2 to 4, a left outer join bounded through 
`rightTime BETWEEN leftTime AND expiry` and followed by a window aggregation on 
leftTime in append mode counts the unmatched left rows that the join emits with 
nulls after their expiry passes.
   - **Regression:** With a constant-only conjunct on leftTime added, a 
deduplication on leftTime after the join keeps a joined row whose right row 
arrives after the watermark has passed its leftTime.
   - **Behavior:** After each batch, the join's output watermark is at or below 
the smallest leftTime still held by an input evicted by expiry, including 
across a restart.
   - **Compatibility:** Joins that evict every input by its event time, 
including both examples in the PR description, report the same output watermark 
as now on state formats 2 to 4.



##########
docs/streaming/ss-migration-guide.md:
##########
@@ -25,6 +25,29 @@ Please refer [Migration Guide: SQL, Datasets and 
DataFrame](../sql-migration-gui
 
 ## Upgrading from Structured Streaming 4.3 to 4.4
 
+- Since Spark 4.4, a stream-stream join whose condition bounds an input with 
its own watermark
+  only through another TIMESTAMP column, for example `rightTime BETWEEN 
leftTime AND expiry`,
+  evicts the state of that input by the bounded column instead of its event 
time. Earlier versions
+  could emit outer join rows too early and lose matches. Such a join can now 
emit rows below its
+  output watermark, which still assumes eviction by the event time, so a 
stateful operator after
+  it can drop them (SPARK-62001). With state format version 4, such a join 
cannot restart from a
+  checkpoint of an earlier version, or after a change of
+  `spark.sql.streaming.statefulOperator.allowMultiple`; start it with a new 
checkpoint. With
+  state format versions 1 to 3, it restarts, and rows that an earlier version 
evicted are not
+  restored. With `spark.sql.streaming.statefulOperator.allowMultiple` set to 
false, joins keep the
+  earlier behavior.
+
+- Since Spark 4.4, a range condition of a stream-stream join bounds the state 
of one input only
+  if it can be rearranged to `leftTime > rightTime + c` (or `>=`), where 
`rightTime` is the other
+  input's watermarked column, so that the cutoff rises with that watermark. 
For example,
+  `leftTime > rightTime - INTERVAL 5 SECONDS` bounds the state of the left 
input.
+  `CAST(leftTime AS LONG) > 10` no longer gives a cutoff, so it no longer 
holds back the cutoff of
+  other range conditions. `CAST(leftTime AS LONG) + CAST(rightTime AS LONG) > 
100` no longer
+  evicts state that later rows of the other input can still match. As a 
result, outer and semi
+  joins without a watermark in the join keys, whose only range condition has 
one of these forms,
+  fail analysis, also when an existing query restarts. To run such a query, 
add a range condition

Review Comment:
   **Blocking (P1):** By the review's reading of the code, a left semi join on 
`leftKey = rightKey AND CAST(lt AS LONG) > 10`, with watermarks on lt and rt 
and none in the join keys, runs on Spark 4.3: analysis accepts it on the 
constant's cutoff, the optimizer pushes the comparison below the join, and the 
join emits each matched left row once. Restarted from its checkpoint on this 
change, it fails with 'Stream-stream LeftSemi join between two streaming 
DataFrame/Datasets is not supported without a watermark in the join keys, or a 
watermark on the nullable side and an appropriate range condition', because the 
check runs during the initial analysis of every start, before the offset log's 
values are restored (`StreamingQueryManager.scala:287-328`). A left semi join 
whose only range condition is `CAST(lt AS LONG) + CAST(rt AS LONG) > 100`, with 
event times far above 100 s, fails the same way although it evicted nothing on 
the base branch. The reply to the earlier review kept this failur
 e because such joins could not produce correct results before, which holds for 
outer joins but not for these left semi joins.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60664#issuecomment-6993123416).
   
   **Recommended change:** Add an internal SQL conf, recorded in 
OffsetSeqMetadata with a legacy value for checkpoints that lack it, under which 
checkForStreamStreamJoinWatermark keeps accepting a stream-stream left semi 
join without a watermark in the join keys whose range conditions give a cutoff 
only under the base branch's rule, that is, constant-only or with a negative 
watermark term. Before analyzing an existing query with a persistent checkpoint 
that contains such a join, have StreamingQueryManager read the recorded value 
into the analysis session, as it does for a streaming EXCEPT. New queries 
record the new value and still fail, and outer joins fail under either value. 
Describe both cases in the migration-guide entry, and add analysis and restart 
tests.
   
   **Why this works:** The recorded value lets the check tell an existing query 
from a new one at the only point where it runs. Under the new rule such a left 
semi join gets no cutoff and evicts nothing, so the restarted query keeps 
emitting each matched left row once with correct results, while outer joins, 
which could not produce correct results, keep failing.
   
   **Risks:** Left semi joins accepted under the compatibility value evict 
nothing, so their state keeps growing as it did on the base branch. The start 
of an existing query with such a join reads its offset log once more before 
analysis.
   
   **Constraints:** The value is read before the initial analysis, because the 
offset log's values are restored into the session only after it. Joins accepted 
under the compatibility value build their cutoffs with the new rule, so their 
results stay correct.
   
   **Exclusions:**
   - Outer joins that the rule newly rejects, which could not produce correct 
results and keep failing.
   - New queries, which keep failing analysis.
   
   **Verification:**
   - **Regression:** A left semi join whose only range condition is 
constant-only, restarted from a checkpoint without the new offset-log entry, 
starts and returns the same rows as on the base branch, and so does one whose 
only range condition has a negative watermark term.
   - **Behavior:** New queries of those shapes, and left, right and full outer 
joins of those shapes restarted from such a checkpoint, fail analysis with the 
existing error.
   - **Compatibility:** A checkpoint that records the new value keeps rejecting 
such a left semi join after a restart.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -710,18 +740,30 @@ case class StreamingSymmetricHashJoinExec(
         Predicate.create(Literal(false), Seq.empty).eval _ // false = do not 
remove if no predicate
     }
 
+    private[this] var updatedStateRowsCount = 0
+    private[this] var numRemovedFromOtherSideDuringJoinCount = 0
+    private[this] val allowMultipleStatefulOperators: Boolean =
+      conf.getConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE)
+
+    // The join condition bounds the column that the value predicate tests, so 
a row with a NULL
+    // in it can never match, and `column <= cutoff` never holds for it. The 
legacy mode tests the
+    // event time even when the condition bounds another column.
+    private[this] val isEvictionColumnNull: UnsafeRow => Boolean = 
stateWatermarkPredicate match {

Review Comment:
   **Blocking (P1):** The comment above this rule assumes the condition bounds 
the predicate's column, but on the default-mode fallback the predicate is 
`eventTime <= cutoff` from the whole-input solve 
(`StreamingSymmetricHashJoinHelper.scala:277-283`), so the rule tests IsNull on 
an event time the condition may not reference. By the review's reading of the 
code, take an inner join with watermarks on lt and rt on `leftKey = rightKey 
AND CAST(d AS TIMESTAMP) >= rt - INTERVAL 1 DAY`, where d is a DATE column of 
the left input. A left row with a NULL lt and d = DATE '2026-11-18' passes late 
filtering, because the comparison with NULL is not true, and a later right row 
with rt = TIMESTAMP '2026-11-18 12:00:00' satisfies the condition with it. On 
the base branch the row is stored and the match is emitted; with this rule it 
is skipped (`StreamingSymmetricHashJoinExec.scala:892`) and the match is lost. 
A left outer join emits the row with nulls at once instead, and on state 
formats 1 to 3 s
 uch a row stored by an earlier version is evicted at the next batch 
(`StreamingSymmetricHashJoinExec.scala:761-762`).
   
   **Verification:**
   - **Regression:** In the default mode on state formats 2 to 4, an inner join 
and a left outer join bounded only through a DATE column cast to TIMESTAMP, fed 
a left row with a NULL event time and a later right row that matches it through 
that column, emit the joined row.
   - **Regression:** On state formats 2 and 3, a row with a NULL event time 
stored in the legacy mode for such a join still matches a right row after the 
query restarts in the default mode.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -262,27 +262,44 @@ object StreamingSymmetricHashJoinHelper extends Logging {
             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)
+        val eventTime = 
oneSideInputAttributes.find(_.metadata.contains(delayKey))
+        // The legacy mode with a single global watermark keeps applying a 
cutoff on any column of
+        // this input to the event time. So does the default mode when the 
condition bounds no
+        // TIMESTAMP column, such as through a DATE column cast to TIMESTAMP 
only.
+        def solve(watermark: Option[Long]): Option[(Attribute, Long)] = {
+          def wholeInput = eventTime.flatMap { e =>
+            StreamingJoinHelper.getStateValueWatermark(
+              attributesToFindStateWatermarkFor = 
AttributeSet(oneSideInputAttributes),
+              attributesWithEventWatermark = 
AttributeSet(otherSideInputAttributes),
+              condition,
+              watermark).map(e -> _)
+          }
+          if (useFirstEventTimeColumn) {
+            wholeInput
+          } else {
+            
StreamingJoinHelper.getStateValueWatermarkColumn(oneSideInputAttributes,
+              AttributeSet(otherSideInputAttributes), condition, 
watermark).orElse(wholeInput)
+          }
         }
-        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)
+        solve(eventTimeWatermarkForEviction).flatMap { case (column, 
stateValueWatermark) =>
+          // 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. Late-input filtering bounds only the 
event time, so a
+          // cutoff on another column always scans from the beginning. The 
bound is solved over
+          // the whole input, as earlier versions and the legacy mode evicted 
only up to it.

Review Comment:
   **Nit (P3):** `scanEvictedKeys` starts above this bound because its caller 
guarantees that everything at or below it was evicted 
(`SymmetricHashJoinStateManager.scala:187-196`). By the review's reading of the 
code, a state format 4 query restarted from a checkpoint that an earlier 
version wrote while a constant-only or negative-sign conjunct held the minimum 
gets a first bound above what that version evicted, so the rows between the two 
stay in state and an outer join never emits them with nulls, while formats 1 to 
3 evict them on the first batch. Naming that deferral here in a TODO for 
SPARK-62038, and saying that the bound assumes the previous batch evicted with 
the same rule, keeps the comment true.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60664#issuecomment-6993123416).
   
   **Verification:**
   - **Inspection:** The comment above the state format 4 previous bound names 
SPARK-62038, states that the bound assumes the previous batch evicted with the 
same rule, and no comment there still claims that earlier versions evicted only 
up to the bound.



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