HeartSaVioR commented on code in PR #60280:
URL: https://github.com/apache/spark/pull/60280#discussion_r4604032837
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -17,36 +17,720 @@
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]].
+ */
+ 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)
Review Comment:
> [!NOTE]
> **DISCLAIMER:** This comment was written by an LLM: Claude Opus 5.5
(`claude-opus-5-5`, 1M context), running as an SP2K agent on behalf of
@HeartSaVioR.
Thanks, fixed in
[ab59957f358](https://github.com/apache/spark/pull/60280/commits/ab59957f3582d270164fd563b24f31603ff5e54c).
The ranking now puts keys that the plan relates to the late-filtered column
before
keys that it does not relate, and sorts each group by lag. In your example
`ax` wins, with the
cutoff at the watermark less 20 seconds. When every candidate key is
unrelated, the first one in
key order wins with the full watermark, as in Spark 4.3.
Tests: your shape as an inner and a left outer join, on state formats 2 and
3. A left row whose
`lu` is below the watermark but whose `lx` is above the `ax` cutoff stays in
state, and a later
A row joins it. Without the fix, the inner join loses that match, and the
left outer join emits
the left row padded with nulls first.
<!-- sp2k-review11 reply 4598159087 -->
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -17,36 +17,720 @@
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]].
+ */
+ def getEventTimeKeyOrdinal(
+ keys: Seq[Expression],
+ inputAttributes: Seq[Attribute],
+ lags: Option[EventTimeLags] = None): Option[Int] = {
+ // When multiple stateful operators are disabled, late filtering uses the
first event-time
+ // column. Otherwise, execution rejects multiple distinct event-time
columns.
+ inputAttributes.find(_.metadata.contains(delayKey)).flatMap { eventTime =>
+ Some(keys.indexWhere(_.semanticEquals(eventTime))).filter(_ >= 0).orElse
{
+ lags.flatMap { l =>
+ keys.indices.flatMap { i =>
+ keyLag(keys(i), inputAttributes, l).filterNot(_.unbounded).map(i
-> _.micros)
+ }.sortBy(_._2).headOption.map(_._1)
}
+ }
+ }
+ }
+
+ /** The lag of a key that is a watermarked column of the input. */
+ private def keyLag(
+ key: Expression,
+ inputAttributes: Seq[Attribute],
+ lags: EventTimeLags): Option[EventTimeLag] = key match {
+ case n: NamedExpression => lags.lagOf(n, inputAttributes)
+ case _ => None
+ }
+
+ /**
+ * The lag of every watermarked column of each stream-stream join input in
`plan`, combined
+ * over the inputs by [[EventTimeLag.max]]. This is for
+ * spark.sql.streaming.statefulOperator.allowMultiple=false, where an input
can keep several
+ * watermarked columns, such as its event time and a copy of it or a time
window over it, and
+ * filters late rows by the first of them. When `planned`, `plan` is the
optimized plan that runs,
+ * so each input filters late rows by its first watermarked column, and a
column's lag is taken
+ * against that one. Otherwise the optimizer can prune any watermarked
column before a column, so
+ * its lag is the largest against all of them. Spark 4.3 bounded state by
every watermarked
+ * column at the watermark. A lag lowers that cutoff; see [[EventTimeLag]].
+ */
+ def findEventTimeLags(plan: LogicalPlan, planned: Boolean): EventTimeLags = {
+ val lags = plan.collect {
+ case j: Join if j.left.isStreaming && j.right.isStreaming => Seq(j.left,
j.right)
+ }.flatten.flatMap { input =>
+ val watermarked =
input.output.filter(_.metadata.contains(delayKey)).map(_.exprId).distinct
+ watermarked.indices.map { i =>
+ val lateFiltered = if (planned) watermarked.take(1) else
watermarked.take(i)
+ watermarked(i) -> lateFiltered.filter(_ != watermarked(i)).map {
eventTime =>
+ lagBelow(input, watermarked(i), eventTime, Some(0L), Some(0L))
+ }.foldLeft(EventTimeLag.zero)(_ max _)
+ }
+ }
+ EventTimeLags(lags.groupMapReduce(_._1)(_._2)(_ max _))
+ }
+
+ /** How a column relates to the column of a node's child that [[lagBelow]]
follows for it. */
+ private case class Step(column: ExprId, offset: Option[Long])
+
+ /**
+ * How far `key` of `plan` can be below its column `eventTime`, which late
filtering compares
+ * with the watermark. Both are compared by their bounds: a time, or a
window's end. `keyLow` is
+ * the smallest that the join input's key is above `key`, and
`eventTimeHigh` the largest that the
+ * join input's late-filtered column is above `eventTime`; None means
without bound. The walk
+ * follows both columns down by expression ID: through a projection or an
expansion that passes
+ * them on, builds a time or session window from a single column, or, for
the key, shifts a
+ * timestamp by constant intervals; through any other node with one input
that outputs both, as
+ * such a node keeps an expression ID only for an unchanged value; into the
input of a join that
+ * outputs both, or into both inputs of one that outputs each from a
different input and equates
+ * them through its condition (see [[lagThroughJoinCondition]]); and into
every input of a union,
+ * at the same positions. A union input that does not watermark a column
that the union, which
+ * takes its first input's metadata, watermarks builds it some other way, so
the lag is
+ * unbounded. Where both reach the same column, the lag is the difference of
the two offsets.
+ * Everything else leaves the columns unrelated.
+ */
+ private def lagBelow(
+ plan: LogicalPlan,
+ key: ExprId,
+ eventTime: ExprId,
+ keyLow: Option[Long],
+ eventTimeHigh: Option[Long]): EventTimeLag = {
+ def outputsBoth(p: LogicalPlan): Boolean =
+ p.output.exists(_.exprId == key) && p.output.exists(_.exprId ==
eventTime)
+ def follow(child: LogicalPlan, keyStep: Option[Step], eventTimeStep:
Option[Step]) =
+ (keyStep, eventTimeStep) match {
+ case (Some(k), Some(t)) => lagBelow(child, k.column, t.column,
+ addOffsets(keyLow, k.offset), addOffsets(eventTimeHigh, t.offset))
+ case _ => EventTimeLag.unrelated
+ }
+ if (key == eventTime) {
+ (keyLow, eventTimeHigh) match {
+ case (Some(low), Some(high)) => Try(Math.subtractExact(high,
low)).toOption match {
+ case Some(lag) => EventTimeLag(math.max(0L, lag), unrelated = false,
unbounded = false)
+ case None => EventTimeLag.unbounded
+ }
+ case _ => EventTimeLag.unbounded
+ }
+ } else {
+ plan match {
+ case p: Project =>
+ def entry(id: ExprId): Option[NamedExpression] =
p.projectList.find(_.exprId == id)
+ follow(p.child, entry(key).flatMap(keyStep),
entry(eventTime).flatMap(eventTimeStep))
+ case e: Expand =>
+ // The rewrite of a sliding window puts one window per projection
beside the child's
+ // columns, which every projection passes on.
+ def step(id: ExprId, window: (Seq[Expression], Attribute) =>
Option[Long]) = {
+ val entries = e.output.indexWhere(_.exprId == id) match {
+ case -1 => Nil
+ case index => e.projections.map(_(index))
+ }
+ entries.map {
+ case a: Attribute => Some(a.exprId)
+ case _ => None
+ }.distinct match {
+ case Seq(Some(passedOn)) => Some(Step(passedOn, Some(0L)))
+ case _ if e.output.exists(a => a.exprId == id &&
+ a.metadata.contains(TimeWindow.marker)) =>
+ entries.map(timeWindowSource).distinct match {
+ case Seq(Some(source)) => Some(Step(source.exprId,
window(entries, source)))
+ case _ => None
+ }
+ case _ => None
+ }
+ }
+ // A window ends after its time column, and at most its length after
it.
+ follow(e.child, step(key, (_, _) => Some(0L)), step(eventTime,
(entries, source) =>
+ entries.map(timeWindowLength(_, source)).reduceOption((a, b) =>
+ for (x <- a; y <- b) yield math.max(x, y)).flatten))
+ case u: Union =>
+ val keyIndex = u.output.indexWhere(_.exprId == key)
+ val eventTimeIndex = u.output.indexWhere(_.exprId == eventTime)
+ def unwatermarked(child: LogicalPlan, index: Int): Boolean =
+ u.output(index).metadata.contains(delayKey) &&
+ !child.output(index).metadata.contains(delayKey)
+ if (keyIndex < 0 || eventTimeIndex < 0) {
+ EventTimeLag.unrelated
+ } else {
+ u.children.map { child =>
+ if (unwatermarked(child, keyIndex) || unwatermarked(child,
eventTimeIndex)) {
+ EventTimeLag.unbounded
+ } else {
+ lagBelow(child, child.output(keyIndex).exprId,
+ child.output(eventTimeIndex).exprId, keyLow, eventTimeHigh)
+ }
+ }.reduce(_ max _)
+ }
+ case j: Join =>
+ j.children.find(outputsBoth).map(lagBelow(_, key, eventTime, keyLow,
eventTimeHigh))
+ .getOrElse(lagThroughJoinCondition(j, key, eventTime, keyLow,
eventTimeHigh))
+ case u: UnaryNode if outputsBoth(u.child) =>
+ lagBelow(u.child, key, eventTime, keyLow, eventTimeHigh)
+ case _ => EventTimeLag.unrelated
+ }
+ }
+ }
+
+ /**
+ * The lag of `key` below `eventTime` of [[lagBelow]] where `join` outputs
them from different
+ * inputs, through an equality `x = y` in its condition between a
watermarked column x of the
+ * key's input and a watermarked column y of the event time's input: the key
is at most its lag
+ * below x, which equals y, which is at most its lag below the event time,
so the lags add up.
+ * That holds on every row that the join outputs with a non-NULL key: all
rows of an inner join
+ * satisfy its condition, and so do those of a left or right outer join that
pads the key's
+ * input, whose other rows carry a NULL key that no condition matches. The
smallest bounded lag
+ * over such equalities wins. Other conjuncts, such as a range or a shifted
equality, and other
+ * join types leave the columns unrelated.
+ */
+ private def lagThroughJoinCondition(
+ join: Join,
+ key: ExprId,
+ eventTime: ExprId,
+ keyLow: Option[Long],
+ eventTimeHigh: Option[Long]): EventTimeLag = {
+ def watermarked(p: LogicalPlan): Set[ExprId] =
+ p.output.filter(_.metadata.contains(delayKey)).map(_.exprId).toSet
+ def outputs(p: LogicalPlan, id: ExprId): Boolean =
p.output.exists(_.exprId == id)
+ val inputs = if (outputs(join.left, key) && outputs(join.right,
eventTime)) {
+ Some((join.left, join.right))
+ } else if (outputs(join.right, key) && outputs(join.left, eventTime)) {
+ Some((join.right, join.left))
+ } else {
+ None
+ }
+ val lags = inputs.filter { case (keyInput, _) =>
+ join.joinType match {
+ case _: InnerLike => true
+ case LeftOuter => keyInput eq join.right
+ case RightOuter => keyInput eq join.left
+ case _ => false
+ }
+ }.toSeq.flatMap { case (keyInput, eventTimeInput) =>
+ val keyColumns = watermarked(keyInput)
+ val eventTimeColumns = watermarked(eventTimeInput)
+ join.condition.toSeq.flatMap(splitConjunctivePredicates).flatMap {
+ case EqualTo(a: Attribute, b: Attribute) => Seq(a.exprId -> b.exprId,
b.exprId -> a.exprId)
+ case _ => Nil
+ }.filter { case (x, y) => keyColumns.contains(x) &&
eventTimeColumns.contains(y) }
+ .map { case (x, y) =>
+ val below = lagBelow(keyInput, key, x, keyLow, Some(0L))
+ val above = lagBelow(eventTimeInput, y, eventTime, Some(0L),
eventTimeHigh)
+ if (below.unrelated || above.unrelated) {
+ EventTimeLag.unrelated
+ } else {
+ Try(Math.addExact(below.micros, above.micros)).toOption
+ .filter(_ => !below.unbounded && !above.unbounded)
+ .map(EventTimeLag(_, unrelated = false, unbounded = false))
+ .getOrElse(EventTimeLag.unbounded)
+ }
+ }
+ }
+ lags.filter(lag => !lag.unrelated &&
!lag.unbounded).sortBy(_.micros).headOption
+ .getOrElse(EventTimeLag.unrelated)
Review Comment:
> [!NOTE]
> **DISCLAIMER:** This comment was written by an LLM: Claude Opus 5.5
(`claude-opus-5-5`, 1M context), running as an SP2K agent on behalf of
@HeartSaVioR.
Thanks, fixed as you suggested. The join step of the legacy-mode lag walk
now reads every
conjunct of the earlier join's condition that bounds a watermarked TIMESTAMP
column of the key's
input from below by a watermarked column of the other input plus constant
intervals: `x >= y + c`,
`x > y + c`, `x = y + c`, or the lower half of a BETWEEN, which it reads as
the two comparisons
that the optimizer makes of it, so analysis and execution find the same
ties. It adds the bound to
the two lags, as for an equality. A constant whose whole days, months or
years can move a time
backward gives no bound, as for keys. When the conjuncts tie the columns but
no tie has a bounded
lag, the lag now has no bound, instead of being unrelated, so the key bounds
no state; this
covers your union example. A conjunct that bounds the column only from above
is not a tie, so
such a key keeps the Spark 4.3 cutoff, as an unrelated key does. Key-only
and full outer earlier
joins still leave the columns unrelated.
Tests: after an inner or left outer join on `ak = bk AND bt BETWEEN at AND
at + INTERVAL 10
MINUTES`, the right outer form of the chain passes analysis and outputs C's
unmatched row once
the watermark passes it, and the inner form evicts C's state, on state
formats 2 and 3. With
`bt >= at - INTERVAL 1 HOUR`, a C row still matches an AB row whose `bt` is
600 seconds below `at`
after the watermark passed the C row. A chained inner join whose earlier
join ties `bt` to a copy
of `at` shifted back one day keeps the match of a C row a day below the
watermark, and its right
outer form fails analysis. The lag test that expected `at <= bt` to leave
the columns unrelated
now expects lag zero, and new lag tests cover `>`, a shifted equality, a
BETWEEN in a left outer
join, an upper-only conjunct and a day shift.
<!-- sp2k-review11 reply 4598159095 -->
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala:
##########
@@ -167,6 +171,29 @@ class IncrementalExecution(
private val allowMultipleStatefulOperators: Boolean =
sparkSession.sessionState.conf.getConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE)
+ // The lags of the planned join inputs, against the columns that they filter
late rows by. They
+ // read the optimized plan, whose expression IDs the planned joins use. The
analysis check reads
+ // the analyzed plan with the same rule, against every column that pruning
can leave first, so
+ // it bounds a column here whenever it bounds one there. The projections
that build the later
+ // watermarked columns stay in every batch's optimized plan: they sit above
the input's
+ // watermark node, which the optimizer keeps even for a batch without data.
+ private lazy val eventTimeLags: Option[EventTimeLags] =
+ if (allowMultipleStatefulOperators) {
+ None
+ } else {
+ Some(StreamingJoinHelper.findEventTimeLags(optimizedPlan, planned =
true))
Review Comment:
> [!NOTE]
> **DISCLAIMER:** This comment was written by an LLM: Claude Opus 5.5
(`claude-opus-5-5`, 1M context), running as an SP2K agent on behalf of
@HeartSaVioR.
Thanks, fixed in
[ab59957f358](https://github.com/apache/spark/pull/60280/commits/ab59957f3582d270164fd563b24f31603ff5e54c).
The walk still runs on each batch's optimized plan, so keys that the optimizer
renames keep their bound. In addition, Spark now reads from the batch's
analyzed plan, which
keeps every union input, the columns at each union position that the union
watermarks and one of
its inputs does not: the union's column and every input's column there. A
column that reaches one
of them has no bound. Analysis uses the same rule on its own plan, so
analysis and execution
agree in every batch. The comment above `eventTimeLags` is corrected.
Tests: legacy-mode inner joins with an equality key and with a range on a
column that a union
input builds without a watermark, on state formats 2 and 3. After a batch
where that input has no
data, a later row of it still joins a left row stored earlier.
<!-- sp2k-review11 reply 4598159103 -->
##########
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:
> [!NOTE]
> **DISCLAIMER:** This comment was written by an LLM: Claude Opus 5.5
(`claude-opus-5-5`, 1M context), running as an SP2K agent on behalf of
@HeartSaVioR.
Thanks, and you were right that leaving range ties out kept a regression
from Spark 4.3. The new
commit
[ab59957f358](https://github.com/apache/spark/pull/60280/commits/ab59957f3582d270164fd563b24f31603ff5e54c)
reads them: a conjunct of the earlier join that bounds the column from below
by the other
input's watermarked column plus constant intervals, such as `bt BETWEEN at
AND at + INTERVAL 10
MINUTES`, now relates the two columns, with the bound added to the lags as
for an equality. Your
chained join passes analysis again and evicts C's state at the watermark.
Details and tests are in
the reply on line 335.
<!-- sp2k-review11 reply 4587582096 -->
--
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]