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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -17,36 +17,720 @@
 
 package org.apache.spark.sql.catalyst.analysis
 
+import java.util.Locale
+
+import scala.util.Try
 import scala.util.control.NonFatal
 
 import org.apache.spark.internal.Logging
 import org.apache.spark.internal.LogKeys._
+import org.apache.spark.sql.catalyst.InternalRow
 import org.apache.spark.sql.catalyst.expressions._
-import org.apache.spark.sql.catalyst.planning.ExtractEquiJoinKeys
-import org.apache.spark.sql.catalyst.plans.logical.{EventTimeWatermark, 
LogicalPlan}
+import org.apache.spark.sql.catalyst.plans.{InnerLike, LeftOuter, RightOuter}
+import org.apache.spark.sql.catalyst.plans.logical.{Expand, Join, LogicalPlan, 
Project, UnaryNode, Union}
 import org.apache.spark.sql.catalyst.plans.logical.EventTimeWatermark._
-import org.apache.spark.sql.catalyst.util.DateTimeConstants.MICROS_PER_DAY
+import org.apache.spark.sql.catalyst.util.DateTimeConstants.{MICROS_PER_DAY, 
MICROS_PER_HOUR, MICROS_PER_MILLIS, MICROS_PER_MINUTE, MICROS_PER_SECOND}
 import org.apache.spark.sql.types._
 import org.apache.spark.unsafe.types.CalendarInterval
 
+/**
+ * How far below a column that can filter its stream-stream join input's late 
rows one of the
+ * input's watermarked columns can be, for an equality key or a range 
condition on it: at most
+ * `micros` where the plan relates the two columns; by an amount that the plan 
does not bound when
+ * `unbounded`; and by an amount that it does not show when `unrelated`, 
because it does not relate
+ * the two. A window column is compared by its end, as eviction and late 
filtering compare it.
+ */
+case class EventTimeLag(micros: Long, unrelated: Boolean, unbounded: Boolean) {
+  def max(other: EventTimeLag): EventTimeLag = EventTimeLag(math.max(micros, 
other.micros),
+    unrelated || other.unrelated, unbounded || other.unbounded)
+
+  /**
+   * The cutoff for the other input's equality key when this input's watermark 
is `watermark`.
+   * A key that the plan does not relate keeps the Spark 4.3 cutoff.
+   */
+  def keyWatermark(watermark: Long): Option[Long] =
+    if (unbounded) None else Some(watermark - EventTimeLag.ceilMillis(micros))

Review Comment:
   **Non-blocking (P2):** In legacy mode 
(`spark.sql.streaming.statefulOperator.allowMultiple=false`, state formats 1 to 
3), this returns the full watermark for a lag that the plan leaves `unrelated`, 
while `rangeWatermark` returns `None` for the same lag. 
`getEventTimeKeyOrdinal` keeps such a key and, with its placeholder lag of 
zero, prefers it even over a related key with a known lag, so 
`getOneSideStateWatermarkPredicate` evicts the other input's state by it and 
`canEvictState` admits outer and left semi joins through it. 
`lagThroughJoinCondition` also turns a relation that it finds unbounded into 
`unrelated`, so a key that an earlier join relates to the late-filtered column 
only through a union input without a watermark gets the same cutoff.
   
   By the review's reading of the code, the key form of this PR's own scenario 
still loses its match: with `lId = rId AND l = v` in 
`StreamingJoinSelectedEventTimeSuite`, the upstream key-only join leaves `v` 
unrelated to the late-filtered `u`, the left row `(1, 5 s)` is evicted once the 
watermark reaches 50 seconds, and the later upstream row `(u = 100 s, v = 5 
s)`, which passes late filtering on `u`, finds nothing. As a left outer join, 
the same query passes analysis and emits `(1, 5 s)` as unmatched before the 
match arrives. The range form `l > v` now keeps its row, and the base branch 
loses both, so only one of the two paths is fixed. The test name and the docs 
of `getStateKeyWatermarkOrdinal`, `getEventTimeKeyOrdinal` and 
`getStateKeyWatermark` describe a rule that this path does not follow.
   
   **Recommended change:** Give an equality key on a later watermarked column 
whose lag the lag model classifies as unrelated no cutoff, as rangeWatermark 
already gives a range condition on it: make EventTimeLag.keyWatermark return 
None for an unrelated lag, and make getEventTimeKeyOrdinal skip such a key so 
that it never wins over a related key. Name such a key in the legacy-mode note 
of the admission error, and update the keyWatermark doc, the migration guide's 
'As in earlier versions' sentence and the test comments that describe the Spark 
4.3 key cutoff. Build the window column of UnsupportedOperationsSuite's 
legacy-mode cases of a window after its event time with a projection, since a 
test relation that outputs it directly is unrelated. Add the key form of the 
PR's scenario, which loses its match today, to the selected-event-time and 
legacy event-time key tests, and rename the PR's test, whose name says that 
only the first watermarked column bounds state. History: round 4 of #602
 80 (470c0cc6b63) bounded a later key only when the analyzed plan showed it 
built from the late-filtered column; round 5 (e03f9977b87) went back to the 
Spark 4.3 rule because keys reaching the join through a repartition, a 
temporary view, a typed filter, observe, a hint, a stream-static join, a 
self-join or a session window had lost their bound. Round 6 (634eb849aa4) gives 
those keys lag zero, so take 470c0cc6b63's rule as the starting point and apply 
it to the lag model of round 6 rather than restoring round 4's walk.
   
   **Why this works:** rangeWatermark already withholds a cutoff from an 
unrelated or unbounded column. Giving keyWatermark the same condition removes 
the cutoff in getStateKeyWatermark, its only caller, and skipping unrelated 
lags in getEventTimeKeyOrdinal keeps the key ordinal and the admission check 
from selecting such a key, so execution and analysis, which both read keys 
through these two functions, stop bounding state by a column that late 
filtering does not bound. lagThroughJoinCondition's fallback from unbounded to 
unrelated then also gives no cutoff.
   
   **Scope:** Change how the key side of the lag model reads an unrelated lag, 
and update the admission note, the migration guide and the tests that describe 
the Spark 4.3 key cutoff.
   
   **Compatibility:** Keys on the late-filtered column and on later watermarked 
columns whose lag the plan bounds, including copies, time and session windows 
and shifted copies of it, directly or behind repartitions, views, typed 
filters, observe, hints, stream-static joins and self-joins, keep the cutoffs 
and admission that the lag model gives them, and the default mode and state 
format 4 are unchanged.
   
   **Risks:** Released legacy-mode queries keyed on such a column change: an 
inner join keeps the other input's rows for the life of the query instead of 
evicting them, and an outer or left semi join fails analysis unless 
spark.sql.streaming.join.checkFinalization.enabled is false, when it runs with 
the warning and keeps that state; like the stack's other eviction corrections, 
the corrected eviction cannot be turned off, so the migration guide must say 
so. Tests whose relation outputs a later watermarked column directly, without a 
projection that builds it, see an unrelated column and change outcome.
   
   **Constraints:** Keep the cutoffs of keys on the late-filtered column and of 
later keys whose lag the plan bounds. Leave the default mode and state format 4 
unchanged; the default mode passes no lags and state format 4 rejects several 
event-time columns. Land the change before a release writes generation 3 of 
spark.sql.streaming.join.checkpointWatermarkSemanticsVersion, or raise the 
generation, so that the first-batch check covers checkpoints whose state such a 
key evicted.
   
   **Exclusions:**
   - The execution lags of a column that a union input without a watermark 
builds, which the separate repair for union inputs without data covers.
   
   **Success:** In legacy mode an equality key on a later watermarked column 
whose lag the lag model classifies as unrelated gives the other input's state 
no cutoff, in execution and at analysis, as a range condition on that column 
already does. getEventTimeKeyOrdinal never selects such a key, so a related key 
with a bounded lag wins over it. A legacy-mode outer or left semi join whose 
finalized input is bounded only through such a key fails analysis with a note 
that names the key. Keys whose lag the plan bounds keep the cutoffs the lag 
model gives them.
   
   **Verification:**
   - **Regression:** In legacy mode on state formats 2 and 3, the query of the 
PR's own test with lId = rId AND l = v in place of l > v keeps the left row (1, 
5 s) past the 50-second watermark and returns its match when the upstream join 
emits (u = 100 s, v = 5 s).
   - **Regression:** In legacy mode, a left outer join keyed on a column of an 
earlier key-only join, and one keyed on a column that an earlier inner join 
relates to the late-filtered column only through a union input without a 
watermark, fail analysis with a note that names the key, and with 
spark.sql.streaming.join.checkFinalization.enabled set to false they run with 
the warning and keep the left rows.
   - **Compatibility:** Legacy-mode joins keyed on the late-filtered column or 
on a copy, a tumbling, sliding or session window, or a shifted copy of it, 
directly or behind a repartition, a temporary view, a typed filter, observe, a 
hint, a stream-static join or a self-join, keep their current eviction and 
admission, and the default mode and state format 4 behave as before.
   - **Inspection:** No code doc, migration-guide sentence or test comment 
still says that a key the plan does not relate keeps the Spark 4.3 cutoff, and 
the PR's test name states the rule that holds.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala:
##########
@@ -167,6 +171,29 @@ class IncrementalExecution(
   private val allowMultipleStatefulOperators: Boolean =
     
sparkSession.sessionState.conf.getConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE)
 
+  // The lags of the planned join inputs, against the columns that they filter 
late rows by. They
+  // read the optimized plan, whose expression IDs the planned joins use. The 
analysis check reads
+  // the analyzed plan with the same rule, against every column that pruning 
can leave first, so
+  // it bounds a column here whenever it bounds one there. The projections 
that build the later
+  // watermarked columns stay in every batch's optimized plan: they sit above 
the input's
+  // watermark node, which the optimizer keeps even for a batch without data.
+  private lazy val eventTimeLags: Option[EventTimeLags] =
+    if (allowMultipleStatefulOperators) {
+      None
+    } else {
+      Some(StreamingJoinHelper.findEventTimeLags(optimizedPlan, planned = 
true))

Review Comment:
   **Non-blocking (P2):** In legacy mode 
(`spark.sql.streaming.statefulOperator.allowMultiple=false`, state formats 1 to 
3), these lags come from the batch's optimized plan, which does not keep every 
union input. When a union input without a watermark node has no new data, 
`MicroBatchExecution` replaces its sources with an empty streaming 
`LocalRelation`, and `PropagateEmptyRelation` empties the projections over it 
and removes it from the `Union`: its Union case has no streaming guard, and it 
never empties an `EventTimeWatermark`, so the inputs that carry a watermark 
node stay. `lagBelow`'s Union rule then no longer sees the input that makes a 
later watermarked column unbounded, so the column gets the remaining inputs' 
lag, zero for a copy of the event time, and both 
`getStateValueWatermarkForLags` and the key path give it a cutoff in that 
batch. The comment above relies on every batch keeping the projections that 
build such columns, which does not hold for that input.
   
   By the review's reading of the code: take a left input `(lk, lt)` and a 
right input `r1.union(r2)`, where `r1` copies its watermarked `rt` into `rc` 
and `r2` builds `rc` from a stream without a watermark, joined on `lk = rk AND 
lt > rc`. The left row `(1, 10 s)` stays while `r2` has data, but after a batch 
with only left and `r1` rows has advanced the watermark to 69 seconds, the 
no-data batch that follows evicts it, and a later `r2` row `(1, rt = 80 s, rc = 
5 s)` that passes late filtering finds nothing. The base branch evicts such 
rows in every batch; here the result depends on how the input splits into 
batches. Analysis reads the analyzed plan, where the input is present, and 
rejects outer and left semi joins bounded only through such a column, so in 
practice inner joins are affected, and the migration guide's statement that 
inner joins on such a key keep the other input's rows for the life of the query 
does not hold.
   
   **Recommended change:** In legacy mode, also run findEventTimeLags on the 
batch's analyzed plan in IncrementalExecution.eventTimeLags, where a source 
without new data is still an empty streaming LocalRelation under its Union, and 
make a column's execution lag unbounded whenever that walk finds it unbounded; 
every other column keeps the optimized plan's lag. Match the two plans' columns 
through the renames that the optimizer removes: RemoveRedundantAliases strips 
an alias that keeps a column's name and metadata, such as withColumn on the 
column's own name above a repartition of the union, and the optimized join 
input then carries the expression ID of the column that the alias reads, not 
the one that the analyzed walk reports. Correct the comment above 
eventTimeLags, which says that the projections building later watermarked 
columns stay in every batch, to say that a union input without a watermark can 
leave the optimized plan. Add legacy-mode execution tests with a union of a 
water
 marked and an unwatermarked stream and no-data micro-batches on, for a range 
condition and for an equality key, with and without such a rename between the 
union and the join. History: rounds 4 (470c0cc6b63) and 5 (e03f9977b87) of 
#60280 read their legacy-mode rules from the batch's analyzed plan, which keeps 
every operator of the query in every batch, and round 6 (634eb849aa4) moved the 
walk to the optimized plan so that a lag is taken against the column that the 
planned input filters late rows by. Keep round 6's planned walk and read the 
analyzed plan again only for unbounded columns.
   
   **Why this works:** lagBelow's Union rule returns unbounded whenever it sees 
a union input that does not watermark the column, and the batch's analyzed plan 
always contains that input, so the column is unbounded in every batch and 
rangeWatermark and keyWatermark give it no cutoff. Carrying that verdict 
through the renames that the optimizer removes puts it on the expression ID 
that the planned join input uses. Other columns keep the lag that the optimized 
plan measures against the column the planned input filters late rows by, so the 
precise cutoffs that pruning allows stay.
   
   **Scope:** Make the execution lags independent of which sources have data in 
a micro-batch.
   
   **Compatibility:** The default mode and state format 4 are unchanged, and 
every column that the batch's analyzed plan does not find unbounded keeps the 
lag of the optimized plan.
   
   **Risks:** A column that the batch's analyzed plan finds unbounded only 
against an earlier watermarked column that the optimizer prunes, such as a copy 
after a session window with a gap that is not constant placed before the event 
time, loses the cutoff it gets today, so the other input keeps more state; no 
cutoff rises. The analyzed walk adds driver work once per micro-batch, 
proportional to the plan size, as the optimized walk already does.
   
   **Constraints:** Keep measuring every bounded lag against the column that 
the planned input filters late rows by. Leave the analysis check unchanged; it 
already reads the analyzed plan, where every union input is present.
   
   **Exclusions:**
   - The key cutoff of a column that the plan does not relate to the 
late-filtered one, which the separate repair for unrelated keys covers.
   
   **Success:** In legacy mode a later watermarked column that a union input 
without a watermark builds gives no range cutoff and no key cutoff in any 
micro-batch, including batches in which that input has no new data and no-data 
micro-batches, also when a rename that the optimizer removes sits between the 
union and the join. A legacy-mode inner join bounded only through such a column 
keeps the other input's rows, and a later row of the unwatermarked union input 
with an old value in that column matches them. Columns outside unions, and 
columns that every union input builds with a watermark, keep the cutoffs they 
get today.
   
   **Verification:**
   - **Regression:** In legacy mode on state formats 2 and 3 with no-data 
micro-batches on, an inner join whose range condition bounds the left input 
only through a copy of the event time that a union of a watermarked and an 
unwatermarked stream builds keeps a left row through a no-data batch and 
through a batch in which only the watermarked stream has data, and returns its 
match with a later row of the unwatermarked stream whose copy is below the 
watermark.
   - **Regression:** The same scenario with an equality key on such a column 
keeps the other input's row and returns the match.
   - **Regression:** The range scenario above with a repartition of the union 
followed by withColumn on the copy's own name, an alias that the optimizer 
strips, also keeps the left row through a batch in which only the watermarked 
stream has data and returns the match.
   - **Compatibility:** Legacy-mode joins on a copy, a window or a shifted copy 
of the event time, with and without pruning of the event time, and over a union 
whose inputs all carry a watermark, keep their current eviction in data batches 
and no-data batches.



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