spark-test commented on code in PR #60279:
URL: https://github.com/apache/spark/pull/60279#discussion_r4571551463
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -296,6 +293,258 @@ object StreamingSymmetricHashJoinHelper extends Logging {
JoinStateWatermarkPredicates(leftStateWatermarkPredicate,
rightStateWatermarkPredicate)
}
+ /** 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]): Option[(Attribute, Long)] = {
+ // TODO(SPARK-61348): the analysis check admits a range bound on a column
that is not
Review Comment:
**Nit (P3):** This TODO covers only the outer-join consequence. The same
candidate rule also leaves an inner or left semi join side bounded only through
a DATE, TIMESTAMP_NTZ or numeric column cast to TIMESTAMP without an eviction
predicate, so that side keeps its rows for the life of the query. The deferral
of that eviction to SPARK-61508 appears only in the PR description and the
author's reply, so a reader of this rule cannot tell that the unbounded state
is deliberate and tracked. A TODO here that names SPARK-61508, says such sides
keep their rows until eviction through the cast is supported, and notes that
projecting the column to TIMESTAMP before the join bounds that state would
close this.
This extends existing discussions
[1](https://github.com/apache/spark/pull/60279#issuecomment-6796057221),
[2](https://github.com/apache/spark/pull/60279#issuecomment-6816309914).
**Verification:**
- **Inspection:** The comment at the eviction-column candidate rule names
SPARK-61508 for inner and left semi join sides bounded only through a cast to
TIMESTAMP and says that such sides keep their state until then.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala:
##########
@@ -721,14 +869,69 @@ class IncrementalExecution(
override def apply(plan: SparkPlan): SparkPlan = {
val planWithStateOpId = plan transform composedRule
+ // Validate the checkpoint-pinned semantics before writing state
metadata or opening state,
+ // including a restart retrying an incomplete batch zero.
+ if (isFirstBatchWithOlderJoinWatermarkSemantics) {
+ def watermarkColumns(input: SparkPlan): String = {
+ val columns = input.output.filter(
+ _.metadata.contains(EventTimeWatermark.delayKey))
+ if (columns.isEmpty) "none" else columns.map(_.name).mkString(", ")
+ }
+ // A join's output watermark reaches every stateful operator above it.
One that uses its
+ // input watermark reads the inputs that the tracer names, or both
inputs when it cannot
+ // be traced. An operator uses it when an input carries an event-time
column, when it
+ // fires event-time timeouts, or when it passes the watermark to user
code, as
+ // transformWithState does in every time mode. The join's output
watermark changes
+ // nothing for any other operator, such as an update-mode count on a
key.
+ def usesInputWatermark(operator: StatefulOperator): Boolean = operator
match {
+ case _: TransformWithStateExec | _: TransformWithStateInPySparkExec
=> true
+ case f: FlatMapGroupsWithStateExec if f.timeoutConf ==
EventTimeTimeout => true
+ case f: FlatMapGroupsInPandasWithStateExec if f.timeoutConf ==
EventTimeTimeout => true
+ case _ => operator.children.exists(
+ _.output.exists(_.metadata.contains(EventTimeWatermark.delayKey)))
+ }
+ val joinsBelowStatefulOperators = planWithStateOpId.collect {
+ case s: StatefulOperator if usesInputWatermark(s) =>
s.children.flatMap(_.collect {
+ case j: StreamingSymmetricHashJoinExec =>
j.stateInfo.map(_.operatorId)
+ }.flatten)
+ }.flatten.toSet
+ val tracedSides = joinWatermarkConsumers(planWithStateOpId)
+ .groupMap(_.joinOperatorId)(_.side)
+ def consumedSides(j: StreamingSymmetricHashJoinExec): Set[JoinSide] =
+ j.stateInfo.map(_.operatorId) match {
+ case Some(id) if joinsBelowStatefulOperators.contains(id) =>
+ tracedSides.get(id).map(_.toSet).getOrElse(Set(LeftSide,
RightSide))
Review Comment:
**Blocking (P1):** For a left semi join this fallback counts the right input
although nothing after the join can read it: the join outputs only left
columns, and produceOutputWatermark uses only the left state watermark, here
and on the base branch. Take `leftKey = rightKey AND leftTime > rightTime -
INTERVAL 1 HOUR` with watermarks on both inputs, the shape of 'left semi output
watermark ignores unbounded right state', followed by transformWithState in
processing-time mode and restarted from a checkpoint that Spark 4.3.0 wrote.
Both versions derive the same left cutoff and no right cutoff, and give the
same output watermark. But usesInputWatermark is true for transformWithState,
the tracer records no side for it, and isWatermarkCheckpointCompatible, which
is not given the join type, sees the unbounded right input as consumed and
rejects the restart. The user must start a new checkpoint and replay input,
which the migration guide says cannot recover past results once the history i
s gone. flatMapGroupsWithState without an event-time timeout over an input
with an event-time column, and any operator behind a stream-static join,
trigger the same rejection. Intersecting the consumed inputs with the inputs
whose state watermark can enter the join's output watermark, only the left
input for a left semi join, would let these restarts resume while a right input
whose eviction changes is still rejected.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60279#discussion_r4537966847).
**Verification:**
- **Regression:** Restarting an older-marker checkpoint of a left semi join
on `leftKey = rightKey AND leftTime > rightTime - INTERVAL 1 HOUR` with
watermarks on both inputs, followed by transformWithState in processing-time
mode, resumes and keeps emitting the expected rows.
- **Compatibility:** An older-marker checkpoint of a left semi join whose
right input is bounded on a column other than its event time, and one of a
key-only inner join followed by a processing-time transformWithState, are still
rejected, and the left semi output watermark is unchanged.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/SymmetricHashJoinStateManager.scala:
##########
@@ -253,47 +254,47 @@ class SymmetricHashJoinStateManagerV4(
protected val keySchema = StructType(
joinKeys.zipWithIndex.map { case (k, i) => StructField(s"field$i",
k.dataType, k.nullable) })
protected val keyAttributes = toAttributes(keySchema)
- private val eventTimeColIdxOpt = WatermarkSupport.findEventTimeColumnIndex(
- inputValueAttributes,
- // NOTE: This does not accept multiple event time columns. This is not the
same with the
- // operator which we offer the backward compatibility, but it involves too
many layers to
- // pass the information. The information is in SQLConf.
- allowMultipleEventTimeColumns = false)
-
- // When there is no event time column in the value and no watermark ordinal
in the key,
+ private val valueTimestampColumnOrdinal = {
+ val eventTimeColIdx = WatermarkSupport.findEventTimeColumnIndex(
+ inputValueAttributes,
+ // NOTE: This does not accept multiple event time columns. This is not
the same with the
+ // operator which we offer the backward compatibility, but it involves
too many layers to
+ // pass the information. The information is in SQLConf.
+ allowMultipleEventTimeColumns = false)
+ // Validate event-time columns above even when eviction indexes a
different timestamp.
+ stateValueWatermarkColumnOrdinal.orElse(eventTimeColIdx)
+ }
+
+ // When there is no indexed timestamp column in the value and no watermark
ordinal in the key,
// the secondary index (TsWithKey) will never be used for eviction. Skip
writing to it
// to avoid unnecessary RocksDB merge overhead.
// TODO(SPARK-56536): This could be further optimized by also considering
whether the state
- // watermark predicate is defined. Even when an event time column exists,
the secondary index
- // is unused if eviction is not possible (e.g., only one side defines a
watermark in a time
- // interval join). That would require propagating the predicate
information here.
- private val hasEventTime: Boolean =
- eventTimeColIdxOpt.isDefined || joinKeyOrdinalForWatermark.isDefined
+ // watermark predicate is defined. Even when an indexed timestamp column
exists, the secondary
+ // index is unused if eviction is not possible (e.g., only one side
defines a watermark in a
+ // time interval join). That would require propagating the predicate
information here.
+ private val hasTimestampForEviction: Boolean =
+ valueTimestampColumnOrdinal.isDefined ||
joinKeyOrdinalForWatermark.isDefined
private val random = new scala.util.Random(System.currentTimeMillis())
- private val bucketCountForNoEventTime = 1024
- private val extractEventTimeFn: UnsafeRow => Long = { row =>
- eventTimeColIdxOpt match {
- case Some(idx) =>
- val attr = inputValueAttributes(idx)
-
- if (attr.dataType.isInstanceOf[StructType]) {
- // NOTE: We assume this is window struct, as same as
WatermarkSupport.watermarkExpression
- row.getStruct(idx, 2).getLong(1)
- } else {
- row.getLong(idx)
- }
-
- case _ =>
- // When event time column is not available, we will use random
bucketing strategy to decide
- // where the new value will be stored. There is a trade-off between
the bucket size and the
- // number of values in each bucket; we can tune the bucket size with
the configuration if
- // we figure out the magic number to not work well.
- random.nextInt(bucketCountForNoEventTime)
+ private val bucketCountWithoutTimestamp = 1024
+ // A null indexed timestamp makes the value-eviction predicate SQL-unknown,
so V2 and V3 never
Review Comment:
**Nit (P3):** OneSideHashJoiner now passes stateKeyEvictionFunc and
stateValueEvictionFunc to V1 to V3 eviction, and both also return true when the
eviction column is NULL, so V2 and V3 do evict such a row, and an outer join
emits it padded with nulls; the 'evict a restored left row with a NULL event
time' test asserts it. The rationale here is now false and hides a real
difference: a NULL-index row that V4 stores on a side without an eviction
predicate never enters the timestamp index, while V2 and V3 would remove it
once a predicate exists. V4's own reason would hold instead: a row whose
indexed timestamp is NULL can never satisfy the bound on that column, so a side
that evicts by it never stores one, and a side without an eviction predicate
keeps such a row out of the timestamp index so that timestamp eviction never
removes it.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60279#discussion_r4537966865).
**Verification:**
- **Inspection:** The V4 state manager's comment on NULL indexed timestamps
agrees with V1 to V3 eviction removing rows with a NULL eviction column and
states V4's own reason.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -4237,6 +4237,19 @@ object SQLConf {
.checkValue(v => Set(1, 2, 3, 4).contains(v), "Valid versions are 1, 2,
3, and 4")
.createWithDefault(2)
+ val STREAMING_JOIN_CHECKPOINT_WATERMARK_SEMANTICS_VERSION =
+ buildConf("spark.sql.streaming.join.checkpointWatermarkSemanticsVersion")
+ .internal()
+ .doc("Checkpoint generation for stream-stream join watermark semantics,
persisted in " +
+ "the offset log. Older generations are accepted only when the query
plan proves that " +
+ "its state and output watermark semantics are unchanged. The
generation validates " +
Review Comment:
**Nit (P3):** isWatermarkCheckpointCompatible accepts joins whose output
watermark does change: a key-only or one-directional join with no later
stateful operator that uses the watermark, where an unbounded input now
contributes 0 instead of nothing, and two-sided interval joins whose output
watermark is now narrowed to the inputs the next operator reads. Its scaladoc
says so: 'its state watermark in the join's output watermark changed'.
Maintainers of the later stack PRs, which raise this version when they change
which rows are kept, would read a stronger guarantee than the check gives.
Suggested wording: 'Older generations are accepted only when the query plan
proves that the saved join state, and every stateful operator after the join
that uses the affected event times, keep their meaning.'
**Verification:**
- **Inspection:** The doc of the semantics-version conf matches the restart
check's acceptance rule, including accepted joins whose output watermark
changes when no later stateful operator uses the affected event times.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -296,6 +292,229 @@ object StreamingSymmetricHashJoinHelper extends Logging {
JoinStateWatermarkPredicates(leftStateWatermarkPredicate,
rightStateWatermarkPredicate)
}
+ /** 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]): Option[(Attribute, Long)] = {
+ 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))
Review Comment:
Thanks for adding the TODO and for confirming the behavior. This review
still treats it as a defect of this PR rather than an acceptable in-between
state: each PR of the stack lands on master on its own, so from this PR until
SPARK-61348 merges, master accepts these outer joins and silently never emits
their unmatched rows, which it emitted before this PR. The TODO records the gap
but does not prevent it. Rejecting the shape at analysis in this PR, as
SPARK-61348 does later, would make these queries fail loudly in the meantime.
<!-- SPARK_DEV_REVIEW_REPLY
{"feedback_id":"inline:4537966815","thread_id":"inline:4537966815","verdict_sha256":"44ec2e248ca3b5ce860546a0fb3569712d9cbf00026b9aabb754f633dfb154a9"}
-->
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -717,21 +727,105 @@ case class StreamingSymmetricHashJoinExec(
Predicate.create(Literal(false), Seq.empty).eval _ // false = do not
remove if no predicate
}
+ // A NULL in the column that the state watermark predicate tests makes the
predicate unknown,
+ // so eviction never removes the row. The row cannot match either: that
column is an equality
+ // key, or a comparison in the join condition bounds it. Handle the row
like one that fails
+ // the pre-join filter.
+ // The check takes the generated key and the input row, so the key is
computed only once.
+ private[this] val isEvictionColumnNull: (UnsafeRow, UnsafeRow) => Boolean =
+ stateWatermarkPredicate match {
+ case Some(JoinStateKeyWatermarkPredicate(expr, _, _)) =>
+ // Only a NULL key fails equality. A struct key with a NULL field
can still be equal.
+ val ordinal = expr.collectFirst { case b: BoundReference =>
b.ordinal }.get
+ (key, _) => key.isNullAt(ordinal)
+ case Some(JoinStateValueWatermarkPredicate(LessThanOrEqual(column, _),
_, _)) =>
+ // Test the compared column, not the predicate: the predicate holds
the cutoff, which
+ // changes every batch and would generate and compile new code each
time.
+ val isNull = Predicate.create(IsNull(column), inputAttributes)
+ (_, row) => isNull.eval(row)
+ case _ =>
+ (_, _) => false
+ }
+
+ // V1 to V3 eviction tests every stored row each batch, so it also removes
a row whose
+ // eviction column is NULL. This version never stores such a row, but an
older version did,
+ // and the row can never match. isEvictionColumnNull reads only the key
for a key predicate
+ // and only the row for a value predicate.
+ private[this] val stateKeyEvictionFunc: UnsafeRow => Boolean =
+ key => stateKeyWatermarkPredicateFunc(key) || isEvictionColumnNull(key,
null)
Review Comment:
**Nit (P3):** This disjunct and the one below feed evictByKeyCondition,
evictByValueCondition, evictAndReturnByKeyCondition and
evictAndReturnByValueCondition, but only the last has a failure signal: 'evict
a restored left row with a NULL event time' restores a left outer interval
join. The NULL watermarked equality key test in StreamingOuterJoinBase checks
only the arrival gate, so reverting this line to stateKeyWatermarkPredicateFunc
still passes every suite. A row restored from an older checkpoint of a left
outer join on `leftKey = rightKey AND leftTime = rightTime`, a shape the
restart check accepts, would then stay in state and never be emitted padded
with nulls, which the PR description says happens in the first batch after the
restart. This version cannot write that state itself: for this condition
analysis needs a watermark on an equality key, and a watermarked equality key
drops a NULL-key row on arrival. A Spark 4.3.0 state format 2 checkpoint
holding a NULL-key left row
, like the state format 4 fixture this PR adds, would cover the key path that
returns rows. Inner joins on an event-time key and on an interval, whose NULL
row is stored in a first run without watermarks and with constraint propagation
off, as the inner NULL range-end test does, would cover the two paths that do
not return rows.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60279#discussion_r4537966865).
**Verification:**
- **Regression:** With the NULL check removed from the key eviction
function, the restored NULL-key row of the Spark 4.3.0 left outer join
checkpoint is never emitted and the inner join on an event-time key keeps its
NULL-key row, and with it removed from the value eviction function the inner
interval join keeps its NULL-time row; the inner-join cases fail in state
formats 2 and 3.
##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelperSuite.scala:
##########
@@ -48,6 +50,34 @@ class StreamingJoinHelperSuite extends AnalysisTest {
}
}
+ test("state watermark extraction ignores columns outside both attribute
sets") {
+ val leftTime = AttributeReference("leftTime", TimestampType)()
+ val leftOffset = AttributeReference("leftOffset", LongType)()
+ val metadata = new MetadataBuilder().putLong(EventTimeWatermark.delayKey,
1000).build()
+ val rightTime = AttributeReference("rightTime", TimestampType, metadata =
metadata)()
+ val rightDelay = AttributeReference("rightDelay", DayTimeIntervalType())()
+ val conditions = Seq(
+ leftTime > TimestampAddInterval(rightTime, rightDelay),
+ leftTime.cast(LongType) + leftOffset > rightTime.cast(LongType))
+ val logAppender = new LogAppender("state watermark extraction")
+ withLogAppender(logAppender, level = Some(Level.WARN)) {
+ conditions.foreach { condition =>
+ withClue(condition.sql) {
+ // The first condition reaches the references check through the V4
range scan and the
+ // left semi exact cutoff, which pass only the opposite event time;
eviction passes the
Review Comment:
**Nit (P3):** The left semi exact cutoff cannot reach the references check
for this condition: getLeftSemiExactRightCutoffs keeps only conjuncts whose
sides pass isExactShiftOf, which accepts a TimestampAddInterval only with a
literal interval, so a shift by the column rightDelay is filtered out before
getStateValueWatermark runs. This wording followed an earlier suggestion from
this review, which made the same mistake. Only the V4 range scan, which passes
just the two event times, can reach the check with this conjunct, and only when
another conjunct gives a side a value-eviction predicate on its own event time,
since the range scan runs only for such a side. Naming only that caller, with
that precondition, and keeping the explanation of eviction for both conditions
would make the comment accurate.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60279#discussion_r4537966899).
**Verification:**
- **Inspection:** For each condition in the solver test, the comment names
only callers whose attribute sets and conjunct filters let the condition reach
the references check.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala:
##########
@@ -630,6 +660,124 @@ class IncrementalExecution(
watermarkPropagator.propagate(currentBatchId, plan,
watermarkForCurrBatch)
}
+ /**
+ * Find, for each stateful operator that applies its input watermark to an
event-time column,
+ * which stream-stream join inputs' event times that column carries. The
walk follows the
+ * column down through nodes that pass it on unchanged, to the same
position in every input
+ * of a union, and through windows built from it, which end after it. It
stops at a join, at
+ * another operator that writes state or sets an event time, and at any
node it does not
+ * recognize; a join that no traced column reaches holds back for both
inputs.
+ */
+ private def joinWatermarkConsumers(plan: SparkPlan):
Seq[JoinWatermarkConsumer] = {
+ def eventTime(output: Seq[Attribute]): Option[Attribute] =
+ output.find(_.metadata.contains(EventTimeWatermark.delayKey))
+
+ // A time or session window built from one column, plus constants, ends
after that column.
+ def windowSource(window: Attribute, expression: Expression):
Option[Attribute] = {
+ val isWindow = window.metadata.contains(TimeWindow.marker) ||
+ window.metadata.contains(SessionWindow.marker)
+ expression.references.toSeq match {
+ case Seq(source) if isWindow => Some(source)
+ case _ => None
+ }
+ }
+
+ def passThrough(child: SparkPlan, attribute: Attribute): Seq[(Long,
JoinSide, Attribute)] =
+ child.output.find(_.exprId ==
attribute.exprId).toSeq.flatMap(findJoinSides(child, _))
+
+ def findJoinSides(
+ node: SparkPlan,
+ attribute: Attribute): Seq[(Long, JoinSide, Attribute)] = {
+ node match {
+ case j: StreamingSymmetricHashJoinExec =>
+ val side = if (eventTime(j.left.output).exists(_.exprId ==
attribute.exprId)) {
+ Some(LeftSide)
+ } else if (eventTime(j.right.output).exists(_.exprId ==
attribute.exprId)) {
+ Some(RightSide)
+ } else {
+ None
+ }
+ j.stateInfo.map(_.operatorId).zip(side).map { case (id, s) => (id,
s, attribute) }
+ .toSeq
+ case p: ProjectExec =>
+ p.projectList.find(_.exprId == attribute.exprId).toSeq.flatMap {
+ case a: Attribute => passThrough(p.child, a)
+ case Alias(a: Attribute, _) => passThrough(p.child, a)
+ case alias: Alias =>
+ windowSource(alias.toAttribute,
alias.child).toSeq.flatMap(passThrough(p.child, _))
+ case _ => Nil
+ }
+ case e: ExpandExec =>
+ // A sliding window is one projection per window; each must carry
the same column.
+ val index = e.output.indexWhere(_.exprId == attribute.exprId)
+ val traced = e.projections.map { projection =>
+ projection.lift(index).toSeq.flatMap {
+ case a: Attribute => passThrough(e.child, a)
+ case expression =>
+ windowSource(e.output(index),
expression).toSeq.flatMap(passThrough(e.child, _))
+ }
+ }
+ if (traced.nonEmpty && traced.forall(_.nonEmpty) &&
traced.distinct.size == 1) {
+ traced.head
+ } else {
+ Nil
+ }
+ case u: UnionExec =>
+ val index = u.output.indexWhere(_.exprId == attribute.exprId)
+ if (index < 0) Nil else u.children.flatMap(c => findJoinSides(c,
c.output(index)))
+ case _: StateStoreWriter | _: EventTimeWatermarkExec | _:
UpdateEventTimeColumnExec =>
+ Nil
+ case u: UnaryExecNode if u.output.exists(_.exprId ==
attribute.exprId) =>
+ passThrough(u.child, attribute)
+ case _ => Nil
Review Comment:
**Blocking (P1):** A stream-static join is planned as a
BroadcastHashJoinExec, ShuffledHashJoinExec, SortMergeJoinExec or nested-loop
join, and this case stops the trace there, although such a join passes its
streaming side's columns through unchanged, and the PR description says the
tracer follows nodes that keep the column. The stream-stream join below keeps
outputWatermarkSides = None, so produceOutputWatermark holds back for both
inputs, and getOneSideStateWatermark now returns 0 for an input with no bound
on its own event time. The PR's own test 'V4 chained joins scan from the start
after the plan between them changes' builds this: impressions joined with
clicks on `clickTime <= impressionTime + INTERVAL 10 SECONDS`, a stream-static
left outer join with campaigns, then a left outer join with conversions over
impressionTime, and the test expects nothing to be evicted in its third batch.
On the base branch the click input had no state watermark and was left out of
the minimum,
so by this review's reading the upstream output watermark was the impression
cutoff, about 90 seconds there, and the downstream join emitted (1, 10, null,
null). An append-mode window aggregation or a deduplication over impressionTime
behind a stream-static enrichment join likewise never emits, and its state
grows with every row, with no error. The restart check reads the same tracer,
so older checkpoints of such queries are rejected as well.
This extends existing discussions
[1](https://github.com/apache/spark/pull/60279#issuecomment-6775614175),
[2](https://github.com/apache/spark/pull/60279#discussion_r4537966830).
**Recommended change:** In findJoinSides, at any binary node that outputs
the traced attribute, such as the join node of a stream-static join, follow it
into the one child that outputs it instead of stopping, and stop as today when
no child or more than one child outputs it. Update the chained-join V4
checkpoint test, whose first run expects nothing to be evicted behind a
stream-static join: with the trace through that join, its first run emits the
buffered impression padded with nulls as the base branch does, and its second
run still checks that the downstream join's first batch has no scan start.
Update the example in the comment at that reset, which cites removing a
stream-static join, and add stream-stream join output watermark tests with a
stream-static join between a one-directional join and the next stateful
operator.
**Why this works:** With the trace continuing through binary nodes that pass
the column on, the join below a stream-static join learns which of its inputs
the next operator reads, so it holds back only for those inputs as it already
does without the stream-static join, and the restart check reads the same
narrower set.
**Scope:** Let the output-watermark tracer follow an event-time column
through stream-static joins and other binary nodes that keep it.
**Compatibility:** Joins whose next stateful operator reads the unbounded
input's event time keep holding the output watermark back for that input.
**Risks:** Downstream operators behind stream-static joins that read a
bounded input's event time receive a higher watermark than in this PR and evict
and finalize again as on the base branch, and older checkpoints of those
queries resume; reverting the change restores the stall and the rejection.
**Constraints:** Keep stopping at stateful operators, event-time watermark
nodes and UpdateEventTimeColumnExec, and keep holding back both inputs when the
traced attribute cannot be followed into exactly one child. Keep the V4
first-batch reset for joins with a stream-stream join below them.
**Exclusions:**
- Operators that read the unbounded input's event time, whose silent stall
is the open reviewer decision on a query-start error.
**Success:** Behind a stream-static join, the join's output watermark
follows the inputs whose event time the next stateful operator reads, as it
does without the stream-static join. A consumer whose event-time column the
tracer still cannot follow keeps the join holding back both inputs.
**Verification:**
- **Regression:** A one-directional stream-stream join followed by a
stream-static join and an append-mode window aggregation over the bounded
input's event time emits each window once the watermark passes it, and a
stream-stream left outer join in that position emits its unmatched rows padded
with nulls, as on the base branch.
- **Behavior:** With the same stream-static join, an aggregation over the
unbounded input's event time still holds the join's output watermark at 0.
- **Compatibility:** An older-marker checkpoint of the bounded-consumer
query behind a stream-static join resumes while the unbounded-consumer variant
is still rejected, and the first batch of a run of a V4 join with a
stream-stream join below it still has no scan start.
##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinRangeEvictionSuite.scala:
##########
@@ -0,0 +1,183 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.streaming
+
+import org.apache.logging.log4j.Level
+
+import org.apache.spark.sql.Row
+import org.apache.spark.sql.catalyst.analysis.StreamingJoinHelper
+import
org.apache.spark.sql.execution.streaming.operators.stateful.join.StreamingSymmetricHashJoinExec
+import org.apache.spark.sql.execution.streaming.runtime.MemoryStream
+import org.apache.spark.sql.execution.streaming.state.RocksDBStateStoreProvider
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.tags.SlowSQLTest
+
+@SlowSQLTest
+class StreamingJoinRangeEvictionSuite extends StreamTest {
+ import testImplicits._
+
+ private def withJoinConf(version: Int)(f: => Unit): Unit = {
+ withSQLConf(
+ SQLConf.STREAMING_JOIN_STATE_FORMAT_VERSION.key -> version.toString,
+ SQLConf.STATE_STORE_PROVIDER_CLASS.key ->
classOf[RocksDBStateStoreProvider].getName,
+ SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> "false")(f)
+ }
+
+ // V3 shares V2's eviction code. BETWEEN is replaced by the conjunction
before planning, so it
+ // only adds coverage for the outer-join watermark check during analysis.
+ for {
+ version <- Seq(2, 4)
+ joinType <- Seq("inner", "left_outer", "right_outer")
+ shape <- Seq("between", "conjunction", "upper", "interval", "downstream")
+ if shape != "between" || joinType != "inner"
+ } {
+ test(s"range eviction uses bounded timestamp, V$version $joinType $shape")
{
+ withJoinConf(version) {
+ val leftInput = MemoryStream[(Int, Long, Long)]
+ val rightInput = MemoryStream[(Int, Long)]
+ val left = leftInput.toDF().toDF("leftKey", "start", "end")
+ .select($"leftKey", timestamp_seconds($"start").as("leftTime"),
+ timestamp_seconds($"end").as("expiry"))
+ .withWatermark("leftTime", "60 seconds")
+ val right = rightInput.toDF().toDF("rightKey", "time")
+ .select($"rightKey", timestamp_seconds($"time").as("rightTime"))
+ .withWatermark("rightTime", "60 seconds")
+ val range = shape match {
+ case "between" | "downstream" => "rightTime BETWEEN leftTime AND
expiry"
+ case "conjunction" => "rightTime >= leftTime AND rightTime <= expiry"
+ case "interval" => "rightTime BETWEEN leftTime AND leftTime +
INTERVAL 10 MINUTES"
+ case _ => "rightTime <= expiry"
+ }
+ val condition = expr(s"leftKey = rightKey AND $range")
+ val joined = if (joinType == "right_outer") {
+ right.join(left, condition, joinType)
+ } else {
+ left.join(right, condition, joinType)
+ }
+ val output = joined.select($"leftKey", $"leftTime",
+ $"rightTime".cast("long").as("matchTime"))
+ val deduplicated = if (shape == "downstream") {
+ output.dropDuplicates("leftKey", "matchTime")
+ } else {
+ output
+ }
+ val result = deduplicated.select($"leftKey", $"matchTime",
$"leftTime".cast("long"))
+ val matched = Row(1, 460L, 100L)
+ val unmatched = Row(2, null, 100L)
+ testStream(result)(
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (1, 100L, 700L), (2, 100L, 700L)),
AddData(rightInput, (9, 100L)))),
+ CheckNewAnswer(),
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (8, 400L, 1000L)), AddData(rightInput, (9,
400L)))),
+ CheckNewAnswer(),
+ AddData(rightInput, (9, 400L)),
+ // The watermark has passed the start time, but the interval has not
expired.
+ CheckNewAnswer(),
+ Execute { query =>
+ val join = query.lastExecution.executedPlan.collectFirst {
+ case j: StreamingSymmetricHashJoinExec => j
+ }.get
+ assert(join.eventTimeWatermarkForEviction.contains(340000L))
+ if (shape != "interval") {
+ assert(join.produceOutputWatermark(340000L).contains(0L))
+ }
+ },
+ AddData(rightInput, (1, 460L)),
+ CheckNewAnswer(matched),
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (8, 1000L, 1600L)), AddData(rightInput, (9,
1000L)))),
+ CheckNewAnswer(),
+ AddData(rightInput, (9, 1100L)),
+ CheckNewAnswer((if (joinType != "inner") Seq(unmatched) else
Seq.empty): _*)
+ )
+ }
+ }
+ }
+
+ for {
+ version <- Seq(2, 3, 4)
+ joinType <- Seq("left_outer", "right_outer")
+ } {
+ test(s"range eviction includes newly admitted expired values, V$version
$joinType") {
+ withJoinConf(version) {
+ val leftInput = MemoryStream[(Int, Long, Long)]
+ val rightInput = MemoryStream[(Int, Long)]
+ val left = leftInput.toDF().toDF("leftKey", "start", "end")
+ .select($"leftKey", timestamp_seconds($"start").as("leftTime"),
+ timestamp_seconds($"end").as("expiry"))
+ .withWatermark("leftTime", "60 seconds")
+ val right = rightInput.toDF().toDF("rightKey", "time")
+ .select($"rightKey", timestamp_seconds($"time").as("rightTime"))
+ .withWatermark("rightTime", "60 seconds")
+ val condition = expr("leftKey = rightKey AND rightTime <= expiry")
+ val joined = if (joinType == "right_outer") {
+ right.join(left, condition, joinType)
+ } else {
+ left.join(right, condition, joinType)
+ }
+ val result = joined.select($"leftKey", $"rightKey",
$"leftTime".cast("long"))
+ testStream(result)(
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (8, 100L, 700L)), AddData(rightInput, (9,
100L)))),
+ CheckNewAnswer(),
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (8, 400L, 1000L)), AddData(rightInput, (9,
400L)))),
+ CheckNewAnswer(),
+ AddData(rightInput, (9, 400L)), CheckNewAnswer(),
+ // The start passes late filtering, but expiry is below the previous
eviction cutoff.
+ AddData(leftInput, (3, 460L, 200L)), CheckNewAnswer(Row(3, null,
460L)),
+ AddData(rightInput, (9, 500L)), CheckNewAnswer())
+ }
+ }
+ }
+
+ for (bound <- Seq("leftTime > rightTime + rightDelay",
Review Comment:
**Nit (P3):** In this V2 inner join only the eviction-predicate and
output-watermark derivations solve the condition: solving leftTime against the
whole right input stops at the occurrence check, because rightTime and
rightDelay are both right columns, and solving rightTime finds a positive term
and returns early. No solve substitutes the watermark and evaluates, so
removing the `exprWithWatermarkSubstituted.references.nonEmpty` guard leaves
this case passing, and the base branch logs nothing for this query either. Only
the CAST case and the catalyst test give a failure signal. The V4 range scan is
the caller that can reach the guard with this conjunct, and only when another
conjunct gives a side a value-eviction predicate, so running this case in state
format 4 with a conjunct such as `leftTime < rightTime + INTERVAL 1 HOUR`,
keeping its expected matches, would let the right joiner's range-scan solve
reach the guard.
**Verification:**
- **Regression:** With the references guard in the solver removed, the
integration case for a bound shifted by a column of the other input fails
because the solver logs an extraction error, and it passes with the guard in
place.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala:
##########
@@ -630,6 +650,124 @@ class IncrementalExecution(
watermarkPropagator.propagate(currentBatchId, plan,
watermarkForCurrBatch)
}
+ /**
+ * Find, for each stateful operator that applies its input watermark to an
event-time column,
+ * which stream-stream join inputs' event times that column carries. The
walk follows the
+ * column down through nodes that pass it on unchanged, to the same
position in every input
+ * of a union, and through windows built from it, which end after it. It
stops at a join, at
+ * another operator that writes state or sets an event time, and at any
node it does not
+ * recognize; a join that no traced column reaches holds back for both
inputs.
+ */
+ private def joinWatermarkConsumers(plan: SparkPlan):
Seq[JoinWatermarkConsumer] = {
+ def eventTime(output: Seq[Attribute]): Option[Attribute] =
+ output.find(_.metadata.contains(EventTimeWatermark.delayKey))
+
+ // A time or session window built from one column, plus constants, ends
after that column.
+ def windowSource(window: Attribute, expression: Expression):
Option[Attribute] = {
+ val isWindow = window.metadata.contains(TimeWindow.marker) ||
+ window.metadata.contains(SessionWindow.marker)
+ expression.references.toSeq match {
+ case Seq(source) if isWindow => Some(source)
+ case _ => None
+ }
+ }
+
+ def passThrough(child: SparkPlan, attribute: Attribute): Seq[(Long,
JoinSide, Attribute)] =
+ child.output.find(_.exprId ==
attribute.exprId).toSeq.flatMap(findJoinSides(child, _))
+
+ def findJoinSides(
+ node: SparkPlan,
+ attribute: Attribute): Seq[(Long, JoinSide, Attribute)] = {
+ node match {
+ case j: StreamingSymmetricHashJoinExec =>
+ val side = if (eventTime(j.left.output).exists(_.exprId ==
attribute.exprId)) {
+ Some(LeftSide)
+ } else if (eventTime(j.right.output).exists(_.exprId ==
attribute.exprId)) {
+ Some(RightSide)
+ } else {
+ None
+ }
+ j.stateInfo.map(_.operatorId).zip(side).map { case (id, s) => (id,
s, attribute) }
+ .toSeq
+ case p: ProjectExec =>
+ p.projectList.find(_.exprId == attribute.exprId).toSeq.flatMap {
+ case a: Attribute => passThrough(p.child, a)
+ case Alias(a: Attribute, _) => passThrough(p.child, a)
+ case alias: Alias =>
+ windowSource(alias.toAttribute,
alias.child).toSeq.flatMap(passThrough(p.child, _))
+ case _ => Nil
+ }
+ case e: ExpandExec =>
+ // A sliding window is one projection per window; each must carry
the same column.
+ val index = e.output.indexWhere(_.exprId == attribute.exprId)
+ val traced = e.projections.map { projection =>
+ projection.lift(index).toSeq.flatMap {
+ case a: Attribute => passThrough(e.child, a)
+ case expression =>
+ windowSource(e.output(index),
expression).toSeq.flatMap(passThrough(e.child, _))
+ }
+ }
+ if (traced.nonEmpty && traced.forall(_.nonEmpty) &&
traced.distinct.size == 1) {
+ traced.head
+ } else {
+ Nil
+ }
+ case u: UnionExec =>
+ val index = u.output.indexWhere(_.exprId == attribute.exprId)
+ if (index < 0) Nil else u.children.flatMap(c => findJoinSides(c,
c.output(index)))
+ case _: StateStoreWriter | _: EventTimeWatermarkExec | _:
UpdateEventTimeColumnExec =>
+ Nil
+ case u: UnaryExecNode if u.output.exists(_.exprId ==
attribute.exprId) =>
+ passThrough(u.child, attribute)
+ case _ => Nil
+ }
+ }
+
+ // The inputs whose event-time column each operator compares with its
input watermark.
+ def watermarkedInputs(node: SparkPlan): Seq[SparkPlan] = node match {
+ case _: StateStoreSaveExec | _: StatefulStreamlineAggregateExec |
+ _: SessionWindowStateStoreSaveExec | _: StreamingDeduplicateExec |
+ _: StreamingDeduplicateWithinWatermarkExec | _:
StreamingSymmetricHashJoinExec =>
+ node.children
+ case f: FlatMapGroupsWithStateExec if f.timeoutConf ==
EventTimeTimeout => Seq(f.child)
+ case f: FlatMapGroupsInPandasWithStateExec if f.timeoutConf ==
EventTimeTimeout =>
Review Comment:
A follow-up is fine. The two PySpark arms mirror the JVM arms that
StreamingJoinOutputWatermarkSuite covers, and if either stopped matching, the
join would only hold back its output watermark for both inputs rather than
return a wrong result, so this does not need to block the PR. Please link the
follow-up JIRA here when you file it.
<!-- SPARK_DEV_REVIEW_REPLY
{"feedback_id":"inline:4537966938","thread_id":"inline:4537966938","verdict_sha256":"44ec2e248ca3b5ce860546a0fb3569712d9cbf00026b9aabb754f633dfb154a9"}
-->
--
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]