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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -66,13 +66,17 @@ 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 risingCutoffsOnly             whether only conjuncts whose cutoff 
rises with the
+   *                                      watermark give a cutoff. Earlier 
versions also took
+   *                                      constant-only and negative-sign 
conjuncts.
    * @return state value watermark in milliseconds, is possible.
    */
   def getStateValueWatermark(
       attributesToFindStateWatermarkFor: AttributeSet,
       attributesWithEventWatermark: AttributeSet,
       joinCondition: Option[Expression],
-      eventWatermark: Option[Long]): Option[Long] = {
+      eventWatermark: Option[Long],
+      risingCutoffsOnly: Boolean = true): Option[Long] = {

Review Comment:
   **Blocking (P1):** This default also reaches 
`StreamingSymmetricHashJoinHelper.getStateWatermark`, the only source of the 
state watermarks that `produceOutputWatermark` takes into the join's output 
watermark. Where a constant-only or negative-sign conjunct gave an input its 
only state watermark on the base branch, that input now reports none, although 
its rows stay in state and can still be emitted. Where the rule moves an input 
onto eviction by another TIMESTAMP column, as for `rightTime BETWEEN leftTime 
AND expiry AND CAST(leftTime AS LONG) > 10`, its state watermark becomes that 
column's cutoff. Either way the output watermark rises past rows the join still 
emits, and a stateful operator after the join, which the default mode allows, 
drops them as late.
   
   By the review's reading of the code, take a full outer join with 1-second 
watermarks on `leftKey = rightKey AND lt > rt - INTERVAL 5 SECONDS AND CAST(rt 
AS LONG) > 10`, projected to rightKey and rt and deduplicated with 
`dropDuplicatesWithinWatermark`. The right row (1, rt = 30 s) is stored and 
never evicted. Once other keys move the watermark to 99 s, the left row (1, lt 
= 100 s) matches it and the join emits the joined row, but the deduplication 
drops it, because the join's output watermark is now about 94 s. On the base 
branch the right input's state watermark of 10 s held the output watermark 
there, and the row passed. The description's inner join on `CAST(lt AS LONG) + 
CAST(rt AS LONG) > 100`, followed by a deduplication on lt, drops (1, 200, 500) 
the same way. Inputs evicted by another column without such a conjunct have 
this gap from #60667 alone (SPARK-62001); this comment is about the inputs 
whose state watermark this PR's rule changes.
   
   This extends existing discussions 
[1](https://github.com/apache/spark/pull/60664#issuecomment-7001062358), 
[2](https://github.com/apache/spark/pull/60664#discussion_r4622938152).
   
   **Recommended change:** Keep the rule in the solver for the analysis check 
and the V4 probe range, and give the readers that evict state or report a state 
watermark a per-input choice between the rule's answer and the earlier rule's 
answer, which still takes constant-only and negative-sign conjuncts into the 
minimum (risingCutoffsOnly = false). In 
StreamingSymmetricHashJoinHelper.getStateWatermarkPredicates, keep the rule's 
column and cutoff for an input when the rule gives the column it evicts an 
exact cutoff of its own, in the default or the legacy mode, or gives the input 
no cutoff at all, so both description examples and the left semi joins keep 
their fix. Otherwise, as for an input on the whole-input path whose remaining 
cutoffs were all solved for another column (in the legacy mode, or on the 
default-mode fallback in StreamingSymmetricHashJoinHelper.scala lines 287-289), 
or one whose remaining cutoff comes only from conjuncts that pass the evicted 
column or the other input's
  watermarked column through a cast that drops fractions of a second, such as 
CAST to LONG, make the choice the earlier rule makes, with TODOs naming 
SPARK-62044 and SPARK-61381. A cutoff is exact for a column when some conjunct 
solved for that column alone passes neither column through such a cast; 
StreamingJoinHelper gets the check for that cast, and the per-column choice 
gets a way to use the earlier rule. The V4 previous bound and the NULL rule 
follow the choice made, and the V4 restart check computes the default mode's 
column the same way. getStateWatermark returns the rule's answer only for an 
input that this choice evicts by its event time with an exact cutoff, and the 
earlier rule's answer for every other input, including one the rule leaves 
without a cutoff or evicts by another TIMESTAMP column, with a TODO naming 
SPARK-62001. Rewrite the last sentence of the migration entry to say that these 
joins keep the earlier cutoff and output watermark until those follow-ups land, 
and
  add join tests for each case. The whole-input fallback came in 3aaff10de1a, 
whose message gives no reason for it, and used the earlier rule until 
79489c01685 made the new rule the solver's default without a stated reason for 
applying it there; the fallback as of 6ef8e5bb4b1 is the starting point for 
inputs without an exact cutoff.
   
   **Why this works:** The earlier rule's minimum includes every conjunct that 
the branch used before this PR, so making its choice for an input returns that 
input's eviction and V4 previous bound to what the branch computed then, which 
on the whole-input path is what the base branch computes; no such input loses a 
row that the branch kept before this PR. The rule's own answer stays wherever 
it is safe by itself: a cutoff that is exact for the column it evicts removes 
only rows that no later row can match, and no cutoff removes nothing. 
getStateWatermark reports the rule's answer only for an input evicted by its 
event time, the column the output watermark bounds, with an exact cutoff; that 
answer is a minimum over at least the conjuncts behind that cutoff, so it never 
exceeds the cutoff and stays below every row the input keeps. Every other input 
reports the earlier rule's answer, which is the base branch's state watermark, 
so the output watermark stays where the base branch held it 
 for them.
   
   **Compatibility:** Inputs whose remaining cutoff is exact for the column 
they are evicted by keep the rule's column, cutoff and V4 previous bound, and 
their state watermark when that column is the event time, so both description 
examples, the left semi joins and the V4 ordering of such inputs stay as this 
PR makes them; inputs evicted by another TIMESTAMP column with no constant-only 
or negative-sign conjunct keep the stacked change's behavior.
   
   **Risks:** Inputs that take the earlier rule keep its behavior until the 
follow-ups land: a constant-only cap keeps withholding outer null rows and 
growing state, a falling negative-sign cutoff can still evict the early rows 
that the base branch also evicts, and the output watermark stays held back, so 
stateful operators after such a join make no more progress than on the base 
branch. For an input that the rule leaves without a cutoff but that a 
negative-sign conjunct gave a falling cutoff on the base branch, as in the 
description's inner join, the join keeps rows that the base branch evicted 
while reporting the base branch's state watermark, so an operator after the 
join that uses that input's event time still receives every row it received on 
the base branch but drops the new matches of rows below that watermark. 
Eviction, the V4 previous bound, the NULL rule and the V4 restart check have to 
make the same choice, and getStateWatermark has to draw its line from that 
choice; if th
 ey drift apart, the output watermark can pass rows that eviction keeps, or the 
V4 scan can skip rows it never evicted. For an input whose only rising bound 
goes through a truncating cast on a column other than its event time, beside a 
capping conjunct on the event time, the earlier rule evicts by the event time, 
so its V4 state is ordered by the event time; only a checkpoint written by an 
unreleased build of this branch orders it otherwise. There is no flag; rolling 
back means removing the per-input choice, which brings back the lost matches 
and the rows dropped after the join.
   
   **Constraints:** For each input, eviction, the V4 previous bound, the NULL 
rule and the V4 restart check use one choice, and getStateWatermark reports the 
rule's answer only when that choice evicts the input by its event time with an 
exact cutoff, which keeps the reported state watermark at or below that cutoff; 
every other input reports the base branch's state watermark. The analysis check 
and the V4 probe range keep the new rule for every condition, so a 
constant-only conjunct never again becomes a probe offset and the newly 
rejected outer joins stay rejected. An input that the rule leaves without a 
cutoff stays without an eviction cutoff, so the description's inner join keeps 
its match. The exactness check treats as inexact every cast the solver passes 
through that does not keep microseconds exactly, such as a cast to an integral 
type, to a DECIMAL with fewer than six fractional digits, which rounds, or to 
FLOAT, on the evicted column and on the other input's watermarked column
  alike.
   
   **Exclusions:**
   - Making truncating-cast cutoffs exact (SPARK-61381), evicting inputs 
bounded only through a non-TIMESTAMP column by that column (SPARK-62044), and 
bounding the output watermark by the rows the join keeps (SPARK-62001), which 
the planned follow-ups own; each lets the inputs it fixes drop the earlier rule.
   - State format 4 rows that an earlier version left in state before a 
restart, which the SPARK-62038 TODO defers.
   - The output watermark of inputs evicted by another TIMESTAMP column with no 
constant-only or negative-sign conjunct, which comes from the stacked change 
alone.
   
   **Verification:**
   - **Regression:** In the default mode on state formats 2 to 4, a left outer 
join whose only rising bound on the left input goes through a TIMESTAMP_NTZ 
column cast to TIMESTAMP, beside 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:** With spark.sql.streaming.statefulOperator.allowMultiple 
set to false, a left outer join whose rising bound is on a second TIMESTAMP 
column of the left input, beside a constant-only conjunct on the event time, 
keeps the left row and emits the match.
   - **Regression:** On state formats 2 to 4, a left outer join bounded through 
`CAST(lt AS LONG) >= CAST(rt AS LONG) - 5` beside a constant-only conjunct on 
lt emits the match of a left row whose truncated time a later right row still 
satisfies, instead of a null row, and so does the same join with a 
negative-sign conjunct in place of the constant in a batch where that 
conjunct's falling cutoff is the lower one.
   - **Regression:** A full outer join on `leftKey = rightKey AND lt > rt - 
INTERVAL 5 SECONDS AND CAST(rt AS LONG) > 10` followed by a deduplication with 
a watermark on rt keeps a joined row whose right row was stored long before the 
watermark passed it, the description's inner join followed by a deduplication 
on lt keeps a joined row such as (1, 200, 500), and a left semi join on the 
description's sum condition followed by such a deduplication keeps the left row 
(1, 200).
   - **Regression:** A left outer join on `leftKey = rightKey AND rightTime 
BETWEEN leftTime AND expiry AND CAST(leftTime AS LONG) > 10` still evicts the 
left input by expiry, and a deduplication on leftTime after it keeps a joined 
row whose right row arrives after the watermark has passed that row's leftTime, 
as on the base branch.
   - **Behavior:** In the default and the legacy mode on state formats 2 to 4, 
both description examples, the constant-only left semi join across a restart, 
and a left outer join with an exact rising bound on the event time beside a 
constant-only conjunct keep their current results, and for the left outer joins 
the output watermark rises with the input watermark.
   - **Compatibility:** The analysis result of every join type and condition 
form in the analysis tests and the V4 probe range stay as they are, and a join 
bounded only through another TIMESTAMP column with no constant-only or 
negative-sign conjunct keeps its eviction column, cutoff, previous bound and 
output watermark.
   - **Compatibility:** With state format 4, a join checkpointed in the default 
mode restarts in the legacy mode exactly when the column that the default 
mode's eviction now picks is the event time, both for an input that keeps the 
rule's pick of another TIMESTAMP column and for one whose only rising bound 
goes through `CAST(expiry AS LONG) >= CAST(rightTime AS LONG)` beside a 
constant-only conjunct on leftTime, which the earlier rule evicts by leftTime.
   - **Inspection:** The comments at the per-input choice and at 
getStateWatermark name SPARK-62044, SPARK-61381 and SPARK-62001 as the 
follow-ups that let affected inputs drop the earlier rule, and the migration 
entry no longer says that a cutoff solved for another column can evict by the 
event time where a constant-only conjunct used to cap it.



##########
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:
   Thanks. The recommended change does not bring back the sum example: it keeps 
the new rule wherever that rule leaves an input without a cutoff, which is what 
happens to `CAST(lt AS LONG) + CAST(rt AS LONG) > 100`, and uses master's 
cutoff, which still takes constant-only and negative-sign conjuncts into the 
minimum, only for an input whose remaining cutoff was solved for a column other 
than the one it is evicted by. Until #60705 lands, and in the legacy mode even 
after it does, those joins lose matches that master returns; the migration note 
describes that instead of preventing it. Keeping master's cutoff for those 
inputs, with a TODO naming SPARK-62044, keeps those matches until the 
follow-ups land, at the cost of withholding their unmatched outer rows as 
master does.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4622938102","thread_id":"inline:4622938102","verdict_sha256":"7c81d79cd7b4f793e145babd4e64097fb08ac730de60e92d9b54f6016d2fd6a2"}
 -->



##########
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:
   Agreed that SPARK-61381 is the right fix for the inexact cutoff itself. The 
problem is the window before it lands: on master, a constant-only conjunct, or 
a negative-sign one once its falling cutoff is the lower of the two, holds the 
minimum below the cutoff solved from the truncating cast, so these joins keep 
the row and return the match, while with this change alone they evict the row 
and lose it. Keeping master's minimum only for inputs whose remaining bounds 
all go through a truncating cast, with a TODO naming SPARK-61381, or landing 
SPARK-61381 first, keeps those matches in the meantime.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4622938130","thread_id":"inline:4622938130","verdict_sha256":"7c81d79cd7b4f793e145babd4e64097fb08ac730de60e92d9b54f6016d2fd6a2"}
 -->



##########
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:
   Thanks. For a join evicted by another column without a constant-only or 
negative-sign conjunct, SPARK-62001 and its follow-up are the right place, 
since that case comes from #60667. This PR's rule adds joins to it whose output 
watermark master held back, and this review raises the output watermark of the 
inputs the rule changes, including inputs it leaves with no cutoff, as a 
finding: until the guard lands, an operator after such a join drops rows that 
master passed.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4622938152","thread_id":"inline:4622938152","verdict_sha256":"7c81d79cd7b4f793e145babd4e64097fb08ac730de60e92d9b54f6016d2fd6a2"}
 -->



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