spark-test commented on code in PR #60282:
URL: https://github.com/apache/spark/pull/60282#discussion_r4598419940
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -224,98 +238,394 @@ 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.
+ // TODO(SPARK-61348): the analysis check admits a range bound on a
column that is not
+ // TIMESTAMP, which this branch never evicts.
+ 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-61348): the analysis check admits a range bound on a column
that is not
+ // TIMESTAMP, which no candidate below takes. A left, right or full
outer join whose
+ // preserved side is bounded only through such a column cast to
TIMESTAMP then keeps its
+ // unmatched rows in state and never emits them. SPARK-61348 rejects
that shape at analysis.
+ // TODO(SPARK-61508): an inner or left semi join side that is bounded only
through such a
+ // cast column has no eviction predicate either, 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
+ // columns in input schema order and use the first with a bound. This
makes the indexed column
+ // deterministic for a fixed input schema and join condition.
+ val candidates = eventTime.toSeq ++ inputAttributes.filter { attribute =>
+ attribute.dataType == TimestampType &&
!eventTime.exists(_.semanticEquals(attribute))
+ }
+ 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) {
Review Comment:
**Blocking (P1):** In legacy mode
(`spark.sql.streaming.statefulOperator.allowMultiple=false`), take the shape
that `StreamingJoinLegacyEventTimeKeySuite.legacyJoin` runs: `lk = rk AND lw =
rw`, where each input is `(k, t, window(t, 10 seconds))` with a watermark on
`t` and the query reads `t` after the join. `TimeWindowResolution` copies the
delay key onto the window, so each planned input has two watermarked columns
and this size check fails; `keyOnly` is false because `lw` is watermarked, so
the check returns `false` at line 455. Yet Spark 4.3 evicted both sides at the
window end <= W through that key, and this version gives the window lag zero,
so `getStateKeyWatermark` returns W at the same ordinal, late filtering still
uses `t`, and the V1 to V3 layout is unchanged. By the review's reading of the
code, restarting a Spark 4.3 checkpoint of that query fails with
`STREAMING_JOIN_CHECKPOINT_INCOMPATIBLE`, and so does a join on `t` itself
while the window is kept, although the ba
se branch resumes both. The check never reads the legacy-mode lags that decide
these cutoffs, and no test restarts an older legacy-mode checkpoint whose
inputs keep several watermarked columns, so neither this rejection nor the
rejection of keys whose lag does lower the cutoff has a failure signal.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60282#discussion_r4531361623).
**Recommended change:** Pass the legacy-mode event-time lags that
IncrementalExecution already computes for the batch into
isWatermarkCheckpointCompatible. With
spark.sql.streaming.statefulOperator.allowMultiple=false, accept an older
checkpoint in two cases. The first is a join whose watermarked conditions are
equality keys on watermarked columns at the same ordinal of both inputs, where
the lag of every such key gives the watermark itself as its cutoff, as Spark
4.3 used. The second is a time-interval join that compares only the inputs'
first watermarked columns, judged by the existing interval rule on those
columns. For joins with a watermark column on both inputs, keep rejecting keys
whose lag lowers the cutoff or is unbounded, range conditions on later
watermarked columns, and every other shape that the check rejects today. Update
the migration guide's statement that checkpoints of joins on a watermarked
column after the first one are rejected, so it names only those whose bo
und this version lowers.
**Why this works:** A lag of zero, or no relation to the late-filtered
column, gives the watermark itself as the key cutoff, which is what Spark 4.3
used for every watermarked key. Late filtering by the first watermarked column,
the format 1 to 3 state layout and the matched flags are the same in both
versions, and legacy mode ignores the join's output watermark. So the saved
state keeps its meaning exactly when every bound read from the lags equals the
older cutoff, and the check can accept it.
**Scope:** Accept older legacy-mode checkpoints whose join bounds keep Spark
4.3's cutoffs, judged from the lags that eviction already reads.
**Compatibility:** With multiple stateful operators allowed, every join with
a watermark column on both inputs keeps the outcome that the restart check
gives it today.
**Risks:** The acceptance reads the lags of the first batch after the
restart. Until the lags stop depending on which sources have data, a first
batch in which a watermark-less union input is idle would see a bound for a key
that later batches treat as unbounded, and accept a checkpoint it should reject.
**Constraints:** For joins with a watermark column on both inputs, keys
whose lag lowers the cutoff or is unbounded and range conditions on later
watermarked columns stay rejected before any state is opened, and with multiple
stateful operators allowed such joins keep today's outcome. State format 4
keeps rejecting several event-time columns per input.
**Exclusions:**
- Accepting legacy-mode range joins on later watermarked columns of inputs
that both have watermark columns, whose cutoff this version lowers by the
column's lag.
**Success:** In legacy mode, an older format 1 to 3 checkpoint of a join on
a time window over the first watermarked column, or on that column while the
input also keeps the window, resumes and returns the same results as Spark 4.3.
An older legacy-mode checkpoint of a join on a key whose lag lowers the cutoff
or is unbounded is still rejected with STREAMING_JOIN_CHECKPOINT_INCOMPATIBLE,
with state and commits unchanged. The migration guide says which legacy-mode
checkpoints are rejected.
**Verification:**
- **Compatibility:** In legacy mode, an older state format 2 checkpoint of a
join on a ten-second window over the watermarked event time, with the event
time read after the join, resumes and matches rows that were buffered before
the restart.
- **Compatibility:** In legacy mode, an older checkpoint of a join on the
first watermarked column of inputs that also keep a window over it resumes with
the same results as Spark 4.3.
- **Regression:** In legacy mode, older checkpoints of joins on a key
shifted backward by a fixed interval, and on a key that a union input builds
from a column without a watermark, are still rejected before state or commits
change.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -186,6 +878,23 @@ object StreamingJoinHelper extends PredicateHelper with
Logging {
return None
}
+ // The terms count a whole day as 24 hours, although Spark adds days in
the session time
+ // zone, where a day can be 23 or 25 hours, and read CAST(ts AS BIGINT) as
ts, although the
+ // cast drops the fraction of a second. Either can put the cutoff above a
row that can still
+ // match. A column with its own watermark keeps such a cutoff, as existing
queries rely on
+ // it. With exactForUnwatermarkedColumns, any other column, such as the
bounded column of an
+ // input without a watermark, gets no cutoff from such a condition.
+ val stateColumnHasWatermark = constraintTerm.exists {
+ case a: AttributeReference =>
+ attributesToFindStateWatermarkFor.contains(a) &&
a.metadata.contains(delayKey)
+ case _ => false
+ }
+ if (exactForUnwatermarkedColumns && !stateColumnHasWatermark &&
Review Comment:
**Blocking (P1):** With a watermark only on the right input, `lk = rk AND
CAST(lt AS DOUBLE) + CAST(rt AS DOUBLE) > 100` reaches this gate for `lt`: the
DOUBLE casts are not truncating, the constraint term `-lt` passes the sign
check, and substituting the watermark into `-rt`, which has the same sign as
`-lt`, gives a cutoff of 100 s - W. By the review's reading of the code, at
watermark 0 the left row `(k, 40 s)` is evicted, and a right row `(k, 61 s)` in
a later batch passes late filtering and satisfies 40 + 61 > 100 but finds
nothing. The inner join loses that match, and the left outer join, which
`canEvictState` admits through the same solver, emits the left row padded with
nulls first. The base branch never evicted an input without its own watermark,
and SPARK-61350 rejects negative watermark terms only later in the stack, with
nothing here marking the gap. Giving a column without its own watermark no
cutoff from a conjunct whose substituted watermark term has the same sign a
s the stored column, as this gate already does for inexact arithmetic, keeps
those inputs as the base branch had them; the two-sided case, which the base
branch already had, can stay with SPARK-61350 behind a TODO naming it.
**Verification:**
- **Regression:** An inner join with a watermark only on the right input and
the condition lk = rk AND CAST(lt AS DOUBLE) + CAST(rt AS DOUBLE) > 100 still
returns the match of a left row at 40 seconds with a right row at 61 seconds
that arrives in a later batch.
- **Behavior:** The left outer form of that join fails analysis with the
existing finalization error, and the solver gives no cutoff for the left column
of that conjunct.
- **Compatibility:** One-sided range joins whose condition subtracts the
opposite event time, such as rightTime BETWEEN leftTime AND leftTime + INTERVAL
1 HOUR, keep the same cutoffs and results.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -17,36 +17,722 @@
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))
+
+ /**
+ * The watermark to substitute for the column in a range condition. Spark
4.3 substituted the
+ * watermark for every watermarked column; this does so only where the plan
bounds the lag.
+ */
+ def rangeWatermark(watermark: Long): Option[Long] =
+ if (unbounded || unrelated) None else Some(watermark -
EventTimeLag.ceilMillis(micros))
+}
+
+object EventTimeLag {
+ val zero: EventTimeLag = EventTimeLag(0L, unrelated = false, unbounded =
false)
+ val unrelated: EventTimeLag = EventTimeLag(0L, unrelated = true, unbounded =
false)
+ val unbounded: EventTimeLag = EventTimeLag(0L, unrelated = false, unbounded
= true)
+
+ private def ceilMillis(micros: Long): Long =
+ micros / MICROS_PER_MILLIS + (if (micros % MICROS_PER_MILLIS == 0) 0 else
1)
+}
+
+/**
+ * The [[EventTimeLag]] of the watermarked columns of stream-stream join
inputs, by expression ID;
+ * see [[StreamingJoinHelper.findEventTimeLags]]. A column missing from `lags`
has lag zero, so
+ * `EventTimeLags(Map.empty)` gives every watermarked column lag zero. That is
right when multiple
+ * stateful operators are allowed: execution then fails at start for a planned
input with two
+ * distinct watermarked columns, so the only one left filters late rows itself.
+ */
+case class EventTimeLags(lags: Map[ExprId, EventTimeLag]) {
+ /**
+ * The lag of `column` in a join input with output `inputAttributes`, if it
carries a watermark.
+ * The input's first watermarked column filters its late rows itself.
+ */
+ def lagOf(column: NamedExpression, inputAttributes: Seq[Attribute]):
Option[EventTimeLag] =
+ if (!column.metadata.contains(delayKey)) {
+ None
+ } else if (inputAttributes.find(_.metadata.contains(delayKey))
+ .exists(_.exprId == column.exprId)) {
+ Some(EventTimeLag.zero)
+ } else {
+ Some(lags.getOrElse(column.exprId, EventTimeLag.zero))
+ }
+}
+
+object EventTimeLags {
+ val none: EventTimeLags = EventTimeLags(Map.empty)
+}
+
/**
* Helper object for stream joins. See [[StreamingSymmetricHashJoinExec]] in
SQL for more details.
*/
object StreamingJoinHelper extends PredicateHelper with Logging {
/**
- * Check the provided logical plan to see if its join keys contain a
watermark attribute.
- *
- * Will return false if the plan is not an equijoin.
- * @param plan the logical plan to check
+ * Find the equality key filtered by this input's watermark. Its ordinal can
be used to
+ * evict the opposite input's state, whose equality keys have the same
ordering.
+ * For leftTime = rightTime, a watermark on rightTime bounds leftTime even
when leftTime
+ * has no watermark. It does not bound right-side state without a watermark
on leftTime.
+ * A key computed from the event time by adding constant intervals, such as
+ * leftTime = rightTime + INTERVAL 10 SECONDS or leftTime =
timestampadd(HOUR, 1, rightTime),
+ * is bounded too if the solver can count the intervals exactly or they
never move a time
+ * backward; see [[getStateKeyWatermark]]. The result does not depend on the
session time zone,
+ * so neither does the V4 state layout. Without `lags`, only the input's
first watermarked
+ * column counts as its event time; with them, every watermarked column that
they bound does.
+ */
+ def getStateKeyWatermarkOrdinal(
+ keys: Seq[Expression],
+ inputAttributes: Seq[Attribute],
+ lags: Option[EventTimeLags] = None): Option[Int] = {
+ getEventTimeKeyOrdinal(keys, inputAttributes, lags).orElse {
+ keys.indices.find(getStateKeyWatermark(keys, inputAttributes, _,
Some(0L), lags).isDefined)
+ }
+ }
+
+ /**
+ * Find the equality key that is this input's first watermarked column, or
else, with `lags`,
+ * the watermarked key with the smallest lag that bounds it; see
[[findEventTimeLags]].
+ */
+ def getEventTimeKeyOrdinal(
+ keys: Seq[Expression],
+ inputAttributes: Seq[Attribute],
+ lags: Option[EventTimeLags] = None): Option[Int] = {
+ // When multiple stateful operators are disabled, late filtering uses the
first event-time
+ // column. Otherwise, execution rejects multiple distinct event-time
columns.
+ inputAttributes.find(_.metadata.contains(delayKey)).flatMap { eventTime =>
+ Some(keys.indexWhere(_.semanticEquals(eventTime))).filter(_ >= 0).orElse
{
+ lags.flatMap { l =>
+ keys.indices.flatMap { i =>
+ keyLag(keys(i), inputAttributes, l).filterNot(_.unbounded).map(i
-> _.micros)
+ }.sortBy(_._2).headOption.map(_._1)
+ }
+ }
+ }
+ }
+
+ /** The lag of a key that is a watermarked column of the input. */
+ private def keyLag(
+ key: Expression,
+ inputAttributes: Seq[Attribute],
+ lags: EventTimeLags): Option[EventTimeLag] = key match {
+ case n: NamedExpression => lags.lagOf(n, inputAttributes)
+ case _ => None
+ }
+
+ /**
+ * The lag of every watermarked column of each stream-stream join input in
`plan`, combined
+ * over the inputs by [[EventTimeLag.max]]. This is for
+ * spark.sql.streaming.statefulOperator.allowMultiple=false, where an input
can keep several
+ * watermarked columns, such as its event time and a copy of it or a time
window over it, and
+ * filters late rows by the first of them. When `planned`, `plan` is the
optimized plan that runs,
+ * so each input filters late rows by its first watermarked column, and a
column's lag is taken
+ * against that one. Otherwise the optimizer can prune any watermarked
column before a column, so
+ * its lag is the largest against all of them. Spark 4.3 bounded state by
every watermarked
+ * column at the watermark. A lag lowers that cutoff; see [[EventTimeLag]].
+ */
+ def findEventTimeLags(plan: LogicalPlan, planned: Boolean): EventTimeLags = {
+ val lags = plan.collect {
+ case j: Join if j.left.isStreaming && j.right.isStreaming => Seq(j.left,
j.right)
+ }.flatten.flatMap { input =>
+ val watermarked =
input.output.filter(_.metadata.contains(delayKey)).map(_.exprId).distinct
+ watermarked.indices.map { i =>
+ val lateFiltered = if (planned) watermarked.take(1) else
watermarked.take(i)
+ watermarked(i) -> lateFiltered.filter(_ != watermarked(i)).map {
eventTime =>
+ lagBelow(input, watermarked(i), eventTime, Some(0L), Some(0L))
+ }.foldLeft(EventTimeLag.zero)(_ max _)
+ }
+ }
+ EventTimeLags(lags.groupMapReduce(_._1)(_._2)(_ max _))
+ }
+
+ /** How a column relates to the column of a node's child that [[lagBelow]]
follows for it. */
+ private case class Step(column: ExprId, offset: Option[Long])
+
+ /**
+ * How far `key` of `plan` can be below its column `eventTime`, which late
filtering compares
+ * with the watermark. Both are compared by their bounds: a time, or a
window's end. `keyLow` is
+ * the smallest that the join input's key is above `key`, and
`eventTimeHigh` the largest that the
+ * join input's late-filtered column is above `eventTime`; None means
without bound. The walk
+ * follows both columns down by expression ID: through a projection or an
expansion that passes
+ * them on, builds a time or session window from a single column, or, for
the key, shifts a
+ * timestamp by constant intervals; through any other node with one input
that outputs both, as
+ * such a node keeps an expression ID only for an unchanged value; into the
input of a join that
+ * outputs both, or into both inputs of one that outputs each from a
different input and equates
+ * them through its condition (see [[lagThroughJoinCondition]]); and into
every input of a union,
+ * at the same positions. A union input that does not watermark a column
that the union, which
+ * takes its first input's metadata, watermarks builds it some other way, so
the lag is
+ * unbounded. Where both reach the same column, the lag is the difference of
the two offsets.
+ * Everything else leaves the columns unrelated.
+ */
+ private def lagBelow(
+ plan: LogicalPlan,
+ key: ExprId,
+ eventTime: ExprId,
+ keyLow: Option[Long],
+ eventTimeHigh: Option[Long]): EventTimeLag = {
+ def outputsBoth(p: LogicalPlan): Boolean =
+ p.output.exists(_.exprId == key) && p.output.exists(_.exprId ==
eventTime)
+ def follow(child: LogicalPlan, keyStep: Option[Step], eventTimeStep:
Option[Step]) =
+ (keyStep, eventTimeStep) match {
+ case (Some(k), Some(t)) => lagBelow(child, k.column, t.column,
+ addOffsets(keyLow, k.offset), addOffsets(eventTimeHigh, t.offset))
+ case _ => EventTimeLag.unrelated
+ }
+ if (key == eventTime) {
+ (keyLow, eventTimeHigh) match {
+ case (Some(low), Some(high)) => Try(Math.subtractExact(high,
low)).toOption match {
+ case Some(lag) => EventTimeLag(math.max(0L, lag), unrelated = false,
unbounded = false)
+ case None => EventTimeLag.unbounded
+ }
+ case _ => EventTimeLag.unbounded
+ }
+ } else {
+ plan match {
+ case p: Project =>
+ def entry(id: ExprId): Option[NamedExpression] =
p.projectList.find(_.exprId == id)
+ follow(p.child, entry(key).flatMap(keyStep),
entry(eventTime).flatMap(eventTimeStep))
+ case e: Expand =>
+ // The rewrite of a sliding window puts one window per projection
beside the child's
+ // columns, which every projection passes on.
+ def step(id: ExprId, window: (Seq[Expression], Attribute) =>
Option[Long]) = {
+ val entries = e.output.indexWhere(_.exprId == id) match {
+ case -1 => Nil
+ case index => e.projections.map(_(index))
+ }
+ entries.map {
+ case a: Attribute => Some(a.exprId)
+ case _ => None
+ }.distinct match {
+ case Seq(Some(passedOn)) => Some(Step(passedOn, Some(0L)))
+ case _ if e.output.exists(a => a.exprId == id &&
+ a.metadata.contains(TimeWindow.marker)) =>
+ entries.map(timeWindowSource).distinct match {
+ case Seq(Some(source)) => Some(Step(source.exprId,
window(entries, source)))
+ case _ => None
+ }
+ case _ => None
+ }
+ }
+ // A window ends after its time column, and at most its length after
it.
+ follow(e.child, step(key, (_, _) => Some(0L)), step(eventTime,
(entries, source) =>
+ entries.map(timeWindowLength(_, source)).reduceOption((a, b) =>
+ for (x <- a; y <- b) yield math.max(x, y)).flatten))
+ case u: Union =>
+ val keyIndex = u.output.indexWhere(_.exprId == key)
+ val eventTimeIndex = u.output.indexWhere(_.exprId == eventTime)
+ def unwatermarked(child: LogicalPlan, index: Int): Boolean =
+ u.output(index).metadata.contains(delayKey) &&
+ !child.output(index).metadata.contains(delayKey)
+ if (keyIndex < 0 || eventTimeIndex < 0) {
+ EventTimeLag.unrelated
+ } else {
+ u.children.map { child =>
+ if (unwatermarked(child, keyIndex) || unwatermarked(child,
eventTimeIndex)) {
+ EventTimeLag.unbounded
+ } else {
+ lagBelow(child, child.output(keyIndex).exprId,
+ child.output(eventTimeIndex).exprId, keyLow, eventTimeHigh)
+ }
+ }.reduce(_ max _)
+ }
+ case j: Join =>
+ j.children.find(outputsBoth).map(lagBelow(_, key, eventTime, keyLow,
eventTimeHigh))
+ .getOrElse(lagThroughJoinCondition(j, key, eventTime, keyLow,
eventTimeHigh))
+ case u: UnaryNode if outputsBoth(u.child) =>
+ lagBelow(u.child, key, eventTime, keyLow, eventTimeHigh)
+ case _ => EventTimeLag.unrelated
+ }
+ }
+ }
+
+ /**
+ * The lag of `key` below `eventTime` of [[lagBelow]] where `join` outputs
them from different
+ * inputs, through an equality `x = y` in its condition between a
watermarked column x of the
+ * key's input and a watermarked column y of the event time's input: the key
is at most its lag
+ * below x, which equals y, which is at most its lag below the event time,
so the lags add up.
+ * That holds on every row that the join outputs with a non-NULL key: all
rows of an inner join
+ * satisfy its condition, and so do those of a left or right outer join that
pads the key's
+ * input, whose other rows carry a NULL key that no condition matches. The
smallest bounded lag
+ * over such equalities wins. Other conjuncts, such as a range or a shifted
equality, and other
+ * join types leave the columns unrelated.
+ */
+ private def lagThroughJoinCondition(
+ join: Join,
+ key: ExprId,
+ eventTime: ExprId,
+ keyLow: Option[Long],
+ eventTimeHigh: Option[Long]): EventTimeLag = {
+ def watermarked(p: LogicalPlan): Set[ExprId] =
+ p.output.filter(_.metadata.contains(delayKey)).map(_.exprId).toSet
+ def outputs(p: LogicalPlan, id: ExprId): Boolean =
p.output.exists(_.exprId == id)
+ val inputs = if (outputs(join.left, key) && outputs(join.right,
eventTime)) {
+ Some((join.left, join.right))
+ } else if (outputs(join.right, key) && outputs(join.left, eventTime)) {
+ Some((join.right, join.left))
+ } else {
+ None
+ }
+ val lags = inputs.filter { case (keyInput, _) =>
+ join.joinType match {
+ case _: InnerLike => true
+ case LeftOuter => keyInput eq join.right
+ case RightOuter => keyInput eq join.left
+ case _ => false
+ }
+ }.toSeq.flatMap { case (keyInput, eventTimeInput) =>
+ val keyColumns = watermarked(keyInput)
+ val eventTimeColumns = watermarked(eventTimeInput)
+ join.condition.toSeq.flatMap(splitConjunctivePredicates).flatMap {
+ case EqualTo(a: Attribute, b: Attribute) => Seq(a.exprId -> b.exprId,
b.exprId -> a.exprId)
+ case _ => Nil
+ }.filter { case (x, y) => keyColumns.contains(x) &&
eventTimeColumns.contains(y) }
+ .map { case (x, y) =>
+ val below = lagBelow(keyInput, key, x, keyLow, Some(0L))
+ val above = lagBelow(eventTimeInput, y, eventTime, Some(0L),
eventTimeHigh)
+ if (below.unrelated || above.unrelated) {
+ EventTimeLag.unrelated
+ } else {
+ Try(Math.addExact(below.micros, above.micros)).toOption
+ .filter(_ => !below.unbounded && !above.unbounded)
+ .map(EventTimeLag(_, unrelated = false, unbounded = false))
+ .getOrElse(EventTimeLag.unbounded)
+ }
+ }
+ }
+ lags.filter(lag => !lag.unrelated &&
!lag.unbounded).sortBy(_.micros).headOption
+ .getOrElse(EventTimeLag.unrelated)
Review Comment:
**Non-blocking (P2):** In legacy mode (`allowMultiple=false`), let input A
watermark `at` and keep a watermarked copy `as = at - INTERVAL 1 DAY`, then
join `AB = A.join(B, ak = bk AND as = bt)` and `AB.join(C, bt = ct)`. For the
pair `(bt, as)`, the walk from `as` to `at` is unbounded because a backward
whole-day shift has no bound, so the pair is unbounded; this line then drops it
and reports `bt` as unrelated, and `keyWatermark` keeps the cutoff `ct <= W`.
By the review's reading of the code, an AB row whose `at` is just above W
carries a `bt` about a day below W and misses the C rows already evicted, and a
right outer join on `bt` passes analysis and emits those C rows as unmatched
too early, while joining C directly on `as` bounds nothing. `EventTimeLag`
reserves unrelated for columns that the plan does not relate; returning
`EventTimeLag.unbounded` here when no relating equality is bounded but at least
one is unbounded makes such a key bound nothing, as it does without the in
termediate join.
**Verification:**
- **Regression:** In legacy mode, with input A keeping as = at - INTERVAL 1
DAY, AB = A.join(B, ak = bk AND as = bt) and then AB.join(C, bt = ct), the
inner join keeps C's rows, so an AB row whose bt is about a day below the
watermark still matches, and the right outer form fails analysis.
- **Compatibility:** Legacy-mode keys related through an earlier join by a
bounded equality, such as at = bt, keep their cutoffs and results.
##########
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, take an inner join `L.join(Y, lk = yk
AND lw = yw)` with `Y = Y1.union(Y2)`, where Y1 watermarks `t` and builds `yw =
window(t, 10 seconds)`, and Y2 has no watermark and builds `yw = window(other,
10 seconds)`. While Y2 has data, `lagBelow` marks `yw` unbounded through Y2,
and L is not evicted by it. In a batch where Y2's source is idle, and in every
no-data batch, MicroBatchExecution replaces that source with an empty streaming
`LocalRelation`, `PropagateEmptyRelation` folds Y2's projection and drops it
from the union, and the lags read from this optimized plan give `yw` lag zero,
so L's state is evicted at a window end <= W. By the review's reading of the
code, a later Y2 row whose `t` passes late filtering but whose window is older
than W then finds no L row. The comment above relies on every input's
projections sitting above its own watermark node, which Y2 lacks.
**Recommended change:** In legacy mode, also compute the lags from the
batch's analyzed plan, as the analysis check does, and treat a column as
unbounded in execution whenever that result is unbounded. Otherwise keep the
planned amount. Correct the comment above eventTimeLags, which says the
projections stay in every batch's plan. By its message, e03f9977b87 decided
from the analyzed plan which legacy-mode keys bound state. 634eb849aa4 replaced
that with lags from each batch's optimized plan, so that execution takes the
lag against the column that actually filters late rows. Keep that amount, and
start from e03f9977b87's analyzed-plan reading only to decide whether a column
is bounded.
**Why this works:** The analyzed batch plan keeps each idle union input as
an empty relation under its own projections. The lag walk therefore still sees
that the input builds the column from a column without a watermark, and reports
the lag as unbounded. Combining that result with the planned lags makes
execution bound a column only when analysis does, in every batch, which is the
rule the comment above eventTimeLags states.
**Scope:** Make the legacy-mode lags independent of which sources have data
in a batch.
**Risks:** An inner join on a key that is unbounded only through a union
input that the optimizer always removes keeps the other input's rows instead of
evicting them. This is safe, and it matches analysis, which already rejects the
outer forms.
**Constraints:** A bounded column's lag amount stays the one taken against
the planned input's late-filtered column. Runs with multiple stateful operators
allowed, which do not use these lags, are unchanged.
**Success:** In legacy mode, a key that a watermark-less union input builds
bounds no state in any batch, including batches where that input's source is
idle and no-data batches. Keys whose lag is bounded keep their current cutoffs.
**Verification:**
- **Regression:** In legacy mode, take an inner join of L with a union of a
watermarked input and a watermark-less input that builds the window key from
another column. After a batch in which the watermark-less input had no data,
and after a no-data batch, it still matches a later row of that input with an L
row buffered earlier.
- **Compatibility:** Legacy-mode joins on keys with a bounded lag, such as a
window over the first watermarked column, evict the same way in batches with
and without data for each source.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -224,98 +238,394 @@ 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.
+ // TODO(SPARK-61348): the analysis check admits a range bound on a
column that is not
+ // TIMESTAMP, which this branch never evicts.
+ 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-61348): the analysis check admits a range bound on a column
that is not
+ // TIMESTAMP, which no candidate below takes. A left, right or full
outer join whose
+ // preserved side is bounded only through such a column cast to
TIMESTAMP then keeps its
+ // unmatched rows in state and never emits them. SPARK-61348 rejects
that shape at analysis.
+ // TODO(SPARK-61508): an inner or left semi join side that is bounded only
through such a
+ // cast column has no eviction predicate either, 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
+ // columns in input schema order and use the first with a bound. This
makes the indexed column
+ // deterministic for a fixed input schema and join condition.
+ val candidates = eventTime.toSeq ++ inputAttributes.filter { attribute =>
+ attribute.dataType == TimestampType &&
!eventTime.exists(_.semanticEquals(attribute))
+ }
+ 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
Review Comment:
**Blocking (P1):** Take a Spark 4.3 left outer join of impressions without a
watermark and clicks with one, on `adId = clickAdId AND clickTime BETWEEN
impressionTime AND impressionTime + INTERVAL 1 HOUR`, in the default state
format 2 with nothing after the join: the shape the earlier join guide
described for left outer joins. With a watermark column on only one input, none
of the branches above applies, so this returns `false` in every format and the
restart fails with `STREAMING_JOIN_CHECKPOINT_INCOMPATIBLE`, while the base
branch resumes it. The earlier review asked to keep these shapes rejected, but
by this review's reading of the code their state in formats 1 to 3 can be
reused. Spark 4.3 gave the impressions side no predicate because it had no
watermark, and the clicks side none because `getStateValueWatermark` returns
`None` when the other input has no watermark attribute, so the checkpoint holds
every impression with an accurate matched flag. V1 to V3 eviction tests every
stored row, so the first batch after the restart would remove the impressions
at or below the new cutoff and emit the never-matched ones padded with nulls,
which no later click can match; the clicks input still gets no bound, so only
its share of the output watermark changes, which the consumed-sides check
already covers. Format 4 is different: Spark 4.3 stored those impressions in
random buckets with no timestamp index entry, so timestamp eviction cannot find
them. Today users must replay with deduplication, and when the source no longer
holds that history, the unmatched impressions that the old checkpoint still
holds are never emitted.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60282#discussion_r4531361623).
**Recommended change:** Pass the join's pinned state format to
isWatermarkCheckpointCompatible, and accept an older checkpoint of a join in
which exactly one input has a watermark column in the planned join and no
equality key uses an event time, when that input is not among the consumed
sides and the state format is 1 to 3. Keep rejecting format 4, with a TODO at
that rejection naming the migration it would need: Spark 4.3 stored the rows of
the input without a watermark in random buckets with no timestamp index entry,
which timestamp eviction cannot find. Say in the migration guide's restart
paragraph that such checkpoints are reused in formats 1 to 3 and that their
first batch emits the never-matched rows that the older version kept, and turn
the compatibility suite's format 1 to 3 rejections of one-sided range
checkpoints into resume tests.
**Why this works:** Spark 4.3 gave a join input a range predicate only when
it had a watermark of its own, and gave the watermarked input none because the
other input had no watermark attribute, so it evicted neither input of such a
join, and in formats 2 and 3 every stored row keeps an accurate matched flag
(format 1 outer joins fail when the operator is built). Formats 1 to 3 evict by
testing every stored row each batch, so the first batch after the restart
removes the rows at or below this version's cutoff and emits the never-matched
ones padded with nulls; no later row of the other input can match them, because
late filtering drops it at or below the watermark. The watermarked input still
gets no bound, so only its state watermark in the join's output watermark
changes, which the consumed-sides check covers.
**Scope:** Reuse older checkpoints of joins where only one input has a
watermark column in state formats 1 to 3 when nothing after the join reads the
watermarked input's event time.
**Compatibility:** Joins with a watermark column on both inputs, key-only
joins, and joins whose equality keys use an event time keep the restart
outcomes that the other rules give them.
**Risks:** The first batch after such a restart evicts every row of the
input without a watermark that lies at or below the cutoff and emits the
never-matched ones, which for a long-running query can make that batch large.
The checkpoint keeps its older generation marker, so every later run repeats
the check, and a later change to how such a join is evicted must keep this
acceptance sound or raise the generation.
**Constraints:** The new acceptance applies only to joins where exactly one
input has a watermark column and no equality key uses an event time; every
other join keeps the outcome that the existing rules and the legacy-mode
acceptance give it. State format 4 checkpoints of such joins, and those whose
watermarked input's event time a later stateful operator reads, stay rejected
before any state is opened.
**Exclusions:**
- Reusing state format 4 checkpoints of such joins, which needs a migration
that indexes the rows stored without a timestamp.
**Success:** An older format 1 to 3 checkpoint of a join where only one
input has a watermark column, with no later stateful operator reading that
input's event time, resumes, and an outer join's first batch emits padded with
nulls the stored rows of the other input that never matched and lie at or below
the cutoff, and no row that matched before the restart. The same checkpoint in
format 4, or followed by a stateful operator that reads the watermarked input's
event time, is still rejected with STREAMING_JOIN_CHECKPOINT_INCOMPATIBLE, with
state and commits unchanged. The migration guide says which checkpoints of such
joins are reused.
**Verification:**
- **Compatibility:** An older format 2 checkpoint of a left outer join of
impressions without a watermark and clicks with one, on adId = clickAdId AND
clickTime BETWEEN impressionTime AND impressionTime + INTERVAL 1 HOUR, that
buffered matched and unmatched impressions resumes, and its first batch emits
the never-matched impressions at or below the cutoff padded with nulls and none
that matched before the restart.
- **Regression:** That checkpoint is still rejected, with state and commits
unchanged, in format 4 and when a deduplication after the join uses clickTime.
- **Behavior:** The compatibility suite's older checkpoints of the one-sided
inner range join resume in formats 1 to 3, keep their buffered rows that can
still match, and stay rejected in format 4.
##########
common/utils/src/main/resources/error/error-conditions.json:
##########
@@ -8165,6 +8165,41 @@
],
"sqlState" : "55019"
},
+ "STREAMING_JOIN_CHECKPOINT_INCOMPATIBLE" : {
+ "message" : [
+ "Cannot reuse the checkpoint for the stream-stream join with condition
<joinCondition>. Watermarked columns: left [<leftWatermarkColumns>], right
[<rightWatermarkColumns>].",
+ "This Spark version changes how watermarks determine which rows can
still match. Spark cannot verify that rows saved by the previous version can be
reused safely for this join. Start the query with a new checkpoint and replay
the required input, accounting for previously written results to avoid
duplicates and correct any missing or incorrect output."
+ ],
+ "sqlState" : "0A000"
+ },
+ "STREAMING_JOIN_UNBOUNDED_DOWNSTREAM_EVENT_TIME" : {
+ "message" : [
+ "The append-mode aggregation after a stream-stream join uses the event
time <eventTime> of the join's <side> input, but the join has no bound on that
event time for the state of that input, so it holds back its output watermark
and the aggregation would never emit results."
+ ],
+ "subClass" : {
+ "TIME_CONSTRAINT" : {
+ "message" : [
+ "Add a time constraint that limits how late a matching <otherSide>
row can arrive, aggregate the event time of an input whose state the join can
bound. A bound on the event time comes from an equality key that shifts the
other input's event time by an exact interval (under one day, or timestampadd
in hours, minutes or seconds), or from a range condition used in place of a
shifted equality. To run the query anyway, set <config> to false."
Review Comment:
**Nit (P3):** '... limits how late a matching <otherSide> row can arrive,
aggregate the event time of an input whose state the join can bound.' reads as
one instruction to do both, here and in the WATERMARK_AND_TIME_CONSTRAINT
message at line 8192, while the `_OR_UPDATE_MODE` variants end the same list
with 'or use the update output mode'. These are the variants a query with a
stream-stream outer join gets, such as a one-sided left outer join followed by
an append-mode window count over the right event time. Joining the two remedies
with 'or' ('..., or aggregate the event time of ...') makes them read as
alternatives.
**Verification:**
- **Inspection:** The TIME_CONSTRAINT and WATERMARK_AND_TIME_CONSTRAINT
messages join their two remedies with 'or', as the update-mode variants do.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -186,6 +878,23 @@ object StreamingJoinHelper extends PredicateHelper with
Logging {
return None
}
+ // The terms count a whole day as 24 hours, although Spark adds days in
the session time
Review Comment:
**Nit (P3):** This gate, `hasInexactArithmetic` and the exact-shift filter
in `getEventTimeWatermarkFromKey` describe the whole-day and truncating-cast
exemption as the rule, and nothing here says that SPARK-61381 is meant to lift
it: the only TODOs naming that ticket are on the left semi exact cutoff. A
reader would take as final that an inner join on `rightTime <= expiry +
INTERVAL 1 DAY`, with `expiry` lacking a watermark, keeps every left row, and
that a join on `leftTime = rightTime + INTERVAL 1 DAY` holds the output
watermark at 0 for the right input. A `TODO(SPARK-61381)` at each of the three
sites, naming which inputs keep their state or hold back the output watermark
until then, makes the deferral visible.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60282#discussion_r4531361718).
**Verification:**
- **Inspection:** The exactness gate, hasInexactArithmetic and the whole-day
key-shift filter each carry a TODO naming SPARK-61381 that states which inputs
keep their state, or hold back the output watermark, until then.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -224,98 +238,394 @@ 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.
+ // TODO(SPARK-61348): the analysis check admits a range bound on a
column that is not
+ // TIMESTAMP, which this branch never evicts.
+ 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-61348): the analysis check admits a range bound on a column
that is not
+ // TIMESTAMP, which no candidate below takes. A left, right or full
outer join whose
+ // preserved side is bounded only through such a column cast to
TIMESTAMP then keeps its
+ // unmatched rows in state and never emits them. SPARK-61348 rejects
that shape at analysis.
+ // TODO(SPARK-61508): an inner or left semi join side that is bounded only
through such a
+ // cast column has no eviction predicate either, 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
+ // columns in input schema order and use the first with a bound. This
makes the indexed column
+ // deterministic for a fixed input schema and join condition.
+ val candidates = eventTime.toSeq ++ inputAttributes.filter { attribute =>
+ attribute.dataType == TimestampType &&
!eventTime.exists(_.semanticEquals(attribute))
+ }
+ 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
Review Comment:
**Nit (P3):** On the first batch of a run that restores an older-generation
checkpoint, `IncrementalExecution` passes no V4 scan start, so this version
scans the index from the start and evicts the timestamp-0 entry, while Spark
4.3's scan start had already passed 0. The test 'resume a Spark 4.3.0 V4
checkpoint that holds a row with a NULL event time' expects exactly that row,
`Row(2, null, null, null)`, which Spark 4.3 never emitted. The
`isWatermarkCheckpointCompatible` doc above states the mechanism correctly;
naming the first-batch full scan here too keeps a later change from dropping it
and leaving such rows in state forever.
**Verification:**
- **Inspection:** The isOwnEventTimeIntervalJoin doc names the first-batch
full scan as the mechanism and no longer says that both versions scan the entry
the same way.
##########
docs/streaming/apis-on-dataframes-and-datasets.md:
##########
@@ -1297,6 +1297,17 @@ joined <- join(
Outer joins have the same guarantees as [inner
joins](#semantic-guarantees-of-stream-stream-inner-joins-with-watermarking)
regarding watermark delays and whether data will be dropped or not.
+Unmatched output and state removal use the same cutoff, derived from the
opposite input's
+watermark and the time constraint. In the example above, the `clickTime`
watermark finalizes
+impressions; no watermark on `impressionTime` is needed for this. Without that
watermark, the
+time constraint must have an exact length. An interval of a day or more, such
as
+`INTERVAL 1 DAY` or `INTERVAL 48 HOURS`, does not finalize impressions in any
session time zone,
+because Spark adds its whole days in the session time zone, where a day can
last 23 or 25 hours.
+Nor does a truncating cast such as `CAST(impressionTime AS BIGINT)`. An outer
join that relies
+on such a bound fails analysis; add a watermark on `impressionTime`, or use a
bound shorter than
Review Comment:
**Nit (P3):** This advice, repeated in the migration guide and in the
analysis error's note, turns the analysis failure into the inexact cutoff it
was meant to avoid. For a column with its own watermark,
`stateColumnHasWatermark` skips the exactness gate, so the solver counts a day
as 24 hours and reads `CAST(ts AS BIGINT)` as exact, as
`StreamingJoinHelperSuite` asserts for `leftEventTime`. By the review's reading
of the code, once the watermark is added, `clickTime BETWEEN impressionTime AND
impressionTime + INTERVAL 1 DAY` in America/Los_Angeles evicts an impression at
2024-11-02T19:00Z, padded with nulls, once W passes about 2024-11-03T19:00Z,
while a click at 19:30Z still falls inside the 25-hour local day; with a
truncating cast the cutoff can sit up to a second inside the bound in every
zone. A bound shorter than a day removes nothing for a truncating cast, and the
migration guide's 'because Spark adds whole days' also covers the cast, which
is excluded because it drops the
fraction of a second. Recommending an exact bound instead, such as a sub-day
interval on the TIMESTAMP columns in place of the cast (`impressionTime >=
clickTime + INTERVAL 5 SECONDS`), and saying that a watermark keeps the 24-hour
day and the cast's truncation, gives users advice that does what it promises.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60282#discussion_r4531361653).
**Verification:**
- **Inspection:** The join guide, the migration guide and the analysis
error's note say that a watermark keeps the 24-hour day and the cast's
truncation, and they name an exact alternative.
- **Behavior:** The analysis error for a one-sided left outer join bounded
by INTERVAL 1 DAY renders the corrected note.
##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinSuite.scala:
##########
@@ -2425,6 +2802,275 @@ abstract class StreamingLeftSemiJoinBase extends
StreamingJoinSuite {
}
}
+ // A left semi join processes the right input before the left input. A right
row at or below
+ // its eviction cutoff passes late filtering when it is above the
late-events watermark, and
+ // the left rows of the same batch must still find it. Each case runs a
batch whose
+ // late-events watermark is 100 seconds and whose eviction watermark is
`watermark` seconds.
+ // (name, condition, left time, right time, watermark, state rows after the
second batch and
+ // after the third)
+ for ((name, condition, leftTime, rightTime, watermark, rowsBefore,
rowsAfter) <- Seq(
+ ("equal event times", "leftTime = rightTime", 102, 102, 105, 2L, 0L),
+ // The left key leftTime + 10 seconds of (7, 100) stays above the
100-second cutoff.
+ ("a key shifted by less than the watermark step",
+ "leftTime + INTERVAL 10 SECONDS = rightTime", 120, 130, 150, 3L, 1L),
+ // The right key cutoff is the watermark plus 10 seconds less 1 ms, so
the right row
+ // (1, 112) is at or below it although the watermark advances by only 5
seconds. The left
+ // keys of (7, 100) and (7, 105) stay above the 105-second left cutoff.
+ ("a key shifted by more than the watermark step",
+ "leftTime + INTERVAL 10 SECONDS = rightTime", 102, 112, 105, 2L, 2L),
+ // A value cutoff of the watermark less 10 seconds and 1 ms: (1, 130) is
below 139.999 s.
+ ("a time interval",
+ "leftTime BETWEEN rightTime - INTERVAL 10 SECONDS AND rightTime +
INTERVAL 10 SECONDS",
+ 125, 130, 150, 4L, 2L))) {
+ test(s"left semi join keeps a same-batch match between the watermarks:
$name") {
+ withSQLConf(SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key ->
"false") {
+ val leftInput = MemoryStream[(Int, Int)]
+ val rightInput = MemoryStream[(Int, Int)]
+ val left = leftInput.toDF()
+ .select($"_1".as("leftKey"), timestamp_seconds($"_2").as("leftTime"))
+ .withWatermark("leftTime", "0 seconds")
+ val right = rightInput.toDF()
+ .select($"_1".as("rightKey"),
timestamp_seconds($"_2").as("rightTime"))
+ .withWatermark("rightTime", "0 seconds")
+ val joined = left.join(right, expr(s"leftKey = rightKey AND
$condition"), "left_semi")
+ .select($"leftKey", $"leftTime".cast("int"))
+
+ testStream(joined)(
+ MultiAddData(leftInput, (7, 100))(rightInput, (8, 100)),
+ CheckNewAnswer(),
+ MultiAddData(leftInput, (7, watermark))(rightInput, (8, watermark)),
+ CheckNewAnswer(),
+ assertNumStateRows(total = rowsBefore, updated = 4),
+ MultiAddData(leftInput, (1, leftTime))(rightInput, (1, rightTime)),
+ CheckNewAnswer((1, leftTime)),
+ // The right row is stored for the left row to probe and removed at
the end of the
+ // batch, together with the other rows at or below the cutoffs.
+ assertNumStateRows(total = rowsAfter, updated = 1))
+ }
+ }
+ }
+
+ // The right cutoff comes from a bound on rightExpiry. The right row (1,
110, 160) matches the
+ // left row (1, 120) of the same batch and is evicted at its end, whether
the cutoff is applied
+ // to rightExpiry or to rightTime. Storing only the right rows above the
cutoff at the
+ // late-events watermark would drop this match when the cutoff is applied to
rightTime.
+ test("left semi join keeps a same-batch match bounded by another right
column") {
+ withSQLConf(SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key ->
"false") {
+ val leftInput = MemoryStream[(Int, Int, Int)]
+ val rightInput = MemoryStream[(Int, Int, Int)]
+ val left = leftInput.toDF()
+ .select($"_1".as("leftKey"), timestamp_seconds($"_2").as("leftTime"))
+ .withWatermark("leftTime", "0 seconds")
+ val right = rightInput.toDF()
+ .select($"_1".as("rightKey"), timestamp_seconds($"_2").as("rightTime"),
+ timestamp_seconds($"_3").as("rightExpiry"))
+ .withWatermark("rightTime", "0 seconds")
+ val joined = left.join(right, expr("leftKey = rightKey AND " +
+ "rightExpiry >= leftTime + INTERVAL 30 SECONDS AND " +
+ "leftTime >= rightTime - INTERVAL 1 HOUR"), "left_semi")
+ .select($"leftKey", $"leftTime".cast("int"))
+
+ testStream(joined)(
+ MultiAddData(leftInput, (7, 100, 0))(rightInput, (8, 100, 100)),
+ CheckNewAnswer(),
+ MultiAddData(leftInput, (7, 150, 0))(rightInput, (8, 150, 150)),
+ CheckNewAnswer(),
+ assertNumStateRows(total = 3, updated = 4),
+ // The late-events watermark is 100 seconds, and the right cutoff at
it is 130 seconds
+ // less 1 ms: above the right row's rightTime of 110 seconds, below
its rightExpiry.
+ MultiAddData(leftInput, (1, 120, 0))(rightInput, (1, 110, 160)),
+ CheckNewAnswer((1, 120)),
+ assertNumStateRows(total = 2, updated = 1))
+ }
+ }
+
+ test("left semi join keeps a same-batch match bounded by another right
column when both " +
+ "watermarks are equal") {
+ withSQLConf(SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> "false",
+ SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key -> "false") {
+ val leftInput = MemoryStream[(Int, Int, Int)]
+ val rightInput = MemoryStream[(Int, Int, Int)]
+ val left = leftInput.toDF()
+ .select($"_1".as("leftKey"), timestamp_seconds($"_2").as("leftTime"))
+ .withWatermark("leftTime", "0 seconds")
+ val right = rightInput.toDF()
+ .select($"_1".as("rightKey"), timestamp_seconds($"_2").as("rightTime"),
+ timestamp_seconds($"_3").as("rightExpiry"))
+ .withWatermark("rightTime", "0 seconds")
+ val joined = left.join(right, expr("leftKey = rightKey AND " +
+ "rightExpiry >= leftTime + INTERVAL 30 SECONDS AND " +
+ "leftTime >= rightTime - INTERVAL 1 HOUR"), "left_semi")
+ .select($"leftKey", $"leftTime".cast("int"))
+
+ testStream(joined)(
+ MultiAddData(leftInput, (7, 100, 0))(rightInput, (8, 100, 100)),
+ CheckNewAnswer(),
+ // Both watermarks are 100 seconds, and the right cutoff is 130
seconds less 1 ms. The
+ // right row passes late filtering but is at or below the cutoff on
rightTime, and the
Review Comment:
**Nit (P3):** This diff already contains SPARK-61344:
`getStateValueWatermarkForInput` finds no cutoff for `rightTime` and bounds
`rightExpiry` at 130 s less 1 ms, so `(1, 110, 1000)` is not evicted in its
batch. With equal watermarks, a right row evicted in its batch has a
`rightExpiry` at or below 130 s - 1 ms and could match only a left row at or
below 100 s, which late filtering drops, so this legacy variant cannot reach
the same-batch eviction its name describes and passes whether or not the join
stores the right rows a batch evicts. Renaming it and saying that the cutoff is
on `rightExpiry`, with the default-mode test above covering the same-batch
path, keeps the test's description true.
**Verification:**
- **Inspection:** The legacy-mode left semi test's name and comment describe
the rightExpiry cutoff, and they point to the default-mode test for same-batch
eviction.
--
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]