HeartSaVioR commented on code in PR #60279:
URL: https://github.com/apache/spark/pull/60279#discussion_r4546990269
##########
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:
> [!NOTE]
> **DISCLAIMER:** This comment was written by an LLM: Claude Opus 5.5
(`claude-opus-5-5`, 1M context), running as an SP2K agent on behalf of
@HeartSaVioR.
Thanks. We agree that this defect is real at this step. It is an in-between
state of the stack: #60283 (SPARK-61348, step 5) rejects this shape at
analysis, names the side, and asks the user to project the column to TIMESTAMP
before the join. We keep that check in #60283. Moving it here would pull most
of SPARK-61348's admission change into step 1, and the steps in between would
need rework. Instead, this PR now has a TODO at the eviction candidates. It
names SPARK-61348 and says that an outer join bounded only through such a cast
keeps its unmatched rows until that change lands. The PR description will say
the same. Do you agree that this is acceptable as an in-between state of the
stack?
<!-- sp2k-review3 reply 4537966815 -->
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala:
##########
@@ -602,8 +615,15 @@ class IncrementalExecution(
// The prevOffsetSeqMetadata.isDefined check guards against the first
batch, where
// watermark propagation yields Some(0) for late events even though no
state has been
// evicted yet, which would incorrectly skip entries at timestamp 0.
+ //
+ // On the first batch after restoring a checkpoint with older join
watermark semantics,
+ // the late-events watermark comes from re-simulating the previous
batch with this
+ // version's output watermarks. It can be above the watermark that the
older version
+ // evicted with, for example when this version leaves an unbounded
input out of an
+ // upstream join's output watermark. Scan from the start once in that
batch.
val prevBatchLateEventsWm =
- if (prevOffsetSeqMetadata.isDefined &&
allowMultipleStatefulOperators) {
+ if (prevOffsetSeqMetadata.isDefined &&
allowMultipleStatefulOperators &&
+ !isFirstBatchWithOlderJoinWatermarkSemantics) {
Review Comment:
> [!NOTE]
> **DISCLAIMER:** This comment was written by an LLM: Claude Opus 5.5
(`claude-opus-5-5`, 1M context), running as an SP2K agent on behalf of
@HeartSaVioR.
Thanks, good catch. Fixed in
[c984d5cd38b](https://github.com/apache/spark/pull/60279/commits/c984d5cd38be5c8c24dd2120235af9ceb2db4dfc).
On the first batch of every run, a V4 join that has another stream-stream join
below it now gets no scan start. That batch scans the index from the start, so
it evicts the rows the previous run kept and an outer join emits them with
nulls. A V4 join with no stream-stream join below it keeps its scan start. The
comment at the reset now names both cases. A new test chains two V4 joins with
a stream-static left outer join between them, removes that join between runs,
and checks that the downstream left outer join emits the buffered impression
with nulls in the first batch. Without the fix, that row is never emitted.
<!-- sp2k-review3 reply 4537966830 -->
##########
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))
+ }
+ candidates.iterator.flatMap { attribute =>
+ StreamingJoinHelper.getStateValueWatermark(AttributeSet(Seq(attribute)),
+ AttributeSet(otherInputAttributes), condition,
eventWatermark).map(attribute -> _)
+ }.take(1).toSeq.headOption
+ }
+
+ /**
+ * 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 its event
time:
+ * `consumedSides` names the inputs whose event time such an operator reads,
both when the
+ * operator cannot be traced and none when no stateful operator follows. 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.
+ */
+ private[sql] def isWatermarkCheckpointCompatible(
+ leftAttributes: Seq[Attribute],
+ rightAttributes: Seq[Attribute],
+ leftKeys: Seq[Expression],
+ 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
+ }
+ }
+
+ def ownEventTimeKeyOrdinal(keys: Seq[Expression], eventTime: Attribute):
Option[Int] = {
+ keys.zipWithIndex.collectFirst {
+ case (key: NamedExpression, index)
+ if key.metadata.contains(delayKey) &&
key.semanticEquals(eventTime) => 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 = ownEventTimeKeyOrdinal(leftKeys, leftEventTime.head)
+ val rightOrdinal = ownEventTimeKeyOrdinal(rightKeys, rightEventTime.head)
+ val alignedOwnEventTimeKeys = leftOrdinal.isDefined && leftOrdinal ==
rightOrdinal &&
+ leftOrdinals == leftOrdinal.toSeq && rightOrdinals ==
rightOrdinal.toSeq
+ alignedOwnEventTimeKeys || 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]]), and each event
+ * time either gets a range bound or gets none and is not in
`consumedSides`. 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 event time: older versions evicted such keys at the unshifted
watermark. Time windows
+ * are excluded: older versions derived an ordering bound for them that this
version removes.
+ */
+ private def isOwnEventTimeIntervalJoin(
+ leftAttributes: Seq[Attribute],
+ rightAttributes: Seq[Attribute],
+ leftKeys: Seq[Expression],
+ rightKeys: Seq[Expression],
+ condition: Option[Expression],
+ leftEventTime: Attribute,
+ rightEventTime: Attribute,
+ consumedSides: Set[JoinSide]): Boolean = {
+ def conjuncts(e: Expression): Seq[Expression] = e match {
+ case And(left, right) => conjuncts(left) ++ conjuncts(right)
+ case other => Seq(other)
+ }
+ def eventTimeOf(e: Expression): Option[Attribute] =
+ Seq(leftEventTime,
rightEventTime).find(StreamingJoinHelper.isConstantOffsetOf(e, _))
+ def comparesInputs(a: Expression, b: Expression): Boolean =
+ (eventTimeOf(a), eventTimeOf(b)) match {
+ case (Some(x), Some(y)) => !x.semanticEquals(y)
+ case _ => false
+ }
+ // The solver reads bounds only from these conjunct shapes; other
conjuncts give no bound in
+ // either version.
+ val conditionIsInterval = condition.toSeq.flatMap(conjuncts).forall {
Review Comment:
> [!NOTE]
> **DISCLAIMER:** This comment was written by an LLM: Claude Opus 5.5
(`claude-opus-5-5`, 1M context), running as an SP2K agent on behalf of
@HeartSaVioR.
Thanks. Fixed in
[c984d5cd38b](https://github.com/apache/spark/pull/60279/commits/c984d5cd38be5c8c24dd2120235af9ceb2db4dfc).
The interval check now also accepts a comparison that references both inputs
when no version derives a bound from it. The check runs both solves on that
comparison: the older one, over every column of each input, and this version's,
over one candidate column at a time. It judges each half of a BETWEEN on its
own. So `leftPrice >= rightPrice` and a month interval no longer block the
restart. A comparison within one input still blocks it, including a comparison
with a constant. The month-interval join now resumes when nothing after the
join reads leftTime, and is still rejected when a later operator does. The
migration guide no longer gives a month interval as an example of a rejected
join. New tests cover the check directly, a comparison of other columns of both
inputs, and the month interval with each event time read downstream.
<!-- sp2k-review3 reply 4537966838 -->
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala:
##########
@@ -721,14 +859,58 @@ 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.
The nearest one
+ // reads the inputs that the tracer names, or both inputs when it
cannot be traced.
+ val joinsBelowStatefulOperators = planWithStateOpId.collect {
+ case s: StatefulOperator => 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:
> [!NOTE]
> **DISCLAIMER:** This comment was written by an LLM: Claude Opus 5.5
(`claude-opus-5-5`, 1M context), running as an SP2K agent on behalf of
@HeartSaVioR.
Thanks. Fixed in
[c984d5cd38b](https://github.com/apache/spark/pull/60279/commits/c984d5cd38be5c8c24dd2120235af9ceb2db4dfc).
The restart check now counts a join's inputs only below a stateful operator
that uses its input watermark: one with an event-time column in an input, one
with event-time timeouts, or transformWithState in any time mode, because its
code can read the watermark. A key-only or one-directional join followed only
by an update-mode count on a key now resumes, and so does the key-only join
followed by deduplication over cast event times. That test now deduplicates
over leftTime itself, so it stays rejected. New tests check that a window count
over leftTime, or a processing-time transformWithState, after a key-only join
is still rejected. The migration guide now says which operators count.
<!-- sp2k-review3 reply 4537966847 -->
--
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]