spark-test commented on code in PR #60280:
URL: https://github.com/apache/spark/pull/60280#discussion_r4579273017
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -17,36 +17,395 @@
package org.apache.spark.sql.catalyst.analysis
+import java.util.Locale
+
import scala.util.control.NonFatal
import org.apache.spark.internal.Logging
import org.apache.spark.internal.LogKeys._
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.logical.{EventTimeWatermark,
Expand, Filter, Join, LogicalPlan, Project, SubqueryAlias, 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
+/**
+ * Pairs of attributes `(key, eventTime)` where `key` is a copy of
`eventTime`, or a tumbling or
+ * sliding time window over it, in every row of every stream-stream join input
that outputs both.
+ * See [[StreamingJoinHelper.findEventTimeCopies]].
+ */
+case class EventTimeCopies(pairs: Set[(ExprId, ExprId)]) {
+ def isCopyOf(key: Expression, eventTime: Attribute): Boolean = key match {
+ case a: Attribute => pairs.contains((a.exprId, eventTime.exprId))
+ case _ => false
+ }
+
+ def keys: Set[ExprId] = pairs.map(_._1)
+}
+
+object EventTimeCopies {
+ val empty: EventTimeCopies = EventTimeCopies(Set.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.
+ */
+ def getStateKeyWatermarkOrdinal(
+ keys: Seq[Expression],
+ inputAttributes: Seq[Attribute],
+ eventTimeCopies: EventTimeCopies = EventTimeCopies.empty): Option[Int] =
{
+ getEventTimeKeyOrdinal(keys, inputAttributes, eventTimeCopies).orElse {
+ keys.indices.find(getStateKeyWatermark(keys, inputAttributes, _,
Some(0L)).isDefined)
+ }
+ }
+
+ /**
+ * Find the equality key that is this input's event-time column itself, or
else one that
+ * `eventTimeCopies` names as a copy of that column or a time window over
it. Such a key is
+ * above the watermark in every row that passes late filtering, as the
column is: a window
+ * ends after every time it contains.
+ */
+ def getEventTimeKeyOrdinal(
+ keys: Seq[Expression],
+ inputAttributes: Seq[Attribute],
+ eventTimeCopies: EventTimeCopies = EventTimeCopies.empty): 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 =>
+ Seq(keys.indexWhere(_.semanticEquals(eventTime)),
+ keys.indexWhere(eventTimeCopies.isCopyOf(_, eventTime))).find(_ >= 0)
+ }
+ }
+
+ /**
+ * In legacy mode
(spark.sql.streaming.statefulOperator.allowMultiple=false), an input can keep
+ * its event time and a copy of it or a time window over it, all
watermarked, and it filters
+ * late rows by the first of them. Find, for each stream-stream join input
in `plan`, which of
+ * its watermarked columns are a copy of, or a tumbling or sliding time
window over, another of
+ * them. A pair counts only if every join input that outputs both columns
builds it that way,
+ * so the result does not depend on how a physical join is matched to its
logical one: the
+ * physical inputs output the same values under the same expression IDs, or
fewer columns.
+ */
+ def findEventTimeCopies(plan: LogicalPlan): EventTimeCopies = {
+ val verdicts = 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
+ for (key <- watermarked; eventTime <- watermarked if key != eventTime)
yield {
+ (key, eventTime) -> isCopyOrWindowOf(input, key, eventTime,
allowWindow = true)
+ }
+ }
+ val rejected = verdicts.collect { case (pair, false) => pair }.toSet
+ EventTimeCopies(verdicts.collect { case (pair, true) if !rejected(pair) =>
pair }.toSet)
+ }
+
+ /**
+ * Whether `key` is `eventTime`, or a tumbling or sliding time window over
it when
+ * `allowWindow`, in every row of `plan`. The walk follows both columns down
by expression ID
+ * through nodes that pass values on unchanged, to the same positions in
every input of a union,
+ * and to the node that [[TimeWindowResolution.TIME_WINDOW_SOURCE_TAG]]
marks as building the
+ * window from an attribute, which must then be a copy of `eventTime`. Any
other node, or any
+ * other expression, such as a shifted time, a session window or a window
over another column,
+ * gives false.
*/
- def isWatermarkInJoinKeys(plan: LogicalPlan): Boolean = {
- plan match {
- case ExtractEquiJoinKeys(_, leftKeys, rightKeys, _, _, _, _, _) =>
- (leftKeys ++ rightKeys).exists {
- case a: AttributeReference =>
a.metadata.contains(EventTimeWatermark.delayKey)
- case _ => false
+ private def isCopyOrWindowOf(
+ plan: LogicalPlan,
+ key: ExprId,
+ eventTime: ExprId,
+ allowWindow: Boolean): Boolean = {
+ def passedOn(e: Expression): Option[ExprId] = e match {
+ case a: Attribute => Some(a.exprId)
+ case Alias(a: Attribute, _) => Some(a.exprId)
+ case _ => None
+ }
+ // The time column that the node tagged by the window rewrite builds
`window` from.
+ def timeColumnOf(node: LogicalPlan, window: ExprId): Option[ExprId] =
+ node.getTagValue(TimeWindowResolution.TIME_WINDOW_SOURCE_TAG).collect {
+ case (id, timeColumn) if allowWindow && id == window => timeColumn
+ }
+ if (key == eventTime) {
+ true
+ } else {
+ plan match {
+ case p: Project =>
+ val keyEntry = p.projectList.find(_.exprId == key)
+ val eventTimeEntry = p.projectList.find(_.exprId == eventTime)
+ (keyEntry, eventTimeEntry.flatMap(passedOn)) match {
+ case (Some(entry), Some(childEventTime)) => passedOn(entry) match {
+ case Some(childKey) =>
+ isCopyOrWindowOf(p.child, childKey, childEventTime,
allowWindow)
+ case None => timeColumnOf(p, key).exists { timeColumn =>
+ entry.references.map(_.exprId).toSet == Set(timeColumn) &&
+ isCopyOrWindowOf(p.child, timeColumn, childEventTime,
allowWindow = false)
+ }
+ }
+ case _ => false
+ }
+ case e: Expand =>
+ // The rewrite of a sliding window puts one window per projection
beside the child's
+ // columns, which every projection passes on.
+ val keyIndex = e.output.indexWhere(_.exprId == key)
+ val eventTimeIndex = e.output.indexWhere(_.exprId == eventTime)
+ lazy val childEventTimes = e.projections.map(p =>
passedOn(p(eventTimeIndex))).distinct
+ keyIndex >= 0 && eventTimeIndex >= 0 && childEventTimes.size == 1 &&
+ childEventTimes.head.isDefined && timeColumnOf(e, key).exists {
timeColumn =>
+ e.projections.forall(_(keyIndex).references.map(_.exprId).toSet
== Set(timeColumn)) &&
+ isCopyOrWindowOf(e.child, timeColumn, childEventTimes.head.get,
+ allowWindow = false)
+ }
+ case u: Union =>
+ val keyIndex = u.output.indexWhere(_.exprId == key)
+ val eventTimeIndex = u.output.indexWhere(_.exprId == eventTime)
+ keyIndex >= 0 && eventTimeIndex >= 0 && u.children.forall { child =>
+ isCopyOrWindowOf(child, child.output(keyIndex).exprId,
+ child.output(eventTimeIndex).exprId, allowWindow)
+ }
+ case _: Filter | _: SubqueryAlias | _: EventTimeWatermark =>
+ isCopyOrWindowOf(plan.children.head, key, eventTime, allowWindow)
+ case _ => false
Review Comment:
Thanks, the shapes from this thread now keep their bound. On your question:
there is a bound for the copy that holds whichever column the planned input
filters late rows by, so it needs no start-time check. A row passes late
filtering on a window of length D over t only if the window ends above the
watermark, so its t, and therefore its copy c, is above the watermark less D;
when t survives pruning, c is above the watermark itself. Bounding the other
input's state by c at the watermark less D is therefore safe in both cases. For
a sliding window D is the window duration, and for a session window with a
constant gap it is the gap; a window whose length is not constant can keep
today's rejection. The cost is that, when t survives, the other input keeps its
rows up to D longer and its unmatched rows come out up to D later. This review
raises the current rejection of these joins as a separate issue.
<!-- SPARK_DEV_REVIEW_REPLY
{"feedback_id":"inline:4577114370","thread_id":"inline:4577114370","verdict_sha256":"31e22ee7b64dde53ffc1ccf9b55bb1981fc8ac07695538d9cdafbd26fb70df00"}
-->
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -705,33 +715,145 @@ object UnsupportedOperationChecker extends Logging {
plan = operator)
}
- private def checkForStreamStreamJoinWatermark(join: Join): Unit = {
- val watermarkInJoinKeys = StreamingJoinHelper.isWatermarkInJoinKeys(join)
-
- // Check if the nullable side has a watermark, and there's a range
condition which
- // implies a state value watermark on the first side.
- val hasValidWatermarkRange = join.joinType match {
- case LeftOuter | LeftSemi => StreamingJoinHelper.getStateValueWatermark(
- join.left.outputSet, join.right.outputSet, join.condition,
Some(1000000)).isDefined
- case RightOuter => StreamingJoinHelper.getStateValueWatermark(
- join.right.outputSet, join.left.outputSet, join.condition,
Some(1000000)).isDefined
- case FullOuter =>
- Seq((join.left.outputSet, join.right.outputSet),
- (join.right.outputSet, join.left.outputSet)).exists {
- case (attributesToFindStateWatermarkFor,
attributesWithEventWatermark) =>
-
StreamingJoinHelper.getStateValueWatermark(attributesToFindStateWatermarkFor,
- attributesWithEventWatermark, join.condition,
Some(1000000)).isDefined
- }
+ private def checkForStreamStreamJoinWatermark(
+ join: Join,
+ legacyKeys: Option[LegacyEventTimeKeys]): Unit = {
+ val keys = ExtractEquiJoinKeys.unapply(join)
+ val leftKeys = keys.map(_._2).getOrElse(Nil)
+ val rightKeys = keys.map(_._3).getOrElse(Nil)
+
+ // TODO(SPARK-61347): this accepts a range bound on an input without its
own watermark,
+ // which eviction does not finalize yet.
+ // TODO(SPARK-61348): this also accepts a range bound on a column that is
not TIMESTAMP,
+ // which eviction never finalizes.
+ // TODO(SPARK-61349): this also accepts a bound that uses only constants,
which does not
+ // follow the other input's watermark and so cannot finalize unmatched
state.
+ def canEvictState(
+ stateInput: LogicalPlan,
+ otherInput: LogicalPlan,
+ otherKeys: Seq[Expression]): Boolean = {
+ val eventTime =
otherInput.output.find(_.metadata.contains(EventTimeWatermark.delayKey))
Review Comment:
**Blocking (P1):** In the default mode
(`spark.sql.streaming.statefulOperator.allowMultiple=true`), `canEvictState`
takes the other input's first watermarked column of the analyzed plan as its
event time: `getEventTimeKeyOrdinal` counts only a key equal to it, and the
range solver is given only that column. Reading the code with each input built
as `withWatermark("t", ...).withColumn("w", window($"t", "10 seconds"))`, a
left outer join on `lk = rk AND lw = rw` that selects `lk`, `lw` and the value
columns fails analysis here, because `rt` is the right input's first
watermarked column and no right key equals it. The planned query is fine:
`ColumnPruning` removes `t` from each join input, `findEventTimeColumn` then
sees `w` as the only watermarked column, and both the base branch and this
head's execution evict at `w.end`, which drops nothing a later row can match.
So these joins ran correctly before and now fail, and with
`spark.sql.streaming.join.checkFinalization.enabled=false` t
hey run and evict correctly but log a warning that their state is kept without
bound. A copy of the event time appended after it behaves the same way. In
legacy mode the same rule rejects a range condition on a later watermarked copy
of the event time, such as `lt BETWEEN rc - INTERVAL 5 SECONDS AND rc +
INTERVAL 5 SECONDS` with `rc` a copy of `rt`, which the base branch admitted
and evicted correctly. When the planned input keeps both `t` and `w`, execution
fails with `MULTIPLE_EVENT_TIME_COLUMNS` on both branches, so only the pruned
shape regresses.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60280#discussion_r4537719964).
See **Shared repair plan 1** in the review body.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -17,36 +17,500 @@
package org.apache.spark.sql.catalyst.analysis
+import java.util.Locale
+
import scala.util.control.NonFatal
import org.apache.spark.internal.Logging
import org.apache.spark.internal.LogKeys._
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.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
+/**
+ * In legacy mode (spark.sql.streaming.statefulOperator.allowMultiple=false),
the watermarked
+ * equality keys that do not count as their input's event time. See
+ * [[StreamingJoinHelper.findLegacyEventTimeKeys]].
+ */
+case class LegacyEventTimeKeys(rejected: Set[ExprId]) {
+ /** Whether the key carries a watermark and is not rejected, so it bounds as
in Spark 4.3. */
+ def isEventTimeKey(key: Expression): Boolean = key match {
+ case n: NamedExpression => n.metadata.contains(delayKey) &&
!rejected(n.exprId)
+ case _ => false
+ }
+}
+
/**
* 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.
+ */
+ def getStateKeyWatermarkOrdinal(
+ keys: Seq[Expression],
+ inputAttributes: Seq[Attribute],
+ legacyKeys: Option[LegacyEventTimeKeys] = None): Option[Int] = {
+ getEventTimeKeyOrdinal(keys, inputAttributes, legacyKeys).orElse {
+ keys.indices.find(getStateKeyWatermark(keys, inputAttributes, _,
Some(0L)).isDefined)
+ }
+ }
+
+ /**
+ * Find the equality key that is this input's event-time column itself, or
else, in legacy
+ * mode, a watermarked key that `legacyKeys` does not reject. Spark 4.3 used
every watermarked
+ * key so; see [[findLegacyEventTimeKeys]].
+ */
+ def getEventTimeKeyOrdinal(
+ keys: Seq[Expression],
+ inputAttributes: Seq[Attribute],
+ legacyKeys: Option[LegacyEventTimeKeys] = 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 =>
+ Seq(keys.indexWhere(_.semanticEquals(eventTime)),
+ keys.indexWhere(key =>
legacyKeys.exists(_.isEventTimeKey(key)))).find(_ >= 0)
+ }
+ }
+
+ /**
+ * In legacy mode
(spark.sql.streaming.statefulOperator.allowMultiple=false), an input can keep
+ * several watermarked columns, such as its event time and a copy of it or a
time window over
+ * it, and it filters late rows by the first of them. Spark 4.3 counted
every watermarked
+ * equality key as the input's event time, which is right when the key is
never below the
+ * column that filters late rows. Keep doing so, and reject only a key that
`plan` shows some
+ * row can hold below a watermarked column before it, because the planned
input filters late
+ * rows by one of those: the optimizer can prune the ones before it.
Evicting by such a key
+ * would drop state that later rows still match. A key rejected by one
stream-stream join input
+ * is rejected for every join, so the analysis check and execution, which
read the result by
+ * expression ID on the analyzed and the planned join, decide the same.
+ */
+ def findLegacyEventTimeKeys(plan: LogicalPlan): LegacyEventTimeKeys = {
+ val rejected = 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.collect {
+ case i if watermarked.take(i).exists { eventTime =>
+ canBeBelow(input, watermarked(i), eventTime, SameValue,
eventTimeIsWindow = false)
+ } => watermarked(i)
+ }
+ }
+ LegacyEventTimeKeys(rejected.toSet)
+ }
+
+ /** How the join input's key relates to the column that [[canBeBelow]]
follows for it. */
+ private sealed trait KeyBound
+ /** The key is that column. */
+ private case object SameValue extends KeyBound
+ /** The key is a time window over that column, which ends at most a window
after it. */
+ private case object WindowEnd extends KeyBound
+ /** The key is at or above that column, by an amount the walk does not know.
*/
+ private case object AtOrAbove extends KeyBound
+ /** Some rows hold the key more than a microsecond below that column. */
+ private case object Below extends KeyBound
+
+ /**
+ * Whether `plan` shows that some row holds the join input's key below the
bound of its column
+ * `eventTime`, which late filtering compares with the watermark: the column
itself, or its end
+ * when `eventTimeIsWindow`. `bound` says how that key relates to the column
`key` of `plan`.
+ * 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 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; and into every input of a union, at the same
positions. Where both reach
+ * the same column, a key below it, or equal to it while the late-filtered
column is a window
+ * over it, can be below. 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.
Everything else gives
+ * false, so such a key keeps the Spark 4.3 behaviour.
+ */
+ private def canBeBelow(
+ plan: LogicalPlan,
+ key: ExprId,
+ eventTime: ExprId,
+ bound: KeyBound,
+ eventTimeIsWindow: Boolean): Boolean = {
+ def outputsBoth(p: LogicalPlan): Boolean =
+ p.output.exists(_.exprId == key) && p.output.exists(_.exprId ==
eventTime)
+ if (key == eventTime) {
+ bound == Below || (eventTimeIsWindow && bound == SameValue)
Review Comment:
**Blocking (P1):** With
`spark.sql.streaming.statefulOperator.allowMultiple=false`, an input `[k, t, w
= window(t, ...), c = t]` joined on `c` reaches this line with the copy as
`SameValue` and `w` as a window over `t`, so `c` is rejected whatever column
pruning later does. When the query reads `t` after the join, the planned input
filters late rows by `t`, `c` equals `t` on every row, and the base branch's
eviction of the other input at `c <= watermark` is exact; the same holds when
pruning removes both `t` and `w`, since the copy then filters late rows itself.
At this head those joins regress: left outer, right outer, full outer and left
semi joins fail analysis (the suite's right outer test asserts this with `lt`
kept), and inner joins keep both inputs' rows for the life of the query. Only
the case where pruning removes `t` but keeps `w` needs care, and even there a
bound exists that needs no start-time check: a row passes late filtering on a
window of length D over `t` only if
the window ends above the watermark W, so its `t`, and its copy, is above W -
D. Bounding the other input's state by the copy at W - D is safe whichever
column filters late rows.
This extends existing discussions
[1](https://github.com/apache/spark/pull/60280#issuecomment-6895263033),
[2](https://github.com/apache/spark/pull/60280#discussion_r4577114370).
See **Shared repair plan 1** in the review body.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -224,98 +236,389 @@ 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] = {
+ 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, legacyKeys)
Review Comment:
**Non-blocking (P2):** `legacyKeys` reaches only this key-branch call. The
value branch passes the other input's whole output to
`getStateValueWatermarkForInput` a few lines below, and the solver substitutes
the watermark for every attribute that carries the delay, including one that
`findLegacyEventTimeKeys` rejects. Reading the code in legacy mode, with the
right input carrying `rs = rt - INTERVAL 20 SECONDS` with `rt`'s watermark
metadata and an inner join on `lk = rk AND lt BETWEEN rs AND rs + INTERVAL 1
HOUR`, the left cutoff becomes the watermark less 1 ms. A right row with `rt`
just above the watermark has `rs` up to 20 seconds below it, and the left rows
it matches were already evicted. With
`spark.sql.streaming.join.checkFinalization.enabled=false` the left outer form
runs and emits those rows padded with nulls too early, while its warning says
the left state is kept without bound. The PR rejects `rs` as an equality key
for exactly this reason, and no TODO names the range
path.
See **Shared repair plan 1** in the review body.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala:
##########
@@ -167,6 +170,26 @@ class IncrementalExecution(
private val allowMultipleStatefulOperators: Boolean =
sparkSession.sessionState.conf.getConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE)
+ // The analysis check computes the same keys from the plan it checks. Both
read the operators
+ // of the query, which every batch's analyzed plan keeps; a batch only puts
each source's data
+ // in place of the source. The walk needs no state from analysis, such as
tags.
+ private lazy val legacyKeys: Option[LegacyEventTimeKeys] =
+ if (allowMultipleStatefulOperators) {
+ None
+ } else {
+ Some(StreamingJoinHelper.findLegacyEventTimeKeys(analyzed))
Review Comment:
**Non-blocking (P2):** `legacyKeys` is computed here from the analyzed plan,
and `LegacyEventTimeKeys.isEventTimeKey` checks the planned join's keys against
it by expression ID. Reading the code with a left input
`withShifted(eventTimeInput(l)).repartition(3).toDF("lk", "lt", "ls")`, so that
`ls = lt - 20 seconds` carries `lt`'s watermark, inner-joined on `lk = rk AND
ls = rt`: `toDF` resolves to a projection that aliases `ls#3` as a new `ls#6`,
the walk follows the repartition and rejects `ls#6`, but
`RemoveRedundantAliases` replaces that alias with `ls#3`, because its name and
metadata match and `CollapseProject` cannot merge it across the repartition.
The planned key `ls#3` is not in the rejected set, so the right state is
evicted at `rt <= watermark` while left rows with `lt` just above the watermark
still look for right rows with `rt = ls` below it. The inner join loses those
matches, and a left outer join on the same key, which passes analysis, emits
those left rows padded w
ith nulls: the base branch's failure that the PR's rule removes when no alias
is involved. The comments on `findLegacyEventTimeKeys` and at this field say
that both readers decide the same, which does not hold for such keys.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60280#discussion_r4577114376).
See **Shared repair plan 1** in the review body.
##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinLegacyEventTimeKeySuite.scala:
##########
@@ -0,0 +1,448 @@
+/*
+ * 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 java.sql.Timestamp
+
+import org.apache.spark.sql.{AnalysisException, DataFrame, Row}
+import org.apache.spark.sql.catalyst.analysis.StreamingJoinHelper
+import org.apache.spark.sql.catalyst.plans.Inner
+import org.apache.spark.sql.catalyst.plans.logical.{Join, JoinHint, Union}
+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
+
+/**
+ * With spark.sql.streaming.statefulOperator.allowMultiple=false, an input
filters late rows by
+ * its first watermarked column. An equality key on a later watermarked column
bounds the other
+ * input's state, as in Spark 4.3, unless the plan shows that some rows of the
input hold the key
+ * below a watermarked column before it.
+ */
+class StreamingJoinLegacyEventTimeKeySuite extends StreamTest {
+ import testImplicits._
+
+ private val legacyMode = SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key ->
"false"
+
+ /** Adds the key column `<side>w` to an input whose event time is `<side>t`.
*/
+ private type KeyBuilder = (DataFrame, String) => DataFrame
+
+ private val tumbling: KeyBuilder =
+ (df, side) => df.withColumn(s"${side}w", window(col(s"${side}t"), "10
seconds"))
+ private val sliding: KeyBuilder =
+ (df, side) => df.withColumn(s"${side}w", window(col(s"${side}t"), "10
seconds", "5 seconds"))
+ private val copy: KeyBuilder = (df, side) => df.withColumn(s"${side}w",
col(s"${side}t"))
+ private val copyThenWindow: KeyBuilder = (df, side) =>
+ df.withColumn(s"${side}c", col(s"${side}t"))
+ .withColumn(s"${side}w", window(col(s"${side}c"), "10 seconds"))
+ private val renamedWindow: KeyBuilder = (df, side) =>
+ df.withColumn(s"${side}x", window(col(s"${side}t"), "10 seconds"))
+ .filter(col(s"${side}k") >= 0)
+ .withColumnRenamed(s"${side}x", s"${side}w")
+ // Each session is [t, t + 10 seconds), as no aggregation merges sessions.
+ private val sessionWindow: KeyBuilder =
+ (df, side) => df.withColumn(s"${side}w", session_window(col(s"${side}t"),
"10 seconds"))
+ // Adds the event time less 20 seconds, in a column that keeps the event
time's watermark.
+ private def withShifted(df: DataFrame, side: String): DataFrame = {
+ val time = s"${side}t"
+ df.select(col("*"),
+ (col(time) - expr("INTERVAL 20 SECONDS")).as(s"${side}s",
df.schema(time).metadata))
+ }
+ // A window over the shifted time. Its end can be at or below the watermark
while the event
+ // time is above.
+ private val shiftedWindow: KeyBuilder = (df, side) =>
+ withShifted(df, side).withColumn(s"${side}w", window(col(s"${side}s"), "10
seconds"))
+ private val shiftedCopy: KeyBuilder = (df, side) =>
+ withShifted(df, side).withColumnRenamed(s"${side}s", s"${side}w")
+ // A window over the shifted time without a watermark, which a window over
an expression drops.
+ private val unwatermarkedWindow: KeyBuilder = (df, side) =>
+ df.withColumn(s"${side}w",
+ window(col(s"${side}t") - expr("INTERVAL 20 SECONDS"), "10 seconds"))
+
+ /** Puts a node that keeps the input's columns between an input and the
join. */
+ private type Through = (DataFrame, String) => DataFrame
+
+ private val throughNodes: Seq[(String, Through)] = Seq(
+ "repartition" -> ((df, _) => df.repartition(3)),
+ "temporary view read from SQL" -> { (df, side) =>
+ df.createOrReplaceTempView(s"legacy_$side")
+ spark.sql(s"SELECT * FROM legacy_$side")
+ },
+ "typed filter" -> ((df, _) => df.filter((r: Row) => !r.isNullAt(0))),
+ "observe" -> ((df, side) => df.observe(s"legacy_$side", count(lit(1)))),
+ "hint" -> ((df, _) => df.hint("broadcast")),
+ "stream-static join" -> { (df, side) =>
+ df.join(Seq(1, 2, 3, 9).toDF("sk"), col(s"${side}k") === $"sk")
+ .select(col(s"${side}k"), col(s"${side}t"), col(s"${side}w"))
+ })
+
+ private def eventTimeInput(memory: MemoryStream[(Int, Int)], side: String):
DataFrame =
+ memory.toDF().toDF(s"${side}k", "time")
+ .select(col(s"${side}k"), timestamp_seconds($"time").as(s"${side}t"))
+ .withWatermark(s"${side}t", "1 second")
+
+ private def keyed(memory: MemoryStream[(Int, Int)], side: String, key:
KeyBuilder): DataFrame =
+ key(eventTimeInput(memory, side), side)
+ .select(col(s"${side}k"), col(s"${side}t"), col(s"${side}w"))
+
+ /** The keys that the shared rule rejects, by column name. */
+ private def rejectedKeys(df: DataFrame): Set[String] = {
+ val plan = df.queryExecution.analyzed
+ val names = plan.flatMap(_.output).map(a => a.exprId -> a.name).toMap
+ StreamingJoinHelper.findLegacyEventTimeKeys(plan).rejected.map(names)
+ }
+
+ private def joinWithRight(left: DataFrame, key: KeyBuilder = tumbling):
DataFrame =
+ left.join(keyed(MemoryStream[(Int, Int)], "r", key), expr("lk = rk AND lw
= rw"))
+
+ Seq(
+ "tumbling window" -> tumbling,
+ "sliding window" -> sliding,
+ "session window" -> sessionWindow,
+ "copy" -> copy,
+ "window over a copy" -> copyThenWindow,
+ "renamed window after a filter" -> renamedWindow).foreach { case (name,
key) =>
+ test(s"$name of the event time after it is not rejected") {
+ assert(rejectedKeys(joinWithRight(keyed(MemoryStream[(Int, Int)], "l",
key), key)).isEmpty)
+ }
+ }
+
+ throughNodes.foreach { case (name, through) =>
+ test(s"window of the event time behind a $name is not rejected") {
+ withTempView("legacy_l", "legacy_r") {
+ val left = through(keyed(MemoryStream[(Int, Int)], "l", tumbling), "l")
+ val right = through(keyed(MemoryStream[(Int, Int)], "r", tumbling),
"r")
+ assert(rejectedKeys(left.join(right, expr("lk = rk AND lw =
rw"))).isEmpty)
+ }
+ }
+ }
+
+ test("window or copy of a time shifted backward is rejected") {
+ val left = shiftedWindow(eventTimeInput(MemoryStream[(Int, Int)], "l"),
"l")
+ // ls is below lt in every row, and lw ends at most 10 seconds after ls.
+ assert(rejectedKeys(joinWithRight(left)) === Set("lw", "ls"))
+ assert(rejectedKeys(joinWithRight(keyed(MemoryStream[(Int, Int)], "l",
shiftedCopy), copy))
+ === Set("lw"))
+ }
+
+ test("window over a time shifted backward is rejected behind a repartition")
{
Review Comment:
**Nit (P3):** The rejecting cases here and in `UnsupportedOperationsSuite`
reach `canBeBelow`'s `true` result only through projections, this repartition
and unions. If the `Expand` or `Join` branch returned `false` outright, a
sliding window over a time shifted backward, or a shifted window behind a
stream-static join, would bound the other input's state again and drop matches,
and every test would still pass, because the sliding-window and stream-static
cases expect no rejection; the session-window steps are in the same position.
In the other direction, no case keeps a forward-shifted watermarked copy, so a
`keyStep` that classified a forward shift as `Below` would make outer joins on
such a copy fail analysis unnoticed. Rejecting cases through each of those
branches, and a case that keeps a forward-shifted copy, would pin them.
See **Shared repair plan 1** in the review body.
##########
docs/streaming/ss-migration-guide.md:
##########
@@ -25,6 +25,118 @@ Please refer [Migration Guide: SQL, Datasets and
DataFrame](../sql-migration-gui
## Upgrading from Structured Streaming 4.3 to 4.4
+- Since Spark 4.4, left outer and left semi stream-stream joins require a
watermark on the
+ right input and a time condition that limits how late a matching right row
can arrive.
+ Right outer joins require the corresponding settings on the left; full outer
joins require
+ them on both sides. An equality key counts as such a time condition when it
is the other
+ input's event time, or that event time shifted by constant intervals, except
a shift backward
+ by months, years, or a day-time interval of 24 hours or more. A key such as
+ `leftTime = rightTime - INTERVAL 1 DAY` or `leftTime = rightTime - INTERVAL
36 HOURS`, or one
+ truncated from the other input's event time, such as
+ `leftTime = CAST(CAST(rightTime AS BIGINT) AS TIMESTAMP)`, does not count,
while
+ `timestampadd` in hours, minutes or seconds does, whatever the amount. When
both inputs
+ have watermarks, a time range condition between the two event times can
bound such a join
+ instead. Some previously accepted queries now fail if these requirements are
not met. Update
+ their watermarks and join conditions using the
+ [join support
table](apis-on-dataframes-and-datasets.html#support-matrix-for-joins-in-streaming-queries).
+ A stateful operator after such a join that uses the other input's event time
also needs that
+ input bounded: for example, a left outer join followed by an append-mode
aggregation over the
+ right event time also needs a watermark on the left input and a time
condition that limits
+ how late a matching left row can arrive: an equality with an exact shift (an
interval under
+ one day, or `timestampadd` in hours, minutes or seconds), or a range
condition in place of a
+ shifted equality. Without them, the join holds back its output
+ watermark, and the query fails at start (see below) because the aggregation
would never emit
+ results.
+
+- Since Spark 4.4, you can set
`spark.sql.streaming.join.checkFinalization.enabled` to `false`
+ to run a stream-stream outer or left semi join that fails the requirement
above, or a query
+ that fails the start-time check for an aggregation after a join, below.
Spark then logs a
+ warning instead of failing the query. Joins that earlier versions also
rejected, such as an
+ outer join without a watermarked equality key or a range condition on a
watermarked event
+ time, still fail. The corrected state eviction cannot be turned
+ off: such a query keeps the state of the input that lacks a bound for the
life of the query,
+ and an outer join never outputs that input's unmatched rows. Because the
corrected eviction
+ changes results and cannot be turned off, these stream-stream join
corrections are made in
+ Spark 4.4.0 and are not backported to earlier releases.
+
+- Spark 4.4 corrects cases where stream-stream equality joins could discard
rows before their
+ matches arrived or output unmatched rows too early. Such joins with a
watermark on only one
+ input now keep the watermarked input's rows for the life of the query,
because the other input
+ has no watermark that bounds them, and hold back the join's output watermark
for that input.
+ An append-mode aggregation over that input's event time then fails at start.
Other stateful
+ operators after the join that use it keep its rows in state and do not emit
results that wait
+ for the watermark, such as event-time timeouts, while update-mode
aggregations and
+ deduplication still emit rows. Add a watermark on the other input to bound
those rows.
+
+- With `spark.sql.streaming.statefulOperator.allowMultiple` set to `false`, an
input of a
+ stream-stream join can keep several watermarked columns, such as its event
time together with a
+ copy of it or a time window over it, and late rows are filtered by whichever
of them comes
+ first. As in earlier versions, an equality key on any watermarked column of
an input bounds the
+ other input's state, so an input built with `withColumn("window",
window($"ts", ...))` is still
Review Comment:
**Nit (P3):** The premise says the key bounds the other input's state, but
the conclusion says the input built with `withColumn("window", window($"ts",
...))` is itself bounded by its window, which holds only when the other input
also keys on a watermarked window and, read alone, describes the self-bounding
this change removes. Wording such as "so a join on the window of an input built
with `withColumn("window", window($"ts", ...))` still bounds the other input's
state by that window" keeps the direction.
**Verification:**
- **Inspection:** Every sentence of the legacy-mode note that names a key
and a bounded state says the key bounds the other input's state.
##########
docs/streaming/ss-migration-guide.md:
##########
@@ -25,6 +25,118 @@ Please refer [Migration Guide: SQL, Datasets and
DataFrame](../sql-migration-gui
## Upgrading from Structured Streaming 4.3 to 4.4
+- Since Spark 4.4, left outer and left semi stream-stream joins require a
watermark on the
+ right input and a time condition that limits how late a matching right row
can arrive.
+ Right outer joins require the corresponding settings on the left; full outer
joins require
+ them on both sides. An equality key counts as such a time condition when it
is the other
+ input's event time, or that event time shifted by constant intervals, except
a shift backward
+ by months, years, or a day-time interval of 24 hours or more. A key such as
+ `leftTime = rightTime - INTERVAL 1 DAY` or `leftTime = rightTime - INTERVAL
36 HOURS`, or one
+ truncated from the other input's event time, such as
+ `leftTime = CAST(CAST(rightTime AS BIGINT) AS TIMESTAMP)`, does not count,
while
+ `timestampadd` in hours, minutes or seconds does, whatever the amount. When
both inputs
+ have watermarks, a time range condition between the two event times can
bound such a join
+ instead. Some previously accepted queries now fail if these requirements are
not met. Update
+ their watermarks and join conditions using the
+ [join support
table](apis-on-dataframes-and-datasets.html#support-matrix-for-joins-in-streaming-queries).
+ A stateful operator after such a join that uses the other input's event time
also needs that
+ input bounded: for example, a left outer join followed by an append-mode
aggregation over the
+ right event time also needs a watermark on the left input and a time
condition that limits
+ how late a matching left row can arrive: an equality with an exact shift (an
interval under
+ one day, or `timestampadd` in hours, minutes or seconds), or a range
condition in place of a
+ shifted equality. Without them, the join holds back its output
+ watermark, and the query fails at start (see below) because the aggregation
would never emit
+ results.
+
+- Since Spark 4.4, you can set
`spark.sql.streaming.join.checkFinalization.enabled` to `false`
+ to run a stream-stream outer or left semi join that fails the requirement
above, or a query
+ that fails the start-time check for an aggregation after a join, below.
Spark then logs a
+ warning instead of failing the query. Joins that earlier versions also
rejected, such as an
+ outer join without a watermarked equality key or a range condition on a
watermarked event
+ time, still fail. The corrected state eviction cannot be turned
+ off: such a query keeps the state of the input that lacks a bound for the
life of the query,
+ and an outer join never outputs that input's unmatched rows. Because the
corrected eviction
+ changes results and cannot be turned off, these stream-stream join
corrections are made in
+ Spark 4.4.0 and are not backported to earlier releases.
+
+- Spark 4.4 corrects cases where stream-stream equality joins could discard
rows before their
+ matches arrived or output unmatched rows too early. Such joins with a
watermark on only one
+ input now keep the watermarked input's rows for the life of the query,
because the other input
+ has no watermark that bounds them, and hold back the join's output watermark
for that input.
+ An append-mode aggregation over that input's event time then fails at start.
Other stateful
+ operators after the join that use it keep its rows in state and do not emit
results that wait
+ for the watermark, such as event-time timeouts, while update-mode
aggregations and
+ deduplication still emit rows. Add a watermark on the other input to bound
those rows.
+
+- With `spark.sql.streaming.statefulOperator.allowMultiple` set to `false`, an
input of a
+ stream-stream join can keep several watermarked columns, such as its event
time together with a
+ copy of it or a time window over it, and late rows are filtered by whichever
of them comes
+ first. As in earlier versions, an equality key on any watermarked column of
an input bounds the
+ other input's state, so an input built with `withColumn("window",
window($"ts", ...))` is still
+ bounded by its window. Since Spark 4.4, such a key no longer bounds state
when Spark can see
+ that some rows of the input hold the key below a watermarked column before
it: when the key is
+ built from a time shifted backward, when it copies a column that an earlier
watermarked window
+ is built over, or when an input of a union builds it from another column.
Earlier versions
+ removed rows that could still match in these cases. A copy placed after a
window needs this
+ because the query filters late rows by the first watermarked column of the
planned input, and
+ whether the copied column survives column pruning, which analysis cannot
see, decides whether
+ that is the copy's source or the window. If the optimizer prunes the column,
rows are filtered
+ by the window, and evicting by the copy drops rows that can still match.
Outer and left semi
+ joins on such a key now fail, and inner joins keep the other input's rows
for the life of the
+ query. To bound state, join on the first watermarked column itself or on a
time window over it,
+ or select the key before the other watermarked columns of its input.
Checkpoints from earlier
+ versions of joins on a watermarked column after the first one are rejected
at restart, as
+ described below.
+
+- Spark 4.4 holds back the output watermark of a stream-stream join when
retained state can
+ still emit old event times. Downstream stateful operators may retain more
state, take longer
+ to finalize results, or never emit results that wait for the watermark while
the join has no
+ event-time eviction bound.
+ The join holds back only for an input whose event time reaches the next
stateful operator: in
+ a join on `clickTime <= impressionTime + INTERVAL 1 HOUR`, a window
aggregation over
+ `impressionTime` makes progress, and one over `clickTime` does not. Spark
follows the event
+ time through projections, filters, unions, and time and session windows, to
aggregations,
+ deduplication, stream-stream joins, and `flatMapGroupsWithState` or
`transformWithState` with
+ event-time timeouts. When Spark cannot tell which input's event time the
operator uses, for
+ example when the operator's event time is computed from the join output by a
function, it
+ holds back for both inputs.
+
+ Since Spark 4.4, a query fails at start with
`STREAMING_JOIN_UNBOUNDED_DOWNSTREAM_EVENT_TIME`
Review Comment:
**Nit (P3):** `checkJoinOutputWatermarkConsumers` judges only the join that
the tracer reaches first, and its `TODO(SPARK-61509)` lists an aggregation
behind a later join as not rejected yet. In a chain `j1 -> j2 -> append-mode
window aggregation` over a `clickTime` that `j1` cannot bound, for example, the
tracer attributes the aggregation to `j2`'s input; when `j2` bounds that input,
no error is raised, and the aggregation starts and never emits because `j1`
holds its output watermark. This paragraph, the sentence of the one-watermark
paragraph above that says such an aggregation fails at start, and the conf doc
should limit the claim to an aggregation after the nearest join, or say that
one behind a later join is not rejected yet.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60280#issuecomment-6816317254).
**Verification:**
- **Inspection:** The migration guide's start-time paragraph and the doc of
the finalization conf state that the check judges the nearest stream-stream
join and that an aggregation behind a later join is not rejected yet and keeps
running without emitting results, and every other sentence of the guide that
says an append-mode aggregation fails at start limits it to one that no later
stream-stream join separates from the join.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -17,36 +17,500 @@
package org.apache.spark.sql.catalyst.analysis
+import java.util.Locale
+
import scala.util.control.NonFatal
import org.apache.spark.internal.Logging
import org.apache.spark.internal.LogKeys._
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.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
+/**
+ * In legacy mode (spark.sql.streaming.statefulOperator.allowMultiple=false),
the watermarked
+ * equality keys that do not count as their input's event time. See
+ * [[StreamingJoinHelper.findLegacyEventTimeKeys]].
+ */
+case class LegacyEventTimeKeys(rejected: Set[ExprId]) {
+ /** Whether the key carries a watermark and is not rejected, so it bounds as
in Spark 4.3. */
+ def isEventTimeKey(key: Expression): Boolean = key match {
+ case n: NamedExpression => n.metadata.contains(delayKey) &&
!rejected(n.exprId)
+ case _ => false
+ }
+}
+
/**
* 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.
+ */
+ def getStateKeyWatermarkOrdinal(
+ keys: Seq[Expression],
+ inputAttributes: Seq[Attribute],
+ legacyKeys: Option[LegacyEventTimeKeys] = None): Option[Int] = {
+ getEventTimeKeyOrdinal(keys, inputAttributes, legacyKeys).orElse {
+ keys.indices.find(getStateKeyWatermark(keys, inputAttributes, _,
Some(0L)).isDefined)
+ }
+ }
+
+ /**
+ * Find the equality key that is this input's event-time column itself, or
else, in legacy
+ * mode, a watermarked key that `legacyKeys` does not reject. Spark 4.3 used
every watermarked
+ * key so; see [[findLegacyEventTimeKeys]].
+ */
+ def getEventTimeKeyOrdinal(
+ keys: Seq[Expression],
+ inputAttributes: Seq[Attribute],
+ legacyKeys: Option[LegacyEventTimeKeys] = 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 =>
+ Seq(keys.indexWhere(_.semanticEquals(eventTime)),
+ keys.indexWhere(key =>
legacyKeys.exists(_.isEventTimeKey(key)))).find(_ >= 0)
+ }
+ }
+
+ /**
+ * In legacy mode
(spark.sql.streaming.statefulOperator.allowMultiple=false), an input can keep
+ * several watermarked columns, such as its event time and a copy of it or a
time window over
+ * it, and it filters late rows by the first of them. Spark 4.3 counted
every watermarked
+ * equality key as the input's event time, which is right when the key is
never below the
+ * column that filters late rows. Keep doing so, and reject only a key that
`plan` shows some
+ * row can hold below a watermarked column before it, because the planned
input filters late
+ * rows by one of those: the optimizer can prune the ones before it.
Evicting by such a key
+ * would drop state that later rows still match. A key rejected by one
stream-stream join input
+ * is rejected for every join, so the analysis check and execution, which
read the result by
+ * expression ID on the analyzed and the planned join, decide the same.
+ */
+ def findLegacyEventTimeKeys(plan: LogicalPlan): LegacyEventTimeKeys = {
+ val rejected = 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.collect {
+ case i if watermarked.take(i).exists { eventTime =>
+ canBeBelow(input, watermarked(i), eventTime, SameValue,
eventTimeIsWindow = false)
+ } => watermarked(i)
+ }
+ }
+ LegacyEventTimeKeys(rejected.toSet)
+ }
+
+ /** How the join input's key relates to the column that [[canBeBelow]]
follows for it. */
+ private sealed trait KeyBound
+ /** The key is that column. */
+ private case object SameValue extends KeyBound
+ /** The key is a time window over that column, which ends at most a window
after it. */
+ private case object WindowEnd extends KeyBound
+ /** The key is at or above that column, by an amount the walk does not know.
*/
+ private case object AtOrAbove extends KeyBound
+ /** Some rows hold the key more than a microsecond below that column. */
+ private case object Below extends KeyBound
+
+ /**
+ * Whether `plan` shows that some row holds the join input's key below the
bound of its column
+ * `eventTime`, which late filtering compares with the watermark: the column
itself, or its end
+ * when `eventTimeIsWindow`. `bound` says how that key relates to the column
`key` of `plan`.
+ * 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 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; and into every input of a union, at the same
positions. Where both reach
+ * the same column, a key below it, or equal to it while the late-filtered
column is a window
+ * over it, can be below. 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.
Everything else gives
+ * false, so such a key keeps the Spark 4.3 behaviour.
+ */
+ private def canBeBelow(
+ plan: LogicalPlan,
+ key: ExprId,
+ eventTime: ExprId,
+ bound: KeyBound,
+ eventTimeIsWindow: Boolean): Boolean = {
+ def outputsBoth(p: LogicalPlan): Boolean =
+ p.output.exists(_.exprId == key) && p.output.exists(_.exprId ==
eventTime)
+ if (key == eventTime) {
+ bound == Below || (eventTimeIsWindow && bound == SameValue)
+ } else {
+ plan match {
+ case p: Project =>
+ def entry(id: ExprId): Option[NamedExpression] =
p.projectList.find(_.exprId == id)
+ (entry(key).flatMap(keyStep(_, bound)),
+ entry(eventTime).flatMap(eventTimeStep(_, eventTimeIsWindow)))
match {
+ case (Some((childKey, childBound)), Some((childEventTime,
isWindow))) =>
+ canBeBelow(p.child, childKey, childEventTime, childBound,
isWindow)
+ case _ => false
+ }
+ 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 entries(id: ExprId): Seq[Expression] =
+ e.output.indexWhere(_.exprId == id) match {
+ case -1 => Nil
+ case index => e.projections.map(_(index))
+ }
+ def passedOn(entries: Seq[Expression]): Option[ExprId] = entries.map
{
+ case a: Attribute => Some(a.exprId)
+ case _ => None
+ }.distinct match {
+ case Seq(id) => id
+ case _ => None
+ }
+ def windowSource(id: ExprId, entries: Seq[Expression]):
Option[ExprId] =
+ if (e.output.exists(a => a.exprId == id &&
a.metadata.contains(TimeWindow.marker))) {
+ entries.map(singleReference).distinct match {
+ case Seq(source) => source.map(_.exprId)
+ case _ => None
+ }
+ } else {
+ None
+ }
+ val (keyEntries, eventTimeEntries) = (entries(key),
entries(eventTime))
+ val childKey = passedOn(keyEntries).map(_ -> bound).orElse {
+ windowSource(key, keyEntries).filter(_ => bound ==
SameValue).map(_ -> WindowEnd)
+ }
+ val childEventTime = passedOn(eventTimeEntries).map(_ ->
eventTimeIsWindow).orElse {
+ windowSource(eventTime, eventTimeEntries).filter(_ =>
!eventTimeIsWindow).map(_ -> true)
+ }
+ (childKey, childEventTime) match {
+ case (Some((k, b)), Some((t, isWindow))) => canBeBelow(e.child, k,
t, b, isWindow)
+ case _ => false
+ }
+ 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)
+ keyIndex >= 0 && eventTimeIndex >= 0 && u.children.exists { child =>
+ unwatermarked(child, keyIndex) || unwatermarked(child,
eventTimeIndex) ||
+ canBeBelow(child, child.output(keyIndex).exprId,
+ child.output(eventTimeIndex).exprId, bound, eventTimeIsWindow)
+ }
+ case j: Join =>
+ j.children.find(outputsBoth).exists(canBeBelow(_, key, eventTime,
bound,
+ eventTimeIsWindow))
+ case u: UnaryNode if outputsBoth(u.child) =>
+ canBeBelow(u.child, key, eventTime, bound, eventTimeIsWindow)
+ case _ => false
+ }
+ }
+ }
+
+ /** The only attribute that `e` references, if there is one. */
+ private def singleReference(e: Expression): Option[Attribute] =
e.references.toSeq match {
+ case Seq(a) => Some(a)
+ case _ => None
+ }
+
+ /**
+ * The column of the projection's child that [[canBeBelow]] follows for the
key's projection
+ * entry `entry`, and how the key relates to it.
*/
- def isWatermarkInJoinKeys(plan: LogicalPlan): Boolean = {
- plan match {
- case ExtractEquiJoinKeys(_, leftKeys, rightKeys, _, _, _, _, _) =>
- (leftKeys ++ rightKeys).exists {
- case a: AttributeReference =>
a.metadata.contains(EventTimeWatermark.delayKey)
- case _ => false
+ private def keyStep(entry: NamedExpression, bound: KeyBound):
Option[(ExprId, KeyBound)] =
+ entry match {
+ case a: Attribute => Some(a.exprId -> bound)
+ case Alias(a: Attribute, _) => Some(a.exprId -> bound)
+ case Alias(child, _) => singleReference(child).flatMap { source =>
+ // A window is a struct, so a key above it is the window itself.
+ if (entry.metadata.contains(TimeWindow.marker)) {
+ Some(source.exprId -> WindowEnd).filter(_ => bound == SameValue)
+ } else if (entry.metadata.contains(SessionWindow.marker)) {
+ // A session ends its gap after the column, which can be longer than
a shift below.
+ Some(source.exprId -> AtOrAbove).filter(_ => bound == SameValue)
+ } else {
+ isForwardShift(child, source).flatMap {
+ case true => Some(bound).collect {
+ case SameValue | WindowEnd | AtOrAbove => source.exprId ->
AtOrAbove
+ }
+ case false => Some(bound).collect {
+ case SameValue | WindowEnd | Below => source.exprId -> Below
+ }
+ }
}
+ }
+ case _ => None
+ }
+
+ /**
+ * The column of the projection's child that [[canBeBelow]] follows for the
late-filtered
+ * column's projection entry `entry`, and whether the late-filtered column
is a window over it.
+ */
+ private def eventTimeStep(
+ entry: NamedExpression,
+ eventTimeIsWindow: Boolean): Option[(ExprId, Boolean)] = entry match {
+ case a: Attribute => Some(a.exprId -> eventTimeIsWindow)
+ case Alias(a: Attribute, _) => Some(a.exprId -> eventTimeIsWindow)
+ case Alias(child, _) if !eventTimeIsWindow &&
(entry.metadata.contains(TimeWindow.marker) ||
+ entry.metadata.contains(SessionWindow.marker)) =>
+ singleReference(child).map(_.exprId -> true)
+ case _ => None
+ }
+
+ /**
+ * Whether the timestamp `expr` is `source` shifted by constant intervals
that never move a
+ * time backward (true), or that move the epoch back by more than a
microsecond (false), so
+ * some rows hold it below `source`. None for any other expression.
+ */
+ private def isForwardShift(expr: Expression, source: Attribute):
Option[Boolean] = {
+ if (expr.dataType != TimestampType || source.dataType != TimestampType) {
+ None
+ } else {
+ intervalShift(expr, source).flatMap {
+ case (_, true) => Some(true)
+ case _ =>
+ val atEpoch = try {
+ Option(expr.transform {
+ case a: Attribute if a.exprId == source.exprId => Literal(0L,
TimestampType)
+ }.eval())
+ } catch {
+ case NonFatal(_) => None
+ }
+ atEpoch.collect { case micros: Long if micros < -1L => false }
+ }
+ }
+ }
+
+ /**
+ * Get the cutoff for the opposite input's equality key at `ordinal`, given
this input's
+ * watermark. `keys` and `inputAttributes` belong to this input, whose
future rows have an event
+ * time above the watermark. When the key is that event time, the equal key
of any state row
+ * they can still match is above the watermark too. When the key is the
event time shifted by
+ * exact intervals, solving `stateKey >= rightTime + INTERVAL 10 SECONDS`
shifts the cutoff by
+ * that interval, less 1 ms as for range conditions. When the shift has
whole days, months or
+ * years but never moves a time backward, the cutoff is the watermark
itself. Returns None for
+ * any other key, including a shift with whole days, months or years that
can move a time
+ * backward.
+ */
+ def getStateKeyWatermark(
+ keys: Seq[Expression],
+ inputAttributes: Seq[Attribute],
+ ordinal: Int,
+ eventWatermark: Option[Long],
+ legacyKeys: Option[LegacyEventTimeKeys] = None): Option[Long] = {
+ if (getEventTimeKeyOrdinal(keys, inputAttributes,
legacyKeys).contains(ordinal)) {
+ eventWatermark
+ } else {
+ shiftOfKey(keys(ordinal), inputAttributes).flatMap {
+ case KeyShift(eventTime, true, _) =>
+ val stateKey = AttributeReference("stateKey", TimestampType)()
+ getStateValueWatermark(AttributeSet(Seq(stateKey)),
AttributeSet(Seq(eventTime)),
+ Some(GreaterThanOrEqual(stateKey,
withIntervalLiterals(keys(ordinal)))),
+ eventWatermark)
+ // The solver cannot count this shift, but it keeps the key of every
future row at or
+ // above that row's event time, which is above the watermark.
+ case KeyShift(_, false, true) => eventWatermark
+ case _ => None
+ }
+ }
+ }
+
+ /**
+ * Get a bound on this input's event time for state rows whose equality key
at `ordinal` is
+ * above `keyWatermark`. When the key is the event time, the bound is the
key watermark. When
+ * the key is the event time shifted by exact intervals, solving
+ * `leftTime + INTERVAL 10 SECONDS >= keyWatermark` subtracts that constant,
less 1 ms.
+ * Returns None for any other key, including any shift with whole days,
months or years.
+ */
+ def getEventTimeWatermarkFromKey(
+ keys: Seq[Expression],
+ inputAttributes: Seq[Attribute],
+ ordinal: Int,
+ keyWatermark: Long): Option[Long] = {
+ if (getEventTimeKeyOrdinal(keys, inputAttributes).contains(ordinal)) {
+ Some(keyWatermark)
+ } else {
+ shiftOfKey(keys(ordinal), inputAttributes).filter(_.exact).flatMap {
shift =>
+ val keyWithWatermark = AttributeReference("stateKey", TimestampType,
+ metadata = new MetadataBuilder().putLong(delayKey, 0L).build())()
+ getStateValueWatermark(AttributeSet(Seq(shift.eventTime)),
+ AttributeSet(Seq(keyWithWatermark)),
+ Some(GreaterThanOrEqual(withIntervalLiterals(keys(ordinal)),
keyWithWatermark)),
+ Some(keyWatermark))
+ }
+ }
+ }
+
+ /**
+ * Whether the key is this input's event time shifted by constant intervals
that never move a
+ * time backward. [[getStateKeyWatermark]] bounds the opposite state by such
a key at the
+ * watermark plus the shift for an exact interval, and at the watermark
itself otherwise, so it
+ * is never below the watermark.
+ */
+ def isForwardShiftOfEventTime(key: Expression, inputAttributes:
Seq[Attribute]): Boolean =
+ shiftOfKey(key, inputAttributes).exists(_.forward)
+
+ /**
+ * A timestamp key computed from the input's event time by constant
intervals. `exact` means
+ * the solver counts the shift exactly; `forward` means the shift never
moves a time backward.
+ */
+ private case class KeyShift(eventTime: Attribute, exact: Boolean, forward:
Boolean)
+
+ /** How a timestamp key shifts the input's event time, if the solver or its
sign bounds it. */
+ private def shiftOfKey(key: Expression, inputAttributes: Seq[Attribute]):
Option[KeyShift] =
+ inputAttributes.find(_.metadata.contains(delayKey)).filter(_ =>
key.dataType == TimestampType)
+ .flatMap { eventTime =>
+ intervalShift(key, eventTime).collect {
+ case (exact, forward) if exact || forward => KeyShift(eventTime,
exact, forward)
+ }
+ }
+
+ /**
+ * If the expression is the event time plus or minus constant intervals,
whether the shift is
+ * exact and whether it never moves a time backward. Other functions and
casts from other types
+ * are not accepted: a truncation such as CAST(CAST(rightTime AS BIGINT) AS
TIMESTAMP) can map a
+ * later event time below the watermark.
+ */
+ private def intervalShift(expr: Expression, eventTime: Attribute):
Option[(Boolean, Boolean)] = {
+ // Spark adds whole days in the session time zone, where a day can be 23
or 25 hours across a
+ // daylight saving change, and months vary in length, but the solver
counts a day as 24 hours.
+ // So only intervals without whole days or months are exact, in every time
zone.
+ def interval(e: Expression, negate: Boolean): Option[(Boolean, Boolean)] =
{
+ def forward(parts: Long*): Boolean =
+ if (negate) parts.forall(_ <= 0) else parts.forall(_ >= 0)
+ // An interval that fails to evaluate gives no bound; the query reports
the error at run time.
+ def value: Option[Any] = try Option(e.eval()) catch { case NonFatal(_)
=> None }
+ if (!e.foldable) {
+ None
+ } else {
+ e.dataType match {
+ case _: DayTimeIntervalType =>
+ value.map { v =>
+ val micros = v.asInstanceOf[Long]
+ (-MICROS_PER_DAY < micros && micros < MICROS_PER_DAY,
forward(micros))
+ }
+ case _: YearMonthIntervalType =>
+ value.map { v =>
+ val months = v.asInstanceOf[Int]
+ (months == 0, forward(months))
+ }
+ case CalendarIntervalType =>
+ value.map { v =>
+ val i = v.asInstanceOf[CalendarInterval]
+ (i.months == 0 && i.days == 0, forward(i.months, i.days,
i.microseconds))
+ }
+ case _ => None
+ }
+ }
+ }
+ def combine(
+ a: Option[(Boolean, Boolean)],
+ b: Option[(Boolean, Boolean)]): Option[(Boolean, Boolean)] =
+ for ((exactA, forwardA) <- a; (exactB, forwardB) <- b)
+ yield (exactA && exactB, forwardA && forwardB)
Review Comment:
**Blocking (P1):** `rt + INTERVAL 1 DAY - INTERVAL 1 HOUR` resolves to a
cast of `DatetimeSub` whose replacement adds `-INTERVAL 1 HOUR` to `rt +
INTERVAL 1 DAY`; the day term is inexact and forward, the negated hour exact
and backward, and this line combines them into neither, so `shiftOfKey` drops
the key. Reading the code, a left outer join on `lk = rk AND lt = rt + INTERVAL
1 DAY - INTERVAL 1 HOUR` with watermarks on both inputs fails analysis with the
default conf, and its inner form never evicts the left state. On the base
branch the join was admitted through `lt` and both inputs were evicted at that
key, which is exact because the right key never falls below `rt`. Whether the
query works now depends on grouping: `rt + (INTERVAL 1 DAY - INTERVAL 1 HOUR)`
folds into one 23-hour interval and is bounded. The same applies to any
net-forward mix of a whole-day, month or year term with a term of the opposite
sign, such as `rt + INTERVAL 1 MONTH - INTERVAL 1 DAY`.
**Recommended change:** Make intervalShift report each shift's smallest
possible net displacement with its exactness, without reading the session time
zone: count the sub-day part of each term at its value, each whole day of a
forward term at 12 hours, a margin wider than any daylight-saving change, each
month at 28 such days and each year at 365, and each whole day of a backward
term at 36 hours, each month at 31 such days and each year at 366. Classify a
key as never moving a time backward when that smallest displacement is not
negative, and add key-watermark tests for compound shifts of both kinds.
**Why this works:** A compound shift such as rt + INTERVAL 1 DAY - INTERVAL
1 HOUR then has a smallest displacement of at least 11 hours, so shiftOfKey
keeps it as a forward inexact shift and getStateKeyWatermark bounds the other
input's state at the watermark, the cutoff the base branch used; exactness is
unchanged, so the solver and the output watermark still see only exact shifts.
**Scope:** Displacement-based classification of compound equality-key shifts.
**Risks:** Restarts of older checkpoints of such keys become acceptable
through forwardShiftedKey, which is right because older versions evicted them
at the unshifted watermark, the cutoff this version then uses. A compound shift
whose backward terms outweigh 12 hours per forward day stays unbounded, as at
this head, although it may never move a time backward in practice.
**Constraints:** Do not read the session time zone, as the
shift-classification decision requires. Keep exactness as it is, so the solver,
the output watermark and the left semi cutoffs see the same shifts as at this
head.
**Exclusions:**
- Conservative cutoffs for truncations and backward calendar shifts, which
the open decision about unbounded truncated keys covers.
- Net-forward compound shifts whose backward terms outweigh the 12-hour
floor of their forward days, such as rt + INTERVAL 1 DAY - INTERVAL 13 HOURS,
which keep no bound, as at this head: classifying them as forward would need a
longer floor for a day than every time zone guarantees.
**Success:** A left outer join on lk = rk AND lt = rt + INTERVAL 1 DAY -
INTERVAL 1 HOUR with watermarks on both inputs passes analysis and evicts both
inputs at the watermark, as on the base branch. The same shift written with
parentheses keeps its exact 23-hour cutoff. A compound shift whose smallest
displacement can be negative still gives no bound. A key such as rt + INTERVAL
1 MONTH - INTERVAL 1 DAY also bounds the other input's state at the watermark.
**Verification:**
- **Regression:** A left outer join on lk = rk AND lt = rt + INTERVAL 1 DAY
- INTERVAL 1 HOUR with watermarks on both inputs passes analysis, keeps every
match, and emits each unmatched left row once the watermark passes it.
- **Behavior:** The key watermark of rt + INTERVAL 1 DAY - INTERVAL 1 HOUR
and of rt + INTERVAL 1 MONTH - INTERVAL 1 DAY is the unshifted watermark, while
rt - INTERVAL 1 DAY + INTERVAL 1 HOUR and rt + INTERVAL 1 DAY - INTERVAL 13
HOURS give no bound.
- **Compatibility:** Single-term shifts and parenthesized compound intervals
get the same key watermarks as at this head.
--
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]