spark-test commented on code in PR #60280:
URL: https://github.com/apache/spark/pull/60280#discussion_r4605752372
##########
docs/streaming/ss-migration-guide.md:
##########
@@ -25,6 +25,158 @@ 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 with
+ months, years, or a day-time interval of 24 hours or more that can move a
time backward. To
+ decide this without the session time zone, Spark counts each day as 12 to 36
hours and each
+ month as 28 to 31 such days, takes the shortest length for an added term and
the longest for a
+ subtracted one, and counts a key only when the total is never negative. So
+ `leftTime = rightTime + INTERVAL 1 DAY - INTERVAL 1 HOUR` counts. A key such
as
+ `leftTime = rightTime - INTERVAL 1 DAY`, `leftTime = rightTime - INTERVAL 36
HOURS`,
+ `leftTime = rightTime + INTERVAL 1 DAY - INTERVAL 13 HOURS`,
+ `leftTime = rightTime + INTERVAL 5 DAYS - INTERVAL 2 DAYS` or
+ `leftTime = rightTime + INTERVAL 1 MONTH - INTERVAL 15 DAYS`, 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 an append-mode aggregation right after the join, with no
later stream-stream
+ join in between, fails at start (see below) because it 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 right after the join, with no later stream-stream
join in between,
+ 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 and an aggregation behind a later stream-stream join,
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 in the planned input. As in earlier versions, an equality key on any
watermarked column
+ of an input bounds the other input's state, 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. Since Spark 4.4,
+ when Spark can see that some rows of the input hold the key below a
watermarked column before
+ it, the key bounds the other input's state at the watermark less that
amount: the shift for a
+ key built from a time shifted backward by a fixed interval, and the window's
length for a copy
+ of, or a window over, a column that an earlier watermarked window is built
over. Earlier
+ versions removed rows that could still match in these cases. Which column
filters late rows
+ depends on column pruning: a copy placed after a window is filtered by its
source when the
+ query reads the source after the join, and by the window otherwise. Analysis
takes the largest
+ amount over the watermarked columns that can come first, and execution the
amount for the one
+ that does, so the other input keeps its rows, and an outer join outputs its
unmatched rows, up
+ to that amount later. A key that rows can hold below by an amount that Spark
cannot bound no
+ longer bounds state: one built from a time shifted backward by whole days,
months or years,
+ one that copies a column that an earlier session window with a gap that is
not constant is
+ built over, and one that an input of a union builds from a column without a
watermark, also in
+ a batch where that input has no data. 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. A range
+ condition on a watermarked column after the first one bounds state at that
column's watermark
+ less the same amount, but only when Spark can see how the column is built
from the ones before
+ it. Spark can also see this through an earlier inner join whose condition
equates a
+ watermarked column of each of its inputs, such as `at = bt`, or bounds one
of them from below by
+ the other plus constant intervals, such as `bt BETWEEN at AND at + INTERVAL
1 HOUR`, and through
+ an earlier left or right outer join with such a condition for a column of
the input that it pads
+ with nulls.
+ When each such condition relates the columns by an amount that Spark cannot
bound, the column
+ bounds no state, as above. Among the keys that bound state, Spark prefers
one whose amount it
+ can see over one that the plan does not relate to the column that filters
late rows. Spark
+ reuses a checkpoint from an earlier version of a join whose only watermarked
equality key, at
+ the same position in both inputs, bounds state at the watermark itself, such
as a join on a
+ time window over the first watermarked column, or on that column while the
input also keeps
+ the window. Other 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, stream-static joins, and time and
session windows,
+ to aggregations, deduplication, stream-stream joins,
`flatMapGroupsWithState` and
+ `applyInPandasWithState` with event-time timeouts, and `transformWithState`
in event-time
+ mode. It also follows an event time plus constant intervals with no negative
+ part, such as `impressionTime + INTERVAL 1 MINUTE`, which never falls below
that event time.
+ When Spark cannot tell which input's event time the operator uses, for
example when the
+ operator's event time subtracts an interval or is computed by another
function, it holds back
+ for both inputs.
+
+ Since Spark 4.4, a query fails at start with
`STREAMING_JOIN_UNBOUNDED_DOWNSTREAM_EVENT_TIME`
+ when an append-mode aggregation after a stream-stream join uses the event
time of a join input
+ whose state the join cannot bound, because that aggregation would never emit
results. The
+ error names the input and the missing watermark or time constraint. Spark
judges the
+ aggregation against the nearest stream-stream join that its event time
reaches. An aggregation
+ behind a later stream-stream join is not rejected yet (SPARK-61509): it
starts and does not
+ emit results while an earlier join holds back its output watermark, as do
event-time timeouts
+ and a later outer join. An aggregation in update output mode, or one whose
event time Spark
+ cannot trace to a join input, is not rejected either.
+
+- When restarting a stream-stream join from an older Spark version, Spark may
reject the
+ existing checkpoint with `STREAMING_JOIN_CHECKPOINT_INCOMPATIBLE`. Spark
reuses the checkpoint
+ of a join without watermarks, of a join with an equality condition between
the two inputs'
+ event times, such as `leftTime = rightTime`, and of a join whose time
condition compares the
+ two inputs' event times with each other by an ordering comparison (`<`,
`<=`, `>`, `>=` or
+ `BETWEEN`), each event time optionally cast and offset by constant intervals
or numbers, such as
+ `rightTime BETWEEN leftTime AND leftTime + INTERVAL 1 HOUR`. An equality in
which one event time
+ is shifted or cast, such as `leftTime = rightTime + INTERVAL 1 SECOND`, is
rejected. When such a
Review Comment:
**Nit (P3):** This sentence says that the checkpoint of an equality with a
shifted event time, such as `leftTime = rightTime + INTERVAL 1 SECOND`, is
rejected, but later in this paragraph the guide says that Spark reuses the
checkpoint of an equality that shifts the other input's event time forward when
no later stateful operator uses that event time, and `forwardShiftedKey` in
`isWatermarkCheckpointCompatible` accepts that case. A user upgrading such a
join without a later stateful operator reads both answers and may rebuild state
that the restart would keep. The sentence comes from SPARK-61344's round-8
change, where every shifted equality is still rejected; in this PR it can go,
which also makes "such a condition" in the next sentence refer to the ordering
comparison again:
```suggestion
`rightTime BETWEEN leftTime AND leftTime + INTERVAL 1 HOUR`. When such a
```
This extends an [existing
discussion](https://github.com/apache/spark/pull/60280#discussion_r4537719955).
**Verification:**
- **Inspection:** The restart paragraph of the migration guide no longer
says that an equality with a forward-shifted event time, such as leftTime =
rightTime + INTERVAL 1 SECOND, is rejected, and its remaining statements about
shifted equality keys agree with what the restart check accepts and rejects.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -17,36 +17,771 @@
package org.apache.spark.sql.catalyst.analysis
+import java.util.Locale
+
+import scala.util.Try
import scala.util.control.NonFatal
import org.apache.spark.internal.Logging
import org.apache.spark.internal.LogKeys._
+import org.apache.spark.sql.catalyst.InternalRow
import org.apache.spark.sql.catalyst.expressions._
-import org.apache.spark.sql.catalyst.planning.ExtractEquiJoinKeys
-import org.apache.spark.sql.catalyst.plans.logical.{EventTimeWatermark,
LogicalPlan}
+import org.apache.spark.sql.catalyst.plans.{InnerLike, LeftOuter, RightOuter}
+import org.apache.spark.sql.catalyst.plans.logical.{Expand, Join, LogicalPlan,
Project, UnaryNode, Union}
import org.apache.spark.sql.catalyst.plans.logical.EventTimeWatermark._
-import org.apache.spark.sql.catalyst.util.DateTimeConstants.MICROS_PER_DAY
+import org.apache.spark.sql.catalyst.util.DateTimeConstants.{MICROS_PER_DAY,
MICROS_PER_HOUR, MICROS_PER_MILLIS, MICROS_PER_MINUTE, MICROS_PER_SECOND}
import org.apache.spark.sql.types._
import org.apache.spark.unsafe.types.CalendarInterval
+/**
+ * How far below a column that can filter its stream-stream join input's late
rows one of the
+ * input's watermarked columns can be, for an equality key or a range
condition on it: at most
+ * `micros` where the plan relates the two columns; by an amount that the plan
does not bound when
+ * `unbounded`; and by an amount that it does not show when `unrelated`,
because it does not relate
+ * the two. A window column is compared by its end, as eviction and late
filtering compare it.
+ */
+case class EventTimeLag(micros: Long, unrelated: Boolean, unbounded: Boolean) {
+ def max(other: EventTimeLag): EventTimeLag = EventTimeLag(math.max(micros,
other.micros),
+ unrelated || other.unrelated, unbounded || other.unbounded)
+
+ /**
+ * The cutoff for the other input's equality key when this input's watermark
is `watermark`.
+ * A key that the plan does not relate keeps the Spark 4.3 cutoff.
+ */
+ def keyWatermark(watermark: Long): Option[Long] =
+ if (unbounded) None else Some(watermark - EventTimeLag.ceilMillis(micros))
+
+ /**
+ * The watermark to substitute for the column in a range condition. Spark
4.3 substituted the
+ * watermark for every watermarked column; this does so only where the plan
bounds the lag.
+ */
+ def rangeWatermark(watermark: Long): Option[Long] =
+ if (unbounded || unrelated) None else Some(watermark -
EventTimeLag.ceilMillis(micros))
+}
+
+object EventTimeLag {
+ val zero: EventTimeLag = EventTimeLag(0L, unrelated = false, unbounded =
false)
+ val unrelated: EventTimeLag = EventTimeLag(0L, unrelated = true, unbounded =
false)
+ val unbounded: EventTimeLag = EventTimeLag(0L, unrelated = false, unbounded
= true)
+
+ private def ceilMillis(micros: Long): Long =
+ micros / MICROS_PER_MILLIS + (if (micros % MICROS_PER_MILLIS == 0) 0 else
1)
+}
+
+/**
+ * The [[EventTimeLag]] of the watermarked columns of stream-stream join
inputs, by expression ID;
+ * see [[StreamingJoinHelper.findEventTimeLags]]. A column missing from `lags`
has lag zero, so
+ * `EventTimeLags(Map.empty)` gives every watermarked column lag zero. That is
right when multiple
+ * stateful operators are allowed: execution then fails at start for a planned
input with two
+ * distinct watermarked columns, so the only one left filters late rows itself.
+ */
+case class EventTimeLags(lags: Map[ExprId, EventTimeLag]) {
+ /**
+ * The lag of `column` in a join input with output `inputAttributes`, if it
carries a watermark.
+ * The input's first watermarked column filters its late rows itself.
+ */
+ def lagOf(column: NamedExpression, inputAttributes: Seq[Attribute]):
Option[EventTimeLag] =
+ if (!column.metadata.contains(delayKey)) {
+ None
+ } else if (inputAttributes.find(_.metadata.contains(delayKey))
+ .exists(_.exprId == column.exprId)) {
+ Some(EventTimeLag.zero)
+ } else {
+ Some(lags.getOrElse(column.exprId, EventTimeLag.zero))
+ }
+}
+
+object EventTimeLags {
+ val none: EventTimeLags = EventTimeLags(Map.empty)
+}
+
/**
* Helper object for stream joins. See [[StreamingSymmetricHashJoinExec]] in
SQL for more details.
*/
object StreamingJoinHelper extends PredicateHelper with Logging {
/**
- * Check the provided logical plan to see if its join keys contain a
watermark attribute.
- *
- * Will return false if the plan is not an equijoin.
- * @param plan the logical plan to check
+ * Find the equality key filtered by this input's watermark. Its ordinal can
be used to
+ * evict the opposite input's state, whose equality keys have the same
ordering.
+ * For leftTime = rightTime, a watermark on rightTime bounds leftTime even
when leftTime
+ * has no watermark. It does not bound right-side state without a watermark
on leftTime.
+ * A key computed from the event time by adding constant intervals, such as
+ * leftTime = rightTime + INTERVAL 10 SECONDS or leftTime =
timestampadd(HOUR, 1, rightTime),
+ * is bounded too if the solver can count the intervals exactly or they
never move a time
+ * backward; see [[getStateKeyWatermark]]. The result does not depend on the
session time zone,
+ * so neither does the V4 state layout. Without `lags`, only the input's
first watermarked
+ * column counts as its event time; with them, every watermarked column that
they bound does.
*/
- def isWatermarkInJoinKeys(plan: LogicalPlan): Boolean = {
- plan match {
- case ExtractEquiJoinKeys(_, leftKeys, rightKeys, _, _, _, _, _) =>
- (leftKeys ++ rightKeys).exists {
- case a: AttributeReference =>
a.metadata.contains(EventTimeWatermark.delayKey)
- case _ => false
+ def getStateKeyWatermarkOrdinal(
+ keys: Seq[Expression],
+ inputAttributes: Seq[Attribute],
+ lags: Option[EventTimeLags] = None): Option[Int] = {
+ getEventTimeKeyOrdinal(keys, inputAttributes, lags).orElse {
+ keys.indices.find(getStateKeyWatermark(keys, inputAttributes, _,
Some(0L), lags).isDefined)
+ }
+ }
+
+ /**
+ * Find the equality key that is this input's first watermarked column, or
else, with `lags`,
+ * the watermarked key with the smallest lag that bounds it; see
[[findEventTimeLags]]. A key
+ * that the plan relates to the late-filtered column comes before one that
it does not relate,
+ * whose cutoff the plan does not show to be safe.
+ */
+ def getEventTimeKeyOrdinal(
+ keys: Seq[Expression],
+ inputAttributes: Seq[Attribute],
+ lags: Option[EventTimeLags] = None): Option[Int] = {
+ // When multiple stateful operators are disabled, late filtering uses the
first event-time
+ // column. Otherwise, execution rejects multiple distinct event-time
columns.
+ inputAttributes.find(_.metadata.contains(delayKey)).flatMap { eventTime =>
+ Some(keys.indexWhere(_.semanticEquals(eventTime))).filter(_ >= 0).orElse
{
+ lags.flatMap { l =>
+ keys.indices.flatMap { i =>
+ keyLag(keys(i), inputAttributes, l).filterNot(_.unbounded).map(i
-> _)
+ }.sortBy { case (_, lag) => (lag.unrelated, lag.micros)
}.headOption.map(_._1)
}
+ }
+ }
+ }
+
+ /** The lag of a key that is a watermarked column of the input. */
+ private def keyLag(
+ key: Expression,
+ inputAttributes: Seq[Attribute],
+ lags: EventTimeLags): Option[EventTimeLag] = key match {
+ case n: NamedExpression => lags.lagOf(n, inputAttributes)
+ case _ => None
+ }
+
+ /**
+ * The lag of every watermarked column of each stream-stream join input in
`plan`, combined
+ * over the inputs by [[EventTimeLag.max]]. This is for
+ * spark.sql.streaming.statefulOperator.allowMultiple=false, where an input
can keep several
+ * watermarked columns, such as its event time and a copy of it or a time
window over it, and
+ * filters late rows by the first of them. When `planned`, `plan` is the
optimized plan that runs,
+ * so each input filters late rows by its first watermarked column, and a
column's lag is taken
+ * against that one. Otherwise the optimizer can prune any watermarked
column before a column, so
+ * its lag is the largest against all of them. Spark 4.3 bounded state by
every watermarked
+ * column at the watermark. A lag lowers that cutoff; see [[EventTimeLag]].
A column in
+ * `unwatermarkedUnionColumns` has no bound; see
[[findUnwatermarkedUnionColumns]].
+ */
+ def findEventTimeLags(
+ plan: LogicalPlan,
+ planned: Boolean,
+ unwatermarkedUnionColumns: Set[ExprId]): EventTimeLags = {
+ val lags = plan.collect {
+ case j: Join if j.left.isStreaming && j.right.isStreaming => Seq(j.left,
j.right)
+ }.flatten.flatMap { input =>
+ val watermarked =
input.output.filter(_.metadata.contains(delayKey)).map(_.exprId).distinct
+ watermarked.indices.map { i =>
+ val lateFiltered = if (planned) watermarked.take(1) else
watermarked.take(i)
+ watermarked(i) -> lateFiltered.filter(_ != watermarked(i)).map {
eventTime =>
+ lagBelow(input, watermarked(i), eventTime, Some(0L), Some(0L),
+ unwatermarkedUnionColumns)
+ }.foldLeft(EventTimeLag.zero)(_ max _)
+ }
+ }
+ EventTimeLags(lags.groupMapReduce(_._1)(_._2)(_ max _))
+ }
+
+ /**
+ * The columns at each position of a union in `plan` that the union
watermarks and one of its
+ * inputs does not: the union's output column and every input's column
there. That input builds
+ * the column some other way, so the column has no bound. Read them from the
analyzed plan: the
+ * optimizer removes a union input whose sources have no data in a batch,
and can then give
+ * the column the expression ID of any of these.
+ */
+ def findUnwatermarkedUnionColumns(plan: LogicalPlan): Set[ExprId] =
plan.collect {
+ case u: Union => u.output.indices.filter { i =>
+ u.output(i).metadata.contains(delayKey) &&
+ u.children.exists(!_.output(i).metadata.contains(delayKey))
+ }.flatMap(i => u.output(i).exprId +: u.children.map(_.output(i).exprId))
+ }.flatten.toSet
+
+ /** How a column relates to the column of a node's child that [[lagBelow]]
follows for it. */
+ private case class Step(column: ExprId, offset: Option[Long])
+
+ /**
+ * How far `key` of `plan` can be below its column `eventTime`, which late
filtering compares
+ * with the watermark. Both are compared by their bounds: a time, or a
window's end. `keyLow` is
+ * the smallest that the join input's key is above `key`, and
`eventTimeHigh` the largest that the
+ * join input's late-filtered column is above `eventTime`; None means
without bound. The walk
+ * follows both columns down by expression ID: through a projection or an
expansion that passes
+ * them on, builds a time or session window from a single column, or, for
the key, shifts a
+ * timestamp by constant intervals; through any other node with one input
that outputs both, as
+ * such a node keeps an expression ID only for an unchanged value; into the
input of a join that
+ * outputs both, or into both inputs of one that outputs each from a
different input and equates
+ * them through its condition (see [[lagThroughJoinCondition]]); and into
every input of a union,
+ * at the same positions. A union input that does not watermark a column
that the union, which
+ * takes its first input's metadata, watermarks builds it some other way, so
the lag is
+ * unbounded, as it is for a column in `unwatermarkedUnion`, which such an
input builds in a plan
+ * that the optimizer later removed the input from. Where both reach the
same column, the lag is
+ * the difference of the two offsets. Everything else leaves the columns
unrelated.
+ */
+ private def lagBelow(
+ plan: LogicalPlan,
+ key: ExprId,
+ eventTime: ExprId,
+ keyLow: Option[Long],
+ eventTimeHigh: Option[Long],
+ unwatermarkedUnion: Set[ExprId]): EventTimeLag = {
+ def outputsBoth(p: LogicalPlan): Boolean =
+ p.output.exists(_.exprId == key) && p.output.exists(_.exprId ==
eventTime)
+ def follow(child: LogicalPlan, keyStep: Option[Step], eventTimeStep:
Option[Step]) =
+ (keyStep, eventTimeStep) match {
+ case (Some(k), Some(t)) => lagBelow(child, k.column, t.column,
+ addOffsets(keyLow, k.offset), addOffsets(eventTimeHigh, t.offset),
unwatermarkedUnion)
+ case _ => EventTimeLag.unrelated
+ }
+ if (key == eventTime) {
+ (keyLow, eventTimeHigh) match {
+ case (Some(low), Some(high)) => Try(Math.subtractExact(high,
low)).toOption match {
+ case Some(lag) => EventTimeLag(math.max(0L, lag), unrelated = false,
unbounded = false)
+ case None => EventTimeLag.unbounded
+ }
+ case _ => EventTimeLag.unbounded
+ }
+ } else if (unwatermarkedUnion(key) || unwatermarkedUnion(eventTime)) {
+ EventTimeLag.unbounded
+ } else {
+ plan match {
+ case p: Project =>
+ def entry(id: ExprId): Option[NamedExpression] =
p.projectList.find(_.exprId == id)
+ follow(p.child, entry(key).flatMap(keyStep),
entry(eventTime).flatMap(eventTimeStep))
+ case e: Expand =>
+ // The rewrite of a sliding window puts one window per projection
beside the child's
+ // columns, which every projection passes on.
+ def step(id: ExprId, window: (Seq[Expression], Attribute) =>
Option[Long]) = {
+ val entries = e.output.indexWhere(_.exprId == id) match {
+ case -1 => Nil
+ case index => e.projections.map(_(index))
+ }
+ entries.map {
+ case a: Attribute => Some(a.exprId)
+ case _ => None
+ }.distinct match {
+ case Seq(Some(passedOn)) => Some(Step(passedOn, Some(0L)))
+ case _ if e.output.exists(a => a.exprId == id &&
+ a.metadata.contains(TimeWindow.marker)) =>
+ entries.map(timeWindowSource).distinct match {
+ case Seq(Some(source)) => Some(Step(source.exprId,
window(entries, source)))
+ case _ => None
+ }
+ case _ => None
+ }
+ }
+ // A window ends after its time column, and at most its length after
it.
+ follow(e.child, step(key, (_, _) => Some(0L)), step(eventTime,
(entries, source) =>
+ entries.map(timeWindowLength(_, source)).reduceOption((a, b) =>
+ for (x <- a; y <- b) yield math.max(x, y)).flatten))
+ case u: Union =>
+ val keyIndex = u.output.indexWhere(_.exprId == key)
+ val eventTimeIndex = u.output.indexWhere(_.exprId == eventTime)
+ def unwatermarked(child: LogicalPlan, index: Int): Boolean =
+ u.output(index).metadata.contains(delayKey) &&
+ !child.output(index).metadata.contains(delayKey)
+ if (keyIndex < 0 || eventTimeIndex < 0) {
+ EventTimeLag.unrelated
+ } else {
+ u.children.map { child =>
+ if (unwatermarked(child, keyIndex) || unwatermarked(child,
eventTimeIndex)) {
+ EventTimeLag.unbounded
+ } else {
+ lagBelow(child, child.output(keyIndex).exprId,
+ child.output(eventTimeIndex).exprId, keyLow, eventTimeHigh,
unwatermarkedUnion)
+ }
+ }.reduce(_ max _)
+ }
+ case j: Join =>
+ j.children.find(outputsBoth)
+ .map(lagBelow(_, key, eventTime, keyLow, eventTimeHigh,
unwatermarkedUnion))
+ .getOrElse(lagThroughJoinCondition(j, key, eventTime, keyLow,
eventTimeHigh,
+ unwatermarkedUnion))
+ case u: UnaryNode if outputsBoth(u.child) =>
+ lagBelow(u.child, key, eventTime, keyLow, eventTimeHigh,
unwatermarkedUnion)
+ case _ => EventTimeLag.unrelated
+ }
+ }
+ }
+
+ /**
+ * The lag of `key` below `eventTime` of [[lagBelow]] where `join` outputs
them from different
+ * inputs, through a conjunct of its condition that bounds a watermarked
column x of the key's
+ * input from below by a watermarked column y of the event time's input: an
equality `x = y`, or,
+ * for TIMESTAMP columns, `x >= y + c`, `x > y + c`, `x = y + c` or a
BETWEEN with such a lower
+ * bound, where c is constant intervals. The key is at most its lag below x,
x is at most -c
+ * below y, and y is at most its lag below the event time, so the lags add
up. A c whose whole
+ * days, months or years can move a time backward has no bound here, as for
equality keys. That
+ * holds on every row that the join outputs with a non-NULL key: all rows of
an inner join
+ * satisfy its condition, and so do those of a left or right outer join that
pads the key's
+ * input, whose other rows carry a NULL key that no condition matches. The
smallest bounded lag
+ * over such conjuncts wins; if every such conjunct gives a lag without
bound, the lag has no
+ * bound either. Other conjuncts, such as one that bounds x only from above,
and other join
+ * types leave the columns unrelated.
+ */
+ private def lagThroughJoinCondition(
+ join: Join,
+ key: ExprId,
+ eventTime: ExprId,
+ keyLow: Option[Long],
+ eventTimeHigh: Option[Long],
+ unwatermarkedUnion: Set[ExprId]): EventTimeLag = {
+ def watermarked(p: LogicalPlan): Set[ExprId] =
+ p.output.filter(_.metadata.contains(delayKey)).map(_.exprId).toSet
+ def outputs(p: LogicalPlan, id: ExprId): Boolean =
p.output.exists(_.exprId == id)
+ val inputs = if (outputs(join.left, key) && outputs(join.right,
eventTime)) {
+ Some((join.left, join.right))
+ } else if (outputs(join.right, key) && outputs(join.left, eventTime)) {
+ Some((join.right, join.left))
+ } else {
+ None
+ }
+ val lags = inputs.filter { case (keyInput, _) =>
+ join.joinType match {
+ case _: InnerLike => true
+ case LeftOuter => keyInput eq join.right
+ case RightOuter => keyInput eq join.left
+ case _ => false
+ }
+ }.toSeq.flatMap { case (keyInput, eventTimeInput) =>
+ val keyColumns = watermarked(keyInput)
+ val eventTimeColumns = watermarked(eventTimeInput)
+ // (x, y, c) where x >= y + c on every row that satisfies the conjunct;
c is None without
+ // bound. The analyzed plan keeps a BETWEEN, which the optimizer splits
into two of them.
+ def lowerBound(high: Expression, low: Expression): Seq[(ExprId, ExprId,
Option[Long])] =
+ (high, singleReference(low)) match {
+ case (x: Attribute, Some(y))
Review Comment:
**Non-blocking (P2):** `lowerBound` matches only when the larger side is a
bare TIMESTAMP attribute, so a tie that carries the interval on the bounded
column's side gives nothing. Reading the code in legacy mode, take `AB =
A.join(B, ak = bk AND at = bt + INTERVAL 1 MINUTE)` followed by `AB.join(C, ak
= ck AND bt = ct, "right_outer")`: `EqualTo(l, r)` tries `lowerBound(at, bt +
INTERVAL 1 MINUTE)`, whose `(at, bt)` pair the filter drops because `at` is not
a column of the key's input, and `lowerBound(bt + INTERVAL 1 MINUTE, at)`,
which matches nothing, so `bt` stays unrelated and the key keeps the full
watermark. C's state is then evicted at `ct <= W` although `bt` can be up to a
minute below `W`, so those matches are lost and the right outer join has
already emitted the C rows padded with nulls; written as `bt = at - INTERVAL 1
MINUTE`, the same query gets a 60-second lag. Likewise, `at <= bt + INTERVAL 10
MINUTES` and `at BETWEEN bt AND bt + INTERVAL 10 MINUTES` give `bt` no ran
ge bound, so a downstream right outer join on `ct BETWEEN bt AND bt + INTERVAL
1 HOUR` fails analysis and its inner form keeps every C row, while `bt >= at -
INTERVAL 10 MINUTES` bounds C at the watermark less 10 minutes. Reading the
larger side as a watermarked column plus constant intervals, and combining its
shift with the smaller side's through the existing `Shift` arithmetic, would
give each pair of spellings the same lag.
This extends existing discussions
[1](https://github.com/apache/spark/pull/60280#discussion_r4587582096),
[2](https://github.com/apache/spark/pull/60280#discussion_r4598159095).
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,771 @@
package org.apache.spark.sql.catalyst.analysis
+import java.util.Locale
+
+import scala.util.Try
import scala.util.control.NonFatal
import org.apache.spark.internal.Logging
import org.apache.spark.internal.LogKeys._
+import org.apache.spark.sql.catalyst.InternalRow
import org.apache.spark.sql.catalyst.expressions._
-import org.apache.spark.sql.catalyst.planning.ExtractEquiJoinKeys
-import org.apache.spark.sql.catalyst.plans.logical.{EventTimeWatermark,
LogicalPlan}
+import org.apache.spark.sql.catalyst.plans.{InnerLike, LeftOuter, RightOuter}
+import org.apache.spark.sql.catalyst.plans.logical.{Expand, Join, LogicalPlan,
Project, UnaryNode, Union}
import org.apache.spark.sql.catalyst.plans.logical.EventTimeWatermark._
-import org.apache.spark.sql.catalyst.util.DateTimeConstants.MICROS_PER_DAY
+import org.apache.spark.sql.catalyst.util.DateTimeConstants.{MICROS_PER_DAY,
MICROS_PER_HOUR, MICROS_PER_MILLIS, MICROS_PER_MINUTE, MICROS_PER_SECOND}
import org.apache.spark.sql.types._
import org.apache.spark.unsafe.types.CalendarInterval
+/**
+ * How far below a column that can filter its stream-stream join input's late
rows one of the
+ * input's watermarked columns can be, for an equality key or a range
condition on it: at most
+ * `micros` where the plan relates the two columns; by an amount that the plan
does not bound when
+ * `unbounded`; and by an amount that it does not show when `unrelated`,
because it does not relate
+ * the two. A window column is compared by its end, as eviction and late
filtering compare it.
+ */
+case class EventTimeLag(micros: Long, unrelated: Boolean, unbounded: Boolean) {
+ def max(other: EventTimeLag): EventTimeLag = EventTimeLag(math.max(micros,
other.micros),
+ unrelated || other.unrelated, unbounded || other.unbounded)
+
+ /**
+ * The cutoff for the other input's equality key when this input's watermark
is `watermark`.
+ * A key that the plan does not relate keeps the Spark 4.3 cutoff.
+ */
+ def keyWatermark(watermark: Long): Option[Long] =
+ if (unbounded) None else Some(watermark - EventTimeLag.ceilMillis(micros))
+
+ /**
+ * The watermark to substitute for the column in a range condition. Spark
4.3 substituted the
+ * watermark for every watermarked column; this does so only where the plan
bounds the lag.
+ */
+ def rangeWatermark(watermark: Long): Option[Long] =
+ if (unbounded || unrelated) None else Some(watermark -
EventTimeLag.ceilMillis(micros))
+}
+
+object EventTimeLag {
+ val zero: EventTimeLag = EventTimeLag(0L, unrelated = false, unbounded =
false)
+ val unrelated: EventTimeLag = EventTimeLag(0L, unrelated = true, unbounded =
false)
+ val unbounded: EventTimeLag = EventTimeLag(0L, unrelated = false, unbounded
= true)
+
+ private def ceilMillis(micros: Long): Long =
+ micros / MICROS_PER_MILLIS + (if (micros % MICROS_PER_MILLIS == 0) 0 else
1)
+}
+
+/**
+ * The [[EventTimeLag]] of the watermarked columns of stream-stream join
inputs, by expression ID;
+ * see [[StreamingJoinHelper.findEventTimeLags]]. A column missing from `lags`
has lag zero, so
+ * `EventTimeLags(Map.empty)` gives every watermarked column lag zero. That is
right when multiple
+ * stateful operators are allowed: execution then fails at start for a planned
input with two
+ * distinct watermarked columns, so the only one left filters late rows itself.
+ */
+case class EventTimeLags(lags: Map[ExprId, EventTimeLag]) {
+ /**
+ * The lag of `column` in a join input with output `inputAttributes`, if it
carries a watermark.
+ * The input's first watermarked column filters its late rows itself.
+ */
+ def lagOf(column: NamedExpression, inputAttributes: Seq[Attribute]):
Option[EventTimeLag] =
+ if (!column.metadata.contains(delayKey)) {
+ None
+ } else if (inputAttributes.find(_.metadata.contains(delayKey))
+ .exists(_.exprId == column.exprId)) {
+ Some(EventTimeLag.zero)
+ } else {
+ Some(lags.getOrElse(column.exprId, EventTimeLag.zero))
+ }
+}
+
+object EventTimeLags {
+ val none: EventTimeLags = EventTimeLags(Map.empty)
+}
+
/**
* Helper object for stream joins. See [[StreamingSymmetricHashJoinExec]] in
SQL for more details.
*/
object StreamingJoinHelper extends PredicateHelper with Logging {
/**
- * Check the provided logical plan to see if its join keys contain a
watermark attribute.
- *
- * Will return false if the plan is not an equijoin.
- * @param plan the logical plan to check
+ * Find the equality key filtered by this input's watermark. Its ordinal can
be used to
+ * evict the opposite input's state, whose equality keys have the same
ordering.
+ * For leftTime = rightTime, a watermark on rightTime bounds leftTime even
when leftTime
+ * has no watermark. It does not bound right-side state without a watermark
on leftTime.
+ * A key computed from the event time by adding constant intervals, such as
+ * leftTime = rightTime + INTERVAL 10 SECONDS or leftTime =
timestampadd(HOUR, 1, rightTime),
+ * is bounded too if the solver can count the intervals exactly or they
never move a time
+ * backward; see [[getStateKeyWatermark]]. The result does not depend on the
session time zone,
+ * so neither does the V4 state layout. Without `lags`, only the input's
first watermarked
+ * column counts as its event time; with them, every watermarked column that
they bound does.
*/
- def isWatermarkInJoinKeys(plan: LogicalPlan): Boolean = {
- plan match {
- case ExtractEquiJoinKeys(_, leftKeys, rightKeys, _, _, _, _, _) =>
- (leftKeys ++ rightKeys).exists {
- case a: AttributeReference =>
a.metadata.contains(EventTimeWatermark.delayKey)
- case _ => false
+ def getStateKeyWatermarkOrdinal(
+ keys: Seq[Expression],
+ inputAttributes: Seq[Attribute],
+ lags: Option[EventTimeLags] = None): Option[Int] = {
+ getEventTimeKeyOrdinal(keys, inputAttributes, lags).orElse {
+ keys.indices.find(getStateKeyWatermark(keys, inputAttributes, _,
Some(0L), lags).isDefined)
+ }
+ }
+
+ /**
+ * Find the equality key that is this input's first watermarked column, or
else, with `lags`,
+ * the watermarked key with the smallest lag that bounds it; see
[[findEventTimeLags]]. A key
+ * that the plan relates to the late-filtered column comes before one that
it does not relate,
+ * whose cutoff the plan does not show to be safe.
+ */
+ def getEventTimeKeyOrdinal(
+ keys: Seq[Expression],
+ inputAttributes: Seq[Attribute],
+ lags: Option[EventTimeLags] = None): Option[Int] = {
+ // When multiple stateful operators are disabled, late filtering uses the
first event-time
+ // column. Otherwise, execution rejects multiple distinct event-time
columns.
+ inputAttributes.find(_.metadata.contains(delayKey)).flatMap { eventTime =>
+ Some(keys.indexWhere(_.semanticEquals(eventTime))).filter(_ >= 0).orElse
{
+ lags.flatMap { l =>
+ keys.indices.flatMap { i =>
+ keyLag(keys(i), inputAttributes, l).filterNot(_.unbounded).map(i
-> _)
+ }.sortBy { case (_, lag) => (lag.unrelated, lag.micros)
}.headOption.map(_._1)
}
+ }
+ }
+ }
+
+ /** The lag of a key that is a watermarked column of the input. */
+ private def keyLag(
+ key: Expression,
+ inputAttributes: Seq[Attribute],
+ lags: EventTimeLags): Option[EventTimeLag] = key match {
+ case n: NamedExpression => lags.lagOf(n, inputAttributes)
+ case _ => None
+ }
+
+ /**
+ * The lag of every watermarked column of each stream-stream join input in
`plan`, combined
+ * over the inputs by [[EventTimeLag.max]]. This is for
+ * spark.sql.streaming.statefulOperator.allowMultiple=false, where an input
can keep several
+ * watermarked columns, such as its event time and a copy of it or a time
window over it, and
+ * filters late rows by the first of them. When `planned`, `plan` is the
optimized plan that runs,
+ * so each input filters late rows by its first watermarked column, and a
column's lag is taken
+ * against that one. Otherwise the optimizer can prune any watermarked
column before a column, so
+ * its lag is the largest against all of them. Spark 4.3 bounded state by
every watermarked
+ * column at the watermark. A lag lowers that cutoff; see [[EventTimeLag]].
A column in
+ * `unwatermarkedUnionColumns` has no bound; see
[[findUnwatermarkedUnionColumns]].
+ */
+ def findEventTimeLags(
+ plan: LogicalPlan,
+ planned: Boolean,
+ unwatermarkedUnionColumns: Set[ExprId]): EventTimeLags = {
+ val lags = plan.collect {
+ case j: Join if j.left.isStreaming && j.right.isStreaming => Seq(j.left,
j.right)
+ }.flatten.flatMap { input =>
+ val watermarked =
input.output.filter(_.metadata.contains(delayKey)).map(_.exprId).distinct
+ watermarked.indices.map { i =>
+ val lateFiltered = if (planned) watermarked.take(1) else
watermarked.take(i)
+ watermarked(i) -> lateFiltered.filter(_ != watermarked(i)).map {
eventTime =>
+ lagBelow(input, watermarked(i), eventTime, Some(0L), Some(0L),
+ unwatermarkedUnionColumns)
+ }.foldLeft(EventTimeLag.zero)(_ max _)
+ }
+ }
+ EventTimeLags(lags.groupMapReduce(_._1)(_._2)(_ max _))
+ }
+
+ /**
+ * The columns at each position of a union in `plan` that the union
watermarks and one of its
+ * inputs does not: the union's output column and every input's column
there. That input builds
+ * the column some other way, so the column has no bound. Read them from the
analyzed plan: the
+ * optimizer removes a union input whose sources have no data in a batch,
and can then give
+ * the column the expression ID of any of these.
+ */
+ def findUnwatermarkedUnionColumns(plan: LogicalPlan): Set[ExprId] =
plan.collect {
+ case u: Union => u.output.indices.filter { i =>
+ u.output(i).metadata.contains(delayKey) &&
+ u.children.exists(!_.output(i).metadata.contains(delayKey))
+ }.flatMap(i => u.output(i).exprId +: u.children.map(_.output(i).exprId))
+ }.flatten.toSet
+
+ /** How a column relates to the column of a node's child that [[lagBelow]]
follows for it. */
+ private case class Step(column: ExprId, offset: Option[Long])
+
+ /**
+ * How far `key` of `plan` can be below its column `eventTime`, which late
filtering compares
+ * with the watermark. Both are compared by their bounds: a time, or a
window's end. `keyLow` is
+ * the smallest that the join input's key is above `key`, and
`eventTimeHigh` the largest that the
+ * join input's late-filtered column is above `eventTime`; None means
without bound. The walk
+ * follows both columns down by expression ID: through a projection or an
expansion that passes
+ * them on, builds a time or session window from a single column, or, for
the key, shifts a
+ * timestamp by constant intervals; through any other node with one input
that outputs both, as
+ * such a node keeps an expression ID only for an unchanged value; into the
input of a join that
+ * outputs both, or into both inputs of one that outputs each from a
different input and equates
+ * them through its condition (see [[lagThroughJoinCondition]]); and into
every input of a union,
+ * at the same positions. A union input that does not watermark a column
that the union, which
+ * takes its first input's metadata, watermarks builds it some other way, so
the lag is
+ * unbounded, as it is for a column in `unwatermarkedUnion`, which such an
input builds in a plan
+ * that the optimizer later removed the input from. Where both reach the
same column, the lag is
+ * the difference of the two offsets. Everything else leaves the columns
unrelated.
+ */
+ private def lagBelow(
+ plan: LogicalPlan,
+ key: ExprId,
+ eventTime: ExprId,
+ keyLow: Option[Long],
+ eventTimeHigh: Option[Long],
+ unwatermarkedUnion: Set[ExprId]): EventTimeLag = {
+ def outputsBoth(p: LogicalPlan): Boolean =
+ p.output.exists(_.exprId == key) && p.output.exists(_.exprId ==
eventTime)
+ def follow(child: LogicalPlan, keyStep: Option[Step], eventTimeStep:
Option[Step]) =
+ (keyStep, eventTimeStep) match {
+ case (Some(k), Some(t)) => lagBelow(child, k.column, t.column,
+ addOffsets(keyLow, k.offset), addOffsets(eventTimeHigh, t.offset),
unwatermarkedUnion)
+ case _ => EventTimeLag.unrelated
+ }
+ if (key == eventTime) {
+ (keyLow, eventTimeHigh) match {
+ case (Some(low), Some(high)) => Try(Math.subtractExact(high,
low)).toOption match {
+ case Some(lag) => EventTimeLag(math.max(0L, lag), unrelated = false,
unbounded = false)
+ case None => EventTimeLag.unbounded
+ }
+ case _ => EventTimeLag.unbounded
+ }
+ } else if (unwatermarkedUnion(key) || unwatermarkedUnion(eventTime)) {
+ EventTimeLag.unbounded
+ } else {
+ plan match {
+ case p: Project =>
+ def entry(id: ExprId): Option[NamedExpression] =
p.projectList.find(_.exprId == id)
+ follow(p.child, entry(key).flatMap(keyStep),
entry(eventTime).flatMap(eventTimeStep))
+ case e: Expand =>
+ // The rewrite of a sliding window puts one window per projection
beside the child's
+ // columns, which every projection passes on.
+ def step(id: ExprId, window: (Seq[Expression], Attribute) =>
Option[Long]) = {
+ val entries = e.output.indexWhere(_.exprId == id) match {
+ case -1 => Nil
+ case index => e.projections.map(_(index))
+ }
+ entries.map {
+ case a: Attribute => Some(a.exprId)
+ case _ => None
+ }.distinct match {
+ case Seq(Some(passedOn)) => Some(Step(passedOn, Some(0L)))
+ case _ if e.output.exists(a => a.exprId == id &&
+ a.metadata.contains(TimeWindow.marker)) =>
+ entries.map(timeWindowSource).distinct match {
+ case Seq(Some(source)) => Some(Step(source.exprId,
window(entries, source)))
+ case _ => None
+ }
+ case _ => None
+ }
+ }
+ // A window ends after its time column, and at most its length after
it.
+ follow(e.child, step(key, (_, _) => Some(0L)), step(eventTime,
(entries, source) =>
+ entries.map(timeWindowLength(_, source)).reduceOption((a, b) =>
+ for (x <- a; y <- b) yield math.max(x, y)).flatten))
+ case u: Union =>
+ val keyIndex = u.output.indexWhere(_.exprId == key)
+ val eventTimeIndex = u.output.indexWhere(_.exprId == eventTime)
+ def unwatermarked(child: LogicalPlan, index: Int): Boolean =
+ u.output(index).metadata.contains(delayKey) &&
+ !child.output(index).metadata.contains(delayKey)
+ if (keyIndex < 0 || eventTimeIndex < 0) {
+ EventTimeLag.unrelated
+ } else {
+ u.children.map { child =>
+ if (unwatermarked(child, keyIndex) || unwatermarked(child,
eventTimeIndex)) {
+ EventTimeLag.unbounded
+ } else {
+ lagBelow(child, child.output(keyIndex).exprId,
+ child.output(eventTimeIndex).exprId, keyLow, eventTimeHigh,
unwatermarkedUnion)
+ }
+ }.reduce(_ max _)
+ }
+ case j: Join =>
+ j.children.find(outputsBoth)
+ .map(lagBelow(_, key, eventTime, keyLow, eventTimeHigh,
unwatermarkedUnion))
+ .getOrElse(lagThroughJoinCondition(j, key, eventTime, keyLow,
eventTimeHigh,
+ unwatermarkedUnion))
+ case u: UnaryNode if outputsBoth(u.child) =>
+ lagBelow(u.child, key, eventTime, keyLow, eventTimeHigh,
unwatermarkedUnion)
+ case _ => EventTimeLag.unrelated
+ }
+ }
+ }
+
+ /**
+ * The lag of `key` below `eventTime` of [[lagBelow]] where `join` outputs
them from different
+ * inputs, through a conjunct of its condition that bounds a watermarked
column x of the key's
+ * input from below by a watermarked column y of the event time's input: an
equality `x = y`, or,
+ * for TIMESTAMP columns, `x >= y + c`, `x > y + c`, `x = y + c` or a
BETWEEN with such a lower
+ * bound, where c is constant intervals. The key is at most its lag below x,
x is at most -c
+ * below y, and y is at most its lag below the event time, so the lags add
up. A c whose whole
+ * days, months or years can move a time backward has no bound here, as for
equality keys. That
+ * holds on every row that the join outputs with a non-NULL key: all rows of
an inner join
+ * satisfy its condition, and so do those of a left or right outer join that
pads the key's
+ * input, whose other rows carry a NULL key that no condition matches. The
smallest bounded lag
+ * over such conjuncts wins; if every such conjunct gives a lag without
bound, the lag has no
+ * bound either. Other conjuncts, such as one that bounds x only from above,
and other join
+ * types leave the columns unrelated.
+ */
+ private def lagThroughJoinCondition(
+ join: Join,
+ key: ExprId,
+ eventTime: ExprId,
+ keyLow: Option[Long],
+ eventTimeHigh: Option[Long],
+ unwatermarkedUnion: Set[ExprId]): EventTimeLag = {
+ def watermarked(p: LogicalPlan): Set[ExprId] =
+ p.output.filter(_.metadata.contains(delayKey)).map(_.exprId).toSet
+ def outputs(p: LogicalPlan, id: ExprId): Boolean =
p.output.exists(_.exprId == id)
+ val inputs = if (outputs(join.left, key) && outputs(join.right,
eventTime)) {
+ Some((join.left, join.right))
+ } else if (outputs(join.right, key) && outputs(join.left, eventTime)) {
+ Some((join.right, join.left))
+ } else {
+ None
+ }
+ val lags = inputs.filter { case (keyInput, _) =>
+ join.joinType match {
+ case _: InnerLike => true
+ case LeftOuter => keyInput eq join.right
+ case RightOuter => keyInput eq join.left
+ case _ => false
+ }
+ }.toSeq.flatMap { case (keyInput, eventTimeInput) =>
+ val keyColumns = watermarked(keyInput)
+ val eventTimeColumns = watermarked(eventTimeInput)
+ // (x, y, c) where x >= y + c on every row that satisfies the conjunct;
c is None without
+ // bound. The analyzed plan keeps a BETWEEN, which the optimizer splits
into two of them.
+ def lowerBound(high: Expression, low: Expression): Seq[(ExprId, ExprId,
Option[Long])] =
+ (high, singleReference(low)) match {
+ case (x: Attribute, Some(y))
+ if x.dataType == TimestampType && y.dataType == TimestampType =>
+ Try(intervalShift(low, y)).toOption.flatten.toSeq.map { shift =>
+ (x.exprId, y.exprId, Some(shift.min).filter(_ => shift.exact ||
shift.forward))
+ }
+ case _ => Nil
+ }
+ join.condition.toSeq.flatMap(splitConjunctivePredicates).flatMap {
+ case EqualTo(a: Attribute, b: Attribute) =>
+ Seq((a.exprId, b.exprId, Some(0L)), (b.exprId, a.exprId, Some(0L)))
+ case EqualTo(l, r) => lowerBound(l, r) ++ lowerBound(r, l)
+ case GreaterThanOrEqual(l, r) => lowerBound(l, r)
+ case GreaterThan(l, r) => lowerBound(l, r)
+ case LessThanOrEqual(l, r) => lowerBound(r, l)
+ case LessThan(l, r) => lowerBound(r, l)
Review Comment:
**Nit (P3):** No test reaches this arm or the upper half of the BETWEEN case
on the next line: the lag table in `StreamingJoinLegacyEventTimeKeySuite` reads
`=`, `<=`, `>`, a shifted equality and the lower half of BETWEEN, the day-shift
test reads `>=`, and the chained joins in `StreamingJoinPlanRobustBoundSuite`
use `at = bt`, `bt BETWEEN at AND at + INTERVAL 10 MINUTES` and `bt >= at -
INTERVAL 1 HOUR`. Changing this arm to `lowerBound(l, r)`, or dropping
`lowerBound(upper, input)`, would leave every suite green, while an earlier
join on `ak = bk AND at - INTERVAL 1 MINUTE < bt`, or on `ak = bk AND at -
INTERVAL 1 MINUTE BETWEEN bt - INTERVAL 1 HOUR AND bt`, would then leave `bt`
unrelated instead of giving it a 60-second lag, so a downstream key on `bt`
would lose matches up to a minute below the watermark. A lag-table row for each
arm would catch that.
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:
##########
@@ -167,44 +175,49 @@ object StreamingSymmetricHashJoinHelper extends Logging {
eventTimeWatermarkForEviction: Option[Long],
allowMultipleEventTimeColumns: Boolean): (Option[Long], Option[Long]) = {
- // Perform assertions against multiple event time columns in the same
DataFrame. This method
- // assumes there is only one event time column per each side (left /
right) and it is not very
- // clear to reason about the correctness if there are multiple event time
columns. Disallow to
- // be conservative.
- WatermarkSupport.findEventTimeColumn(leftAttributes,
- allowMultipleEventTimeColumns = allowMultipleEventTimeColumns)
- WatermarkSupport.findEventTimeColumn(rightAttributes,
- allowMultipleEventTimeColumns = allowMultipleEventTimeColumns)
-
- val joinKeyOrdinalForWatermark: Option[Int] =
findJoinKeyOrdinalForWatermark(
- leftKeys, rightKeys)
+ val predicates = getStateWatermarkPredicates(leftAttributes,
rightAttributes,
+ leftKeys, rightKeys, condition, eventTimeWatermarkForEviction, None,
+ allowMultipleEventTimeColumns)
def getOneSideStateWatermark(
oneSideInputAttributes: Seq[Attribute],
- otherSideInputAttributes: Seq[Attribute]): Option[Long] = {
- val isWatermarkDefinedOnInput =
oneSideInputAttributes.exists(_.metadata.contains(delayKey))
- val isWatermarkDefinedOnJoinKey = joinKeyOrdinalForWatermark.isDefined
-
- if (isWatermarkDefinedOnJoinKey) { // case 1 and 3 in the
StreamingSymmetricHashJoinExec docs
- eventTimeWatermarkForEviction
- } else if (isWatermarkDefinedOnInput) { // case 2 in the
StreamingSymmetricHashJoinExec docs
- StreamingJoinHelper.getStateValueWatermark(
- attributesToFindStateWatermarkFor =
AttributeSet(oneSideInputAttributes),
- attributesWithEventWatermark =
AttributeSet(otherSideInputAttributes),
- condition,
- eventTimeWatermarkForEviction)
- } else {
- None
+ oneSideKeys: Seq[Expression],
+ predicate: Option[JoinStateWatermarkPredicate]): Option[Long] = {
+ WatermarkSupport.findEventTimeColumn(oneSideInputAttributes,
+ allowMultipleEventTimeColumns).map { eventTime =>
+ predicate match {
+ case Some(JoinStateKeyWatermarkPredicate(expr, watermark, _)) =>
+ // Retained keys are above the cutoff. When the key is this side's
event time,
+ // possibly plus a constant, that bounds the event times of the
retained rows.
+ // Otherwise return 0 for the reason below.
Review Comment:
**Nit (P3):** `getEventTimeWatermarkFromKey` keeps only shifts by exact
intervals (`shiftOfKey(...).filter(_.exact)`), so for a key such as `rightTime
+ INTERVAL 1 DAY` this arm returns 0 and holds back the join's output watermark
for this side, while the comment promises a bound for the event time plus any
constant. The comment predates the exact-only filter, which the round-1 commit
added. Something like:
```suggestion
// possibly shifted by exact intervals, that bounds the event
times of the retained
// rows. Otherwise, including a shift by whole days, return 0
for the reason below.
```
**Verification:**
- **Inspection:** The comment above the key arm of the per-side state
watermark no longer promises a bound for a key that is the event time plus any
constant, and its condition matches the exact-shift filter of
getEventTimeWatermarkFromKey in StreamingJoinHelper.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -17,36 +17,771 @@
package org.apache.spark.sql.catalyst.analysis
+import java.util.Locale
+
+import scala.util.Try
import scala.util.control.NonFatal
import org.apache.spark.internal.Logging
import org.apache.spark.internal.LogKeys._
+import org.apache.spark.sql.catalyst.InternalRow
import org.apache.spark.sql.catalyst.expressions._
-import org.apache.spark.sql.catalyst.planning.ExtractEquiJoinKeys
-import org.apache.spark.sql.catalyst.plans.logical.{EventTimeWatermark,
LogicalPlan}
+import org.apache.spark.sql.catalyst.plans.{InnerLike, LeftOuter, RightOuter}
+import org.apache.spark.sql.catalyst.plans.logical.{Expand, Join, LogicalPlan,
Project, UnaryNode, Union}
import org.apache.spark.sql.catalyst.plans.logical.EventTimeWatermark._
-import org.apache.spark.sql.catalyst.util.DateTimeConstants.MICROS_PER_DAY
+import org.apache.spark.sql.catalyst.util.DateTimeConstants.{MICROS_PER_DAY,
MICROS_PER_HOUR, MICROS_PER_MILLIS, MICROS_PER_MINUTE, MICROS_PER_SECOND}
import org.apache.spark.sql.types._
import org.apache.spark.unsafe.types.CalendarInterval
+/**
+ * How far below a column that can filter its stream-stream join input's late
rows one of the
+ * input's watermarked columns can be, for an equality key or a range
condition on it: at most
+ * `micros` where the plan relates the two columns; by an amount that the plan
does not bound when
+ * `unbounded`; and by an amount that it does not show when `unrelated`,
because it does not relate
+ * the two. A window column is compared by its end, as eviction and late
filtering compare it.
+ */
+case class EventTimeLag(micros: Long, unrelated: Boolean, unbounded: Boolean) {
+ def max(other: EventTimeLag): EventTimeLag = EventTimeLag(math.max(micros,
other.micros),
+ unrelated || other.unrelated, unbounded || other.unbounded)
+
+ /**
+ * The cutoff for the other input's equality key when this input's watermark
is `watermark`.
+ * A key that the plan does not relate keeps the Spark 4.3 cutoff.
+ */
+ def keyWatermark(watermark: Long): Option[Long] =
+ if (unbounded) None else Some(watermark - EventTimeLag.ceilMillis(micros))
+
+ /**
+ * The watermark to substitute for the column in a range condition. Spark
4.3 substituted the
+ * watermark for every watermarked column; this does so only where the plan
bounds the lag.
+ */
+ def rangeWatermark(watermark: Long): Option[Long] =
+ if (unbounded || unrelated) None else Some(watermark -
EventTimeLag.ceilMillis(micros))
+}
+
+object EventTimeLag {
+ val zero: EventTimeLag = EventTimeLag(0L, unrelated = false, unbounded =
false)
+ val unrelated: EventTimeLag = EventTimeLag(0L, unrelated = true, unbounded =
false)
+ val unbounded: EventTimeLag = EventTimeLag(0L, unrelated = false, unbounded
= true)
+
+ private def ceilMillis(micros: Long): Long =
+ micros / MICROS_PER_MILLIS + (if (micros % MICROS_PER_MILLIS == 0) 0 else
1)
+}
+
+/**
+ * The [[EventTimeLag]] of the watermarked columns of stream-stream join
inputs, by expression ID;
+ * see [[StreamingJoinHelper.findEventTimeLags]]. A column missing from `lags`
has lag zero, so
+ * `EventTimeLags(Map.empty)` gives every watermarked column lag zero. That is
right when multiple
+ * stateful operators are allowed: execution then fails at start for a planned
input with two
+ * distinct watermarked columns, so the only one left filters late rows itself.
+ */
+case class EventTimeLags(lags: Map[ExprId, EventTimeLag]) {
+ /**
+ * The lag of `column` in a join input with output `inputAttributes`, if it
carries a watermark.
+ * The input's first watermarked column filters its late rows itself.
+ */
+ def lagOf(column: NamedExpression, inputAttributes: Seq[Attribute]):
Option[EventTimeLag] =
+ if (!column.metadata.contains(delayKey)) {
+ None
+ } else if (inputAttributes.find(_.metadata.contains(delayKey))
+ .exists(_.exprId == column.exprId)) {
+ Some(EventTimeLag.zero)
+ } else {
+ Some(lags.getOrElse(column.exprId, EventTimeLag.zero))
+ }
+}
+
+object EventTimeLags {
+ val none: EventTimeLags = EventTimeLags(Map.empty)
+}
+
/**
* Helper object for stream joins. See [[StreamingSymmetricHashJoinExec]] in
SQL for more details.
*/
object StreamingJoinHelper extends PredicateHelper with Logging {
/**
- * Check the provided logical plan to see if its join keys contain a
watermark attribute.
- *
- * Will return false if the plan is not an equijoin.
- * @param plan the logical plan to check
+ * Find the equality key filtered by this input's watermark. Its ordinal can
be used to
+ * evict the opposite input's state, whose equality keys have the same
ordering.
+ * For leftTime = rightTime, a watermark on rightTime bounds leftTime even
when leftTime
+ * has no watermark. It does not bound right-side state without a watermark
on leftTime.
+ * A key computed from the event time by adding constant intervals, such as
+ * leftTime = rightTime + INTERVAL 10 SECONDS or leftTime =
timestampadd(HOUR, 1, rightTime),
+ * is bounded too if the solver can count the intervals exactly or they
never move a time
+ * backward; see [[getStateKeyWatermark]]. The result does not depend on the
session time zone,
+ * so neither does the V4 state layout. Without `lags`, only the input's
first watermarked
+ * column counts as its event time; with them, every watermarked column that
they bound does.
*/
- def isWatermarkInJoinKeys(plan: LogicalPlan): Boolean = {
- plan match {
- case ExtractEquiJoinKeys(_, leftKeys, rightKeys, _, _, _, _, _) =>
- (leftKeys ++ rightKeys).exists {
- case a: AttributeReference =>
a.metadata.contains(EventTimeWatermark.delayKey)
- case _ => false
+ def getStateKeyWatermarkOrdinal(
+ keys: Seq[Expression],
+ inputAttributes: Seq[Attribute],
+ lags: Option[EventTimeLags] = None): Option[Int] = {
+ getEventTimeKeyOrdinal(keys, inputAttributes, lags).orElse {
+ keys.indices.find(getStateKeyWatermark(keys, inputAttributes, _,
Some(0L), lags).isDefined)
+ }
+ }
+
+ /**
+ * Find the equality key that is this input's first watermarked column, or
else, with `lags`,
+ * the watermarked key with the smallest lag that bounds it; see
[[findEventTimeLags]]. A key
+ * that the plan relates to the late-filtered column comes before one that
it does not relate,
+ * whose cutoff the plan does not show to be safe.
+ */
+ def getEventTimeKeyOrdinal(
+ keys: Seq[Expression],
+ inputAttributes: Seq[Attribute],
+ lags: Option[EventTimeLags] = None): Option[Int] = {
+ // When multiple stateful operators are disabled, late filtering uses the
first event-time
+ // column. Otherwise, execution rejects multiple distinct event-time
columns.
+ inputAttributes.find(_.metadata.contains(delayKey)).flatMap { eventTime =>
+ Some(keys.indexWhere(_.semanticEquals(eventTime))).filter(_ >= 0).orElse
{
+ lags.flatMap { l =>
+ keys.indices.flatMap { i =>
+ keyLag(keys(i), inputAttributes, l).filterNot(_.unbounded).map(i
-> _)
+ }.sortBy { case (_, lag) => (lag.unrelated, lag.micros)
}.headOption.map(_._1)
}
+ }
+ }
+ }
+
+ /** The lag of a key that is a watermarked column of the input. */
+ private def keyLag(
+ key: Expression,
+ inputAttributes: Seq[Attribute],
+ lags: EventTimeLags): Option[EventTimeLag] = key match {
+ case n: NamedExpression => lags.lagOf(n, inputAttributes)
+ case _ => None
+ }
+
+ /**
+ * The lag of every watermarked column of each stream-stream join input in
`plan`, combined
+ * over the inputs by [[EventTimeLag.max]]. This is for
+ * spark.sql.streaming.statefulOperator.allowMultiple=false, where an input
can keep several
+ * watermarked columns, such as its event time and a copy of it or a time
window over it, and
+ * filters late rows by the first of them. When `planned`, `plan` is the
optimized plan that runs,
+ * so each input filters late rows by its first watermarked column, and a
column's lag is taken
+ * against that one. Otherwise the optimizer can prune any watermarked
column before a column, so
+ * its lag is the largest against all of them. Spark 4.3 bounded state by
every watermarked
+ * column at the watermark. A lag lowers that cutoff; see [[EventTimeLag]].
A column in
+ * `unwatermarkedUnionColumns` has no bound; see
[[findUnwatermarkedUnionColumns]].
+ */
+ def findEventTimeLags(
+ plan: LogicalPlan,
+ planned: Boolean,
+ unwatermarkedUnionColumns: Set[ExprId]): EventTimeLags = {
+ val lags = plan.collect {
+ case j: Join if j.left.isStreaming && j.right.isStreaming => Seq(j.left,
j.right)
+ }.flatten.flatMap { input =>
+ val watermarked =
input.output.filter(_.metadata.contains(delayKey)).map(_.exprId).distinct
+ watermarked.indices.map { i =>
+ val lateFiltered = if (planned) watermarked.take(1) else
watermarked.take(i)
+ watermarked(i) -> lateFiltered.filter(_ != watermarked(i)).map {
eventTime =>
+ lagBelow(input, watermarked(i), eventTime, Some(0L), Some(0L),
+ unwatermarkedUnionColumns)
+ }.foldLeft(EventTimeLag.zero)(_ max _)
+ }
+ }
+ EventTimeLags(lags.groupMapReduce(_._1)(_._2)(_ max _))
+ }
+
+ /**
+ * The columns at each position of a union in `plan` that the union
watermarks and one of its
+ * inputs does not: the union's output column and every input's column
there. That input builds
+ * the column some other way, so the column has no bound. Read them from the
analyzed plan: the
+ * optimizer removes a union input whose sources have no data in a batch,
and can then give
+ * the column the expression ID of any of these.
+ */
+ def findUnwatermarkedUnionColumns(plan: LogicalPlan): Set[ExprId] =
plan.collect {
+ case u: Union => u.output.indices.filter { i =>
+ u.output(i).metadata.contains(delayKey) &&
+ u.children.exists(!_.output(i).metadata.contains(delayKey))
+ }.flatMap(i => u.output(i).exprId +: u.children.map(_.output(i).exprId))
Review Comment:
**Non-blocking (P2):** These marks cover only the union's own output and
input columns, and `lagBelow` returns lag zero when the key and the
late-filtered column reach the same column (line 236 of this file) before it
checks the marks (line 244). Reading the code, take the union test in
`StreamingJoinPlanRobustBoundSuite` with the right input renamed,
`watermarked.union(unwatermarked).toDF("k", "t", "c")`, inner-joined on `lk = k
AND lt = c` in legacy mode. Analysis, and every batch in which the
unwatermarked input has data, give `c` no bound, because the walk reaches the
marked `rc` or the union input without a watermark. In a batch where that input
has no data, `PropagateEmptyRelation` drops it, since the input has no
watermark node to stop the propagation, and `CollapseProject` merges `rk AS k,
rt AS t, rc AS c` into the remaining `rk, rt, rt AS rc`, so the planned input
reads `rt AS t, rt AS c`: `c` and `t` both step to `rt`, the walk returns lag
zero there, and the left state
is evicted at the watermark. With the test's data, the batch at a watermark
of 69 seconds would evict the left row at 10 seconds, and the later
unwatermarked row at 80 seconds, whose `c` is 10 seconds, would find nothing,
which the migration guide rules out for a batch where that input has no data.
`withColumnRenamed` on both columns gives the same plan.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60280#discussion_r4598159103).
**Recommended change:** In findUnwatermarkedUnionColumns, also mark every
column that a projection, aggregate or expansion in the analyzed plan computes
above the union from a column that the function already marks, whether it
renames that column or computes a new value from it, so that a batch whose
optimized plan has dropped the empty union input still meets a mark. Update the
scaladoc of findUnwatermarkedUnionColumns and the comment above eventTimeLags
in IncrementalExecution, and add legacy-mode union tests whose right input is
renamed above the union.
**Why this works:** Collect the marks as now, then go up the analyzed plan
from each union and add the output column of every projection, aggregate or
expansion entry whose expression reads a marked column, until nothing more is
added. lagBelow keeps checking the marks before it descends, so a renamed key
column is caught at the top of the walk, before it and the renamed
late-filtered column can both step to the same column of the remaining union
input, which is the step that returns lag zero today. A key that is the
late-filtered column itself still returns lag zero first.
**Compatibility:** Lags of columns that every union input watermarks, and
all behavior with multiple stateful operators allowed, stay as they are.
**Risks:** A column that a node above a union with an unwatermarked input
computes from the union's renamed late-filtered column, such as a window over a
renamed event time, then gets no bound in legacy mode, as the same column
already gets none when the event time keeps its name: an outer or left semi
join on it fails analysis, and an inner join keeps the other input's rows. A
key that a node above a union with an unwatermarked input computes from a
marked column with a function that the lag walk cannot read, which today keeps
the watermark as its cutoff, also gets no bound. No conf turns the change off,
as for the rest of the legacy-mode lags, and it changes nothing with multiple
stateful operators allowed.
**Constraints:** The analysis check and execution must keep reading the
marks through the same function, so that analysis never bounds a column that
some batch leaves unbounded. A join keyed on the late-filtered column itself,
renamed or not, keeps lag zero.
**Exclusions:**
- Unions whose inputs all have a watermark node: the optimizer never drops
such an input from a batch's plan, so their lags do not change between batches.
**Verification:**
- **Regression:** In legacy mode, an inner join on lk = k AND lt = c, whose
right input is a union of a watermarked input and an input without a watermark
node renamed through toDF("k", "t", "c"), keeps the match of a later row of the
second input with a left row stored before a batch in which that input had no
data, on state formats 2 and 3, and so does the same join on lk = k AND lt
BETWEEN c AND c + INTERVAL 1 HOUR.
- **Behavior:** The execution lags of that query are equal in a batch in
which both union inputs have data and in one in which the input without a
watermark node has none.
- **Compatibility:** Legacy-mode joins over unions whose inputs all have a
watermark node, and joins keyed on the union's late-filtered column, keep their
current lags and results.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -17,36 +17,659 @@
package org.apache.spark.sql.catalyst.analysis
+import java.util.Locale
+
+import scala.util.Try
import scala.util.control.NonFatal
import org.apache.spark.internal.Logging
import org.apache.spark.internal.LogKeys._
+import org.apache.spark.sql.catalyst.InternalRow
import org.apache.spark.sql.catalyst.expressions._
-import org.apache.spark.sql.catalyst.planning.ExtractEquiJoinKeys
-import org.apache.spark.sql.catalyst.plans.logical.{EventTimeWatermark,
LogicalPlan}
+import org.apache.spark.sql.catalyst.plans.logical.{Expand, Join, LogicalPlan,
Project, UnaryNode, Union}
import org.apache.spark.sql.catalyst.plans.logical.EventTimeWatermark._
-import org.apache.spark.sql.catalyst.util.DateTimeConstants.MICROS_PER_DAY
+import org.apache.spark.sql.catalyst.util.DateTimeConstants.{MICROS_PER_DAY,
MICROS_PER_HOUR, MICROS_PER_MILLIS, MICROS_PER_MINUTE, MICROS_PER_SECOND}
import org.apache.spark.sql.types._
import org.apache.spark.unsafe.types.CalendarInterval
+/**
+ * How far below a column that can filter its stream-stream join input's late
rows one of the
+ * input's watermarked columns can be, for an equality key or a range
condition on it: at most
+ * `micros` where the plan relates the two columns; by an amount that the plan
does not bound when
+ * `unbounded`; and by an amount that it does not show when `unrelated`,
because it does not relate
+ * the two. A window column is compared by its end, as eviction and late
filtering compare it.
+ */
+case class EventTimeLag(micros: Long, unrelated: Boolean, unbounded: Boolean) {
+ def max(other: EventTimeLag): EventTimeLag = EventTimeLag(math.max(micros,
other.micros),
+ unrelated || other.unrelated, unbounded || other.unbounded)
+
+ /**
+ * The cutoff for the other input's equality key when this input's watermark
is `watermark`.
+ * A key that the plan does not relate keeps the Spark 4.3 cutoff.
+ */
+ def keyWatermark(watermark: Long): Option[Long] =
+ if (unbounded) None else Some(watermark - EventTimeLag.ceilMillis(micros))
+
+ /**
+ * The watermark to substitute for the column in a range condition. Spark
4.3 substituted the
+ * watermark for every watermarked column; this does so only where the plan
bounds the lag.
+ */
+ def rangeWatermark(watermark: Long): Option[Long] =
+ if (unbounded || unrelated) None else Some(watermark -
EventTimeLag.ceilMillis(micros))
+}
+
+object EventTimeLag {
+ val zero: EventTimeLag = EventTimeLag(0L, unrelated = false, unbounded =
false)
+ val unrelated: EventTimeLag = EventTimeLag(0L, unrelated = true, unbounded =
false)
+ val unbounded: EventTimeLag = EventTimeLag(0L, unrelated = false, unbounded
= true)
+
+ private def ceilMillis(micros: Long): Long =
+ micros / MICROS_PER_MILLIS + (if (micros % MICROS_PER_MILLIS == 0) 0 else
1)
+}
+
+/**
+ * The [[EventTimeLag]] of the watermarked columns of stream-stream join
inputs, by expression ID;
+ * see [[StreamingJoinHelper.findEventTimeLags]]. A column missing from `lags`
has lag zero, so
+ * `EventTimeLags(Map.empty)` gives every watermarked column lag zero. That is
right when multiple
+ * stateful operators are allowed: execution then fails at start for a planned
input with two
+ * distinct watermarked columns, so the only one left filters late rows itself.
+ */
+case class EventTimeLags(lags: Map[ExprId, EventTimeLag]) {
+ /**
+ * The lag of `column` in a join input with output `inputAttributes`, if it
carries a watermark.
+ * The input's first watermarked column filters its late rows itself.
+ */
+ def lagOf(column: NamedExpression, inputAttributes: Seq[Attribute]):
Option[EventTimeLag] =
+ if (!column.metadata.contains(delayKey)) {
+ None
+ } else if (inputAttributes.find(_.metadata.contains(delayKey))
+ .exists(_.exprId == column.exprId)) {
+ Some(EventTimeLag.zero)
+ } else {
+ Some(lags.getOrElse(column.exprId, EventTimeLag.zero))
+ }
+}
+
+object EventTimeLags {
+ val none: EventTimeLags = EventTimeLags(Map.empty)
+}
+
/**
* Helper object for stream joins. See [[StreamingSymmetricHashJoinExec]] in
SQL for more details.
*/
object StreamingJoinHelper extends PredicateHelper with Logging {
/**
- * Check the provided logical plan to see if its join keys contain a
watermark attribute.
- *
- * Will return false if the plan is not an equijoin.
- * @param plan the logical plan to check
+ * Find the equality key filtered by this input's watermark. Its ordinal can
be used to
+ * evict the opposite input's state, whose equality keys have the same
ordering.
+ * For leftTime = rightTime, a watermark on rightTime bounds leftTime even
when leftTime
+ * has no watermark. It does not bound right-side state without a watermark
on leftTime.
+ * A key computed from the event time by adding constant intervals, such as
+ * leftTime = rightTime + INTERVAL 10 SECONDS or leftTime =
timestampadd(HOUR, 1, rightTime),
+ * is bounded too if the solver can count the intervals exactly or they
never move a time
+ * backward; see [[getStateKeyWatermark]]. The result does not depend on the
session time zone,
+ * so neither does the V4 state layout. Without `lags`, only the input's
first watermarked
+ * column counts as its event time; with them, every watermarked column that
they bound does.
+ */
+ def getStateKeyWatermarkOrdinal(
+ keys: Seq[Expression],
+ inputAttributes: Seq[Attribute],
+ lags: Option[EventTimeLags] = None): Option[Int] = {
+ getEventTimeKeyOrdinal(keys, inputAttributes, lags).orElse {
+ keys.indices.find(getStateKeyWatermark(keys, inputAttributes, _,
Some(0L), lags).isDefined)
+ }
+ }
+
+ /**
+ * Find the equality key that is this input's first watermarked column, or
else, with `lags`,
+ * the watermarked key with the smallest lag that bounds it; see
[[findEventTimeLags]].
+ */
+ def getEventTimeKeyOrdinal(
+ keys: Seq[Expression],
+ inputAttributes: Seq[Attribute],
+ lags: Option[EventTimeLags] = None): Option[Int] = {
+ // When multiple stateful operators are disabled, late filtering uses the
first event-time
+ // column. Otherwise, execution rejects multiple distinct event-time
columns.
+ inputAttributes.find(_.metadata.contains(delayKey)).flatMap { eventTime =>
+ Some(keys.indexWhere(_.semanticEquals(eventTime))).filter(_ >= 0).orElse
{
+ lags.flatMap { l =>
+ keys.indices.flatMap { i =>
+ keyLag(keys(i), inputAttributes, l).filterNot(_.unbounded).map(i
-> _.micros)
+ }.sortBy(_._2).headOption.map(_._1)
+ }
+ }
+ }
+ }
+
+ /** The lag of a key that is a watermarked column of the input. */
+ private def keyLag(
+ key: Expression,
+ inputAttributes: Seq[Attribute],
+ lags: EventTimeLags): Option[EventTimeLag] = key match {
+ case n: NamedExpression => lags.lagOf(n, inputAttributes)
+ case _ => None
+ }
+
+ /**
+ * The lag of every watermarked column of each stream-stream join input in
`plan`, combined
+ * over the inputs by [[EventTimeLag.max]]. This is for
+ * spark.sql.streaming.statefulOperator.allowMultiple=false, where an input
can keep several
+ * watermarked columns, such as its event time and a copy of it or a time
window over it, and
+ * filters late rows by the first of them. When `planned`, `plan` is the
optimized plan that runs,
+ * so each input filters late rows by its first watermarked column, and a
column's lag is taken
+ * against that one. Otherwise the optimizer can prune any watermarked
column before a column, so
+ * its lag is the largest against all of them. Spark 4.3 bounded state by
every watermarked
+ * column at the watermark. A lag lowers that cutoff; see [[EventTimeLag]].
+ */
+ def findEventTimeLags(plan: LogicalPlan, planned: Boolean): EventTimeLags = {
+ val lags = plan.collect {
+ case j: Join if j.left.isStreaming && j.right.isStreaming => Seq(j.left,
j.right)
+ }.flatten.flatMap { input =>
+ val watermarked =
input.output.filter(_.metadata.contains(delayKey)).map(_.exprId).distinct
+ watermarked.indices.map { i =>
+ val lateFiltered = if (planned) watermarked.take(1) else
watermarked.take(i)
+ watermarked(i) -> lateFiltered.filter(_ != watermarked(i)).map {
eventTime =>
+ lagBelow(input, watermarked(i), eventTime, Some(0L), Some(0L))
+ }.foldLeft(EventTimeLag.zero)(_ max _)
+ }
+ }
+ EventTimeLags(lags.groupMapReduce(_._1)(_._2)(_ max _))
+ }
+
+ /** How a column relates to the column of a node's child that [[lagBelow]]
follows for it. */
+ private case class Step(column: ExprId, offset: Option[Long])
+
+ /**
+ * How far `key` of `plan` can be below its column `eventTime`, which late
filtering compares
+ * with the watermark. Both are compared by their bounds: a time, or a
window's end. `keyLow` is
+ * the smallest that the join input's key is above `key`, and
`eventTimeHigh` the largest that the
+ * join input's late-filtered column is above `eventTime`; None means
without bound. The walk
+ * follows both columns down by expression ID: through a projection or an
expansion that passes
+ * them on, builds a time or session window from a single column, or, for
the key, shifts a
+ * timestamp by constant intervals; through any other node with one input
that outputs both, as
+ * such a node keeps an expression ID only for an unchanged value; into the
input of a join that
+ * outputs both; and into every input of a union, at the same positions. A
union input that does
+ * not watermark a column that the union, which takes its first input's
metadata, watermarks
+ * builds it some other way. Where both reach the same column, the lag is
the difference of the
+ * two offsets. Everything else leaves the columns unrelated.
+ */
+ private def lagBelow(
+ plan: LogicalPlan,
+ key: ExprId,
+ eventTime: ExprId,
+ keyLow: Option[Long],
+ eventTimeHigh: Option[Long]): EventTimeLag = {
+ def outputsBoth(p: LogicalPlan): Boolean =
+ p.output.exists(_.exprId == key) && p.output.exists(_.exprId ==
eventTime)
+ def follow(child: LogicalPlan, keyStep: Option[Step], eventTimeStep:
Option[Step]) =
+ (keyStep, eventTimeStep) match {
+ case (Some(k), Some(t)) => lagBelow(child, k.column, t.column,
+ addOffsets(keyLow, k.offset), addOffsets(eventTimeHigh, t.offset))
+ case _ => EventTimeLag.unrelated
+ }
+ if (key == eventTime) {
+ (keyLow, eventTimeHigh) match {
+ case (Some(low), Some(high)) => Try(Math.subtractExact(high,
low)).toOption match {
+ case Some(lag) => EventTimeLag(math.max(0L, lag), unrelated = false,
unbounded = false)
+ case None => EventTimeLag.unbounded
+ }
+ case _ => EventTimeLag.unbounded
+ }
+ } else {
+ plan match {
+ case p: Project =>
+ def entry(id: ExprId): Option[NamedExpression] =
p.projectList.find(_.exprId == id)
+ follow(p.child, entry(key).flatMap(keyStep),
entry(eventTime).flatMap(eventTimeStep))
+ case e: Expand =>
+ // The rewrite of a sliding window puts one window per projection
beside the child's
+ // columns, which every projection passes on.
+ def step(id: ExprId, window: (Seq[Expression], Attribute) =>
Option[Long]) = {
+ val entries = e.output.indexWhere(_.exprId == id) match {
+ case -1 => Nil
+ case index => e.projections.map(_(index))
+ }
+ entries.map {
+ case a: Attribute => Some(a.exprId)
+ case _ => None
+ }.distinct match {
+ case Seq(Some(passedOn)) => Some(Step(passedOn, Some(0L)))
+ case _ if e.output.exists(a => a.exprId == id &&
+ a.metadata.contains(TimeWindow.marker)) =>
+ entries.map(timeWindowSource).distinct match {
+ case Seq(Some(source)) => Some(Step(source.exprId,
window(entries, source)))
+ case _ => None
+ }
+ case _ => None
+ }
+ }
+ // A window ends after its time column, and at most its length after
it.
+ follow(e.child, step(key, (_, _) => Some(0L)), step(eventTime,
(entries, source) =>
+ entries.map(timeWindowLength(_, source)).reduceOption((a, b) =>
+ for (x <- a; y <- b) yield math.max(x, y)).flatten))
+ case u: Union =>
+ val keyIndex = u.output.indexWhere(_.exprId == key)
+ val eventTimeIndex = u.output.indexWhere(_.exprId == eventTime)
+ def unwatermarked(child: LogicalPlan, index: Int): Boolean =
+ u.output(index).metadata.contains(delayKey) &&
+ !child.output(index).metadata.contains(delayKey)
+ if (keyIndex < 0 || eventTimeIndex < 0) {
+ EventTimeLag.unrelated
+ } else {
+ u.children.map { child =>
+ if (unwatermarked(child, keyIndex) || unwatermarked(child,
eventTimeIndex)) {
+ EventTimeLag.unbounded
+ } else {
+ lagBelow(child, child.output(keyIndex).exprId,
+ child.output(eventTimeIndex).exprId, keyLow, eventTimeHigh)
+ }
+ }.reduce(_ max _)
+ }
+ case j: Join =>
+ j.children.find(outputsBoth).map(lagBelow(_, key, eventTime, keyLow,
eventTimeHigh))
+ .getOrElse(EventTimeLag.unrelated)
Review Comment:
Thanks, confirmed: with `bt BETWEEN at AND at + INTERVAL 10 MINUTES` in the
earlier join, `bt` now gets lag zero, so `AB.join(C, ak = ck AND ct BETWEEN bt
AND bt + INTERVAL 1 HOUR, "right_outer")` passes analysis and bounds C's state
at the watermark again. This review raises one remaining case as a new finding:
the same ties written with the interval on the bounded column's side are still
not read.
<!-- SPARK_DEV_REVIEW_REPLY
{"feedback_id":"inline:4587582096","thread_id":"inline:4587582096","verdict_sha256":"e28802263b5d04823cc48e018abd9e9bf706c73c976ebdd6a4d44f2080e67380"}
-->
--
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]