spark-test commented on code in PR #60284:
URL: https://github.com/apache/spark/pull/60284#discussion_r4607461664
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -186,6 +910,48 @@ object StreamingJoinHelper extends PredicateHelper with
Logging {
return None
}
+ // The terms count a whole day as 24 hours, although Spark adds days in
the session time
+ // zone, where a day can be 23 or 25 hours, and read CAST(ts AS BIGINT) as
ts, although the
+ // cast drops the fraction of a second. Either can put the cutoff above a
row that can still
+ // match. A column with its own watermark keeps such a cutoff, as existing
queries rely on
+ // it. With exactForUnwatermarkedColumns, any other column, such as the
bounded column of an
+ // input without a watermark, gets no cutoff from such a condition.
+ val stateColumnHasWatermark = constraintTerm.exists {
+ case a: AttributeReference =>
+ attributesToFindStateWatermarkFor.contains(a) &&
a.metadata.contains(delayKey)
+ case _ => false
+ }
+ if (exactForUnwatermarkedColumns && !stateColumnHasWatermark &&
+ hasInexactArithmetic(allOnLeftExpr)) {
+ logDebug(s"Inexact arithmetic gives an unwatermarked column no cutoff:
$allOnLeftExpr")
+ return None
+ }
+
+ // State eviction compares this cutoff in timestamp units against the
constrained column, or
+ // against its end for a time window; see [[isWindowEvictionSafe]].
+ val stateColumn = constraintTerm.collectFirst {
+ case a: AttributeReference if
attributesToFindStateWatermarkFor.contains(a) => a
+ }
+ val watermarkColumn = terms.flatMap(_.collect {
+ case a: AttributeReference
+ if attributesWithEventWatermark.contains(a) &&
a.metadata.contains(delayKey) => a
+ }).headOption
+ val canEvictStateColumn = stateColumn.exists { column =>
+ column.dataType == TimestampType ||
watermarkColumn.exists(isWindowEvictionSafe(column, _))
+ }
+ if (!baseAdmissionRules && !canEvictStateColumn) return None
+
+ // A bound needs a term on the opposite input's watermarked event time; a
conjunct that uses
+ // only constants does not follow the watermark, and gives a cutoff only
with
+ // keepConstantOnly. The occurrence check above limits each input to one
attribute, so there
+ // can be at most one such term.
+ // TODO(SPARK-61350): a watermark term with a negative coefficient still
passes this check.
+ val watermarkTerms =
terms.filter(_.references.exists(attributesWithEventWatermark.contains))
+ if (!baseAdmissionRules && (watermarkTerms.isEmpty && !keepConstantOnly ||
Review Comment:
Thanks, this fixes the bounds this comment named: the interval product, the
other computed intervals, the numeric arithmetic and the negated comparison now
count at start, and the rule of earlier versions still reads the analyzed
condition. One spelling of a range bound still fails at start beside a
constant-only conjunct: a SQL BETWEEN whose bound is computed, which this
review raises as a new finding.
<!-- SPARK_DEV_REVIEW_REPLY
{"feedback_id":"inline:4598373596","thread_id":"inline:4598373596","verdict_sha256":"9b3a9877b7e858f7f2de4b67d9f9ca1259bcf03c63e7c862cc55b4d5a50d7c64"}
-->
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -114,7 +906,23 @@ object StreamingJoinHelper extends PredicateHelper with
Logging {
}
stateWatermark
}
- allStateWatermarks.reduceOption((x, y) => Math.min(x, y))
+
+ val conjuncts = splitConjunctivePredicates(joinCondition.get)
+ val boundingConjuncts = conjuncts.flatMap { predicate =>
+ stateWatermarkOf(predicate, keepConstantOnly = false).map(predicate -> _)
+ }
+ // A constant-only conjunct is left out when the other bounds follow the
watermark exactly.
+ // The solver can over-estimate an inexact bound, such as a truncating
cast or whole days,
+ // above a row that can still match. A constant's cutoff keeps that row,
as in earlier
+ // versions, so keep the constants in the minimum then.
Review Comment:
**Nit (P3):** This branch keeps constant-only cutoffs in the minimum beside
a truncating cast or an interval of a day or more, so an outer join of that
shape still never evicts or outputs its preserved input's unmatched rows, which
is the failure this PR fixes for exact bounds. The comment gives the reason but
not that the case is deferred or what lifts it, while the stack's other
exemptions in this file carry TODO(SPARK-61381) or TODO(SPARK-61510), for
example at lines 1006 and 1095. Without a TODO at this branch, a later change
to `hasInexactArithmetic` or to the solver can keep the cap needlessly or drop
it unsafely:
```suggestion
// A constant-only conjunct is left out when the other bounds follow the
watermark exactly.
// The solver can over-estimate an inexact bound, such as a truncating
cast or whole days,
// above a row that can still match. A constant's cutoff keeps that row,
as in earlier
// versions, so keep the constants in the minimum then.
// TODO(SPARK-61381): once inexact bounds get conservative cutoffs,
leave the constants out
// of the minimum here too. Until then an outer join with such a bound
and a constant-only
// conjunct on its preserved input keeps that input's rows in state
and never outputs them
// unmatched, as in earlier versions.
```
**Verification:**
- **Inspection:** The comment above the exemption that keeps constant-only
cutoffs beside an inexact bound, at StreamingJoinHelper.scala:914-917, names
SPARK-61381, states what outer joins of that shape keep until then and what
lifts the exemption, and the code it describes is unchanged.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -17,36 +17,802 @@
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.trees.TreePattern
+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]]. 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)
+ case Between(input, lower, upper, _) => lowerBound(input, lower) ++
lowerBound(upper, input)
+ case _ => Nil
+ }.filter { case (x, y, _) => keyColumns.contains(x) &&
eventTimeColumns.contains(y) }
+ .map { case (x, y, shift) =>
+ val below = lagBelow(keyInput, key, x, keyLow, Some(0L),
unwatermarkedUnion)
+ val above = lagBelow(eventTimeInput, y, eventTime, Some(0L),
eventTimeHigh,
+ unwatermarkedUnion)
+ if (below.unrelated || above.unrelated) {
+ EventTimeLag.unrelated
+ } else {
+ shift.filter(_ => !below.unbounded && !above.unbounded).flatMap {
c =>
+ Try(Math.subtractExact(Math.addExact(below.micros,
above.micros), c)).toOption
+ }.map(lag => EventTimeLag(math.max(0L, lag), unrelated = false,
unbounded = false))
+ .getOrElse(EventTimeLag.unbounded)
+ }
+ }
+ }
+ lags.filter(lag => !lag.unrelated &&
!lag.unbounded).sortBy(_.micros).headOption
+ .getOrElse(if (lags.exists(_.unbounded)) EventTimeLag.unbounded else
EventTimeLag.unrelated)
+ }
+
+ // An offset too large to count in microseconds has no bound.
+ private def addOffsets(a: Option[Long], b: Option[Long]): Option[Long] =
+ for (x <- a; y <- b; sum <- Try(Math.addExact(x, y)).toOption) yield sum
+
+ /** The only attribute that `e` references, if there is one. */
+ private def singleReference(e: Expression): Option[Attribute] =
e.references.toSeq match {
+ case Seq(a) => Some(a)
+ case _ => None
+ }
+
+ /**
+ * The step of [[lagBelow]] for the key's projection entry `entry`: the
column it follows and the
+ * smallest that the entry is above it, None without bound.
+ */
+ private def keyStep(entry: NamedExpression): Option[Step] = entry match {
+ case a: Attribute => Some(Step(a.exprId, Some(0L)))
+ case Alias(a: Attribute, _) => Some(Step(a.exprId, Some(0L)))
+ // A window ends after its time column.
+ case Alias(child, _) if entry.metadata.contains(TimeWindow.marker) =>
+ timeWindowSource(child).map(source => Step(source.exprId, Some(0L)))
+ case Alias(child, _) if entry.metadata.contains(SessionWindow.marker) =>
+ sessionWindowSource(child).map(source => Step(source.exprId, Some(0L)))
+ case Alias(child, _) if child.dataType == TimestampType =>
+ singleReference(child).filter(_.dataType == TimestampType).flatMap {
source =>
+ // A shift whose whole days, months or years can move a time backward
has no bound
+ // here, as for equality keys.
+ intervalShift(child, source).map { shift =>
+ Step(source.exprId, Some(shift.min).filter(_ => shift.exact ||
shift.forward))
+ }
+ }
+ case _ => None
+ }
+
+ /**
+ * The step of [[lagBelow]] for the late-filtered column's projection entry
`entry`: the column
+ * it follows and the largest that the entry is above it, None without bound.
+ */
+ private def eventTimeStep(entry: NamedExpression): Option[Step] = entry
match {
+ case a: Attribute => Some(Step(a.exprId, Some(0L)))
+ case Alias(a: Attribute, _) => Some(Step(a.exprId, Some(0L)))
+ case Alias(child, _) if entry.metadata.contains(TimeWindow.marker) =>
+ timeWindowSource(child).map(source => Step(source.exprId,
timeWindowLength(child, source)))
+ // A session ends its gap after the column, or without bound for a gap
that is not constant.
+ case Alias(child, _) if entry.metadata.contains(SessionWindow.marker) =>
+ sessionWindowSource(child).map { source =>
+ val end = child match {
+ case CreateNamedStruct(Seq(_, _, _, end)) =>
Some(withoutConversions(end))
+ case _ => None
+ }
+ Step(source.exprId, end.flatMap(intervalShift(_, source)).map(_.max))
+ }
+ case _ => None
+ }
+
+ /**
+ * The length of the time window that `window` builds from `source`,
evaluated with `source` at
+ * the epoch. Spark counts window durations in fixed microseconds, so it is
the same for every
+ * time.
+ */
+ private def timeWindowLength(window: Expression, source: Attribute):
Option[Long] = {
+ try {
+ window.transform {
+ case a: Attribute if a.exprId == source.exprId => Literal(0L,
source.dataType)
+ }.eval() match {
+ case row: InternalRow if !row.isNullAt(0) && !row.isNullAt(1) =>
+ Some(row.getLong(1) - row.getLong(0))
+ case _ => None
+ }
+ } catch {
+ case NonFatal(_) => None
+ }
+ }
+
+ /**
+ * The time column of a time window, when the window is built from that
column itself: the
+ * rewrite of window() reads its time column only through a conversion to
microseconds.
+ */
+ private def timeWindowSource(window: Expression): Option[Attribute] =
+ window.collect { case PreciseTimestampConversion(time, _, LongType) =>
time }.distinct match {
+ case Seq(a: Attribute) if window.references.toSeq == Seq(a) => Some(a)
+ case _ => None
+ }
+
+ /** The time column of a session window, which is its start. */
+ private def sessionWindowSource(window: Expression): Option[Attribute] =
window match {
+ case CreateNamedStruct(Seq(_, start, _, _)) => withoutConversions(start)
match {
+ case a: Attribute => Some(a)
+ case _ => None
+ }
+ case _ => None
+ }
+
+ /** The expression without the conversions that the session window rewrite
adds around it. */
+ private def withoutConversions(e: Expression): Expression = e match {
+ case PreciseTimestampConversion(child, _, _) => withoutConversions(child)
+ case KnownNullable(child) => withoutConversions(child)
+ case other => other
+ }
+
+ /**
+ * Get the cutoff for the opposite input's equality key at `ordinal`, given
this input's
+ * watermark. `keys` and `inputAttributes` belong to this input, whose
future rows have an event
+ * time above the watermark. When the key is that event time, the equal key
of any state row
+ * they can still match is above the watermark too; with `lags`, so is a key
on another
+ * watermarked column, less its lag. When the key is the event time shifted
by exact intervals,
+ * solving `stateKey >= rightTime + INTERVAL 10 SECONDS` shifts the cutoff
by that interval, less
+ * 1 ms as for range conditions. When the shift has whole days, months or
years but never moves a
+ * time backward, the cutoff is the watermark itself. Returns None for any
other key, including a
+ * shift with whole days, months or years that can move a time backward.
+ */
+ def getStateKeyWatermark(
+ keys: Seq[Expression],
+ inputAttributes: Seq[Attribute],
+ ordinal: Int,
+ eventWatermark: Option[Long],
+ lags: Option[EventTimeLags] = None): Option[Long] = {
+ // The watermark that bounds a watermarked column of this input.
+ def watermarkOf(column: NamedExpression): Option[Long] = lags match {
+ case Some(l) => l.lagOf(column, inputAttributes).flatMap { lag =>
+ eventWatermark.flatMap(lag.keyWatermark)
+ }
+ case None => eventWatermark.filter { _ =>
+
inputAttributes.find(_.metadata.contains(delayKey)).exists(_.semanticEquals(column))
+ }
+ }
+ keys(ordinal) match {
+ case column: NamedExpression if watermarkOf(column).isDefined =>
watermarkOf(column)
+ case key => shiftOfKey(key, inputAttributes, lags.isDefined).flatMap {
+ case KeyShift(eventTime, true, _) =>
+ val stateKey = AttributeReference("stateKey", TimestampType)()
+ getStateValueWatermark(AttributeSet(Seq(stateKey)),
AttributeSet(Seq(eventTime)),
+ Some(GreaterThanOrEqual(stateKey, withIntervalLiterals(key))),
+ watermarkOf(eventTime))
+ // The solver cannot count this shift, but it keeps the key of every
future row at or
+ // above that row's event time, which is above the watermark.
+ case KeyShift(eventTime, false, true) => watermarkOf(eventTime)
+ case _ => None
+ }
+ }
+ }
+
+ /**
+ * Get the cutoff for this input's range-bounded columns `stateAttributes`
from the opposite
+ * input's watermark, as [[getStateValueWatermark]] does with the opposite
input's
+ * `otherInputAttributes`. Without `lags`, only the opposite input's first
watermarked column
+ * counts as its event time; with them, each of its watermarked columns does
at its own
+ * watermark, the watermark less its lag, where they bound it; see
[[EventTimeLag]].
+ * `exactForUnwatermarkedColumns` is passed on to
[[getStateValueWatermark]], which this
+ * always asks to give no cutoff from a watermark term with the sign of an
unwatermarked column.
+ */
+ def getStateValueWatermarkForLags(
+ stateAttributes: AttributeSet,
+ otherInputAttributes: Seq[Attribute],
+ joinCondition: Option[Expression],
+ eventWatermark: Option[Long],
+ lags: Option[EventTimeLags],
+ exactForUnwatermarkedColumns: Boolean = false): Option[Long] = {
+ val watermarked =
otherInputAttributes.filter(_.metadata.contains(delayKey))
+ val eventTimes = lags match {
+ case Some(l) => watermarked.distinctBy(_.exprId).flatMap { column =>
+ l.lagOf(column, otherInputAttributes).flatMap { lag =>
+ eventWatermark.flatMap(lag.rangeWatermark)
+ }.map(column -> _)
+ }
+ case None => watermarked.headOption.toSeq.flatMap(c =>
eventWatermark.map(c -> _))
+ }
+ // A conjunct on two of these columns gets no cutoff either way, so
solving for each column
+ // alone and taking the lowest gives the cutoff of all of them at their
own watermarks.
+ eventTimes.flatMap { case (column, watermark) =>
+ getStateValueWatermark(stateAttributes, AttributeSet(Seq(column)),
joinCondition,
+ Some(watermark), exactForUnwatermarkedColumns)
+ }.minOption
+ }
+
+ /**
+ * Get a bound on this input's event time for state rows whose equality key
at `ordinal` is
+ * above `keyWatermark`. When the key is the event time, the bound is the
key watermark. When
+ * the key is the event time shifted by exact intervals, solving
+ * `leftTime + INTERVAL 10 SECONDS >= keyWatermark` subtracts that constant,
less 1 ms.
+ * Returns None for any other key, including any shift with whole days,
months or years.
*/
- def isWatermarkInJoinKeys(plan: LogicalPlan): Boolean = {
- plan match {
- case ExtractEquiJoinKeys(_, leftKeys, rightKeys, _, _, _, _, _) =>
- (leftKeys ++ rightKeys).exists {
- case a: AttributeReference =>
a.metadata.contains(EventTimeWatermark.delayKey)
- case _ => false
+ def getEventTimeWatermarkFromKey(
+ keys: Seq[Expression],
+ inputAttributes: Seq[Attribute],
+ ordinal: Int,
+ keyWatermark: Long): Option[Long] = {
+ if (getEventTimeKeyOrdinal(keys, inputAttributes).contains(ordinal)) {
+ Some(keyWatermark)
+ } else {
+ // TODO(SPARK-61381): bound a shift that is not exact too, such as
+ // `leftTime = rightTime + INTERVAL 1 DAY`. Until then such a key
gives its input no
+ // event-time bound, so the join holds the output watermark at 0 for
that input.
+ shiftOfKey(keys(ordinal), inputAttributes).filter(_.exact).flatMap {
shift =>
+ val keyWithWatermark = AttributeReference("stateKey", TimestampType,
+ metadata = new MetadataBuilder().putLong(delayKey, 0L).build())()
+ getStateValueWatermark(AttributeSet(Seq(shift.eventTime)),
+ AttributeSet(Seq(keyWithWatermark)),
+ Some(GreaterThanOrEqual(withIntervalLiterals(keys(ordinal)),
keyWithWatermark)),
+ Some(keyWatermark))
+ }
+ }
+ }
+
+ /**
+ * Whether the key is this input's event time shifted by constant intervals
that never move a
+ * time backward. [[getStateKeyWatermark]] bounds the opposite state by such
a key at the
+ * watermark plus the shift for an exact interval, and at the watermark
itself otherwise, so it
+ * is never below the watermark.
+ */
+ def isForwardShiftOfEventTime(key: Expression, inputAttributes:
Seq[Attribute]): Boolean =
+ shiftOfKey(key, inputAttributes).exists(_.forward)
+
+ /**
+ * A timestamp key computed from the input's event time by constant
intervals. `exact` means
+ * the solver counts the shift exactly; `forward` means the shift never
moves a time backward.
+ */
+ private case class KeyShift(eventTime: Attribute, exact: Boolean, forward:
Boolean)
+
+ /**
+ * How a timestamp key shifts the input's event time, if the solver or its
sign bounds it. With
+ * `anyWatermarkedColumn`, the shifted column can be any watermarked column
of the input.
+ */
+ private def shiftOfKey(
+ key: Expression,
+ inputAttributes: Seq[Attribute],
+ anyWatermarkedColumn: Boolean = false): Option[KeyShift] = {
+ val eventTime = if (anyWatermarkedColumn) {
+ singleReference(key).filter { column =>
+ column.metadata.contains(delayKey) && inputAttributes.exists(_.exprId
== column.exprId)
+ }
+ } else {
+ inputAttributes.find(_.metadata.contains(delayKey))
+ }
+ eventTime.filter(_ => key.dataType == TimestampType).flatMap { eventTime =>
+ intervalShift(key, eventTime).collect {
+ case shift if shift.exact || shift.forward =>
+ KeyShift(eventTime, shift.exact, shift.forward)
+ }
+ }
+ }
+
+ /**
+ * A shift of a time by constant intervals. `exact` means that the solver
counts it exactly, and
+ * `min` and `max` bound how far it moves a time, in microseconds, in every
session time zone.
+ */
+ private case class Shift(exact: Boolean, min: Long, max: Long) {
+ /** Whether the shift never moves a time backward. */
+ def forward: Boolean = min >= 0
+ def plus(other: Shift): Shift = Shift(exact && other.exact,
+ Math.addExact(min, other.min), Math.addExact(max, other.max))
+ def negate: Shift = Shift(exact, Math.negateExact(max),
Math.negateExact(min))
+ }
+
+ private object Shift {
+ def micros(value: Long): Shift = Shift(exact = true, value, value)
+ // Spark adds whole days in the session time zone, where a day can be 23
or 25 hours across a
+ // daylight saving change, and months vary in length, but the solver
counts a day as 24 hours.
+ // So only shifts without whole days or months are exact. To bound a shift
without reading the
+ // time zone, a day counts as 12 to 36 hours, wider than any daylight
saving change, and a
+ // month as 28 to 31 such days.
+ def days(n: Long): Shift = if (n >= 0) {
+ Shift(n == 0, Math.multiplyExact(n, 12 * MICROS_PER_HOUR),
+ Math.multiplyExact(n, 36 * MICROS_PER_HOUR))
+ } else {
+ days(Math.negateExact(n)).negate
+ }
+ def months(n: Long): Shift = if (n >= 0) {
+ Shift(n == 0, Math.multiplyExact(n, 28 * 12 * MICROS_PER_HOUR),
+ Math.multiplyExact(n, 31 * 36 * MICROS_PER_HOUR))
+ } else {
+ months(Math.negateExact(n)).negate
+ }
+ }
+
+ /**
+ * If the expression is the event time plus or minus constant intervals, the
shift. Each term
+ * counts on its own, so a net forward compound shift such as
+ * rightTime + INTERVAL 1 DAY - INTERVAL 1 HOUR never moves a time backward.
Other functions and
+ * casts from other types are not accepted: a truncation such as
+ * CAST(CAST(rightTime AS BIGINT) AS TIMESTAMP) can map a later event time
below the watermark.
+ */
+ private def intervalShift(expr: Expression, eventTime: Attribute):
Option[Shift] = {
+ def interval(e: Expression): Option[Shift] = {
+ // An interval that fails to evaluate gives no bound; the query reports
the error at run time.
+ def value: Option[Any] = try Option(e.eval()) catch { case NonFatal(_)
=> None }
+ if (!e.foldable) {
+ None
+ } else {
+ e.dataType match {
+ case _: DayTimeIntervalType => value.map { v =>
+ val micros = v.asInstanceOf[Long]
+ Shift.days(micros / MICROS_PER_DAY).plus(Shift.micros(micros %
MICROS_PER_DAY))
+ }
+ case _: YearMonthIntervalType => value.map(v =>
Shift.months(v.asInstanceOf[Int]))
+ case CalendarIntervalType => value.map { v =>
+ val i = v.asInstanceOf[CalendarInterval]
+
Shift.months(i.months).plus(Shift.days(i.days)).plus(Shift.micros(i.microseconds))
+ }
+ case _ => None
}
+ }
+ }
+ def combine(a: Option[Shift], b: Option[Shift]): Option[Shift] =
+ for (x <- a; y <- b) yield x.plus(y)
+ def shift(expr: Expression): Option[Shift] = expr match {
+ case a: Attribute if a.semanticEquals(eventTime) =>
Some(Shift.micros(0L))
+ // The analyzer wraps timestamp + interval in a cast to the same
timestamp type.
+ case Cast(child, TimestampType, _, _) if child.dataType == TimestampType
=> shift(child)
+ case TimestampAddInterval(start, i, _) => combine(interval(i),
shift(start))
+ case TimestampAddYMInterval(start, i, _) => combine(interval(i),
shift(start))
+ // timestampadd adds sub-day units exactly, and days, weeks, months,
quarters and years in
+ // the session time zone.
+ case TimestampAdd(unit, quantity, start, _) if quantity.foldable =>
+ val amount = try Option(quantity.eval()) catch { case NonFatal(_) =>
None }
+ val unitShift = amount.collect { case n: Number => n.longValue()
}.flatMap { n =>
+ timestampAddUnitMicros(unit).map(u =>
Shift.micros(Math.multiplyExact(n, u))).orElse {
+ unit.toUpperCase(Locale.ROOT) match {
+ case "DAY" | "DAYOFYEAR" => Some(Shift.days(n))
+ case "WEEK" => Some(Shift.days(Math.multiplyExact(n, 7L)))
+ case "MONTH" => Some(Shift.months(n))
+ case "QUARTER" => Some(Shift.months(Math.multiplyExact(n, 3L)))
+ case "YEAR" => Some(Shift.months(Math.multiplyExact(n, 12L)))
+ case _ => None
+ }
+ }
+ }
+ combine(unitShift, shift(start))
+ case DatetimeSub(_, _, replacement) => shift(replacement)
+ case Add(left, right, _) =>
+ combine(interval(right), shift(left)).orElse(combine(interval(left),
shift(right)))
+ case Subtract(left, right, _) => combine(interval(right).map(_.negate),
shift(left))
+ case _ => None
+ }
+ // A shift too large to count in microseconds gives no bound.
+ try shift(expr) catch { case _: ArithmeticException => None }
+ }
+
+ /**
+ * The key with each foldable interval, such as INTERVAL 1 HOUR * 2,
replaced by a literal of
+ * its value, as [[intervalShift]] evaluates it, and each timestampadd of a
sub-day unit replaced
+ * by the same interval added to its timestamp. The solver reads only
interval literals, and the
+ * admission check runs on the analyzed plan, before constant folding, so
without this it would
+ * find no bound where execution finds one.
+ */
+ private def withIntervalLiterals(key: Expression): Expression =
key.transformDown {
+ case e if e.foldable && !e.isInstanceOf[Literal] &&
isIntervalType(e.dataType) =>
+ try Literal.create(e.eval(), e.dataType) catch { case NonFatal(_) => e }
+ // A sub-day unit adds an exact number of microseconds, which the solver
reads as an interval.
+ case e @ TimestampAdd(unit, quantity, start, timeZoneId) if
quantity.foldable &&
+ timestampAddUnitMicros(unit).isDefined =>
+ try {
+ val micros = Math.multiplyExact(
+ quantity.eval().asInstanceOf[Number].longValue(),
timestampAddUnitMicros(unit).get)
+ TimestampAddInterval(start, Literal(micros, DayTimeIntervalType()),
timeZoneId)
+ } catch {
+ case NonFatal(_) => e
+ }
+ }
+
+ /**
+ * The join condition in the form the optimizer gives the planned condition,
which state
+ * eviction solves, for the admission check, which solves the analyzed
condition: each foldable
+ * expression replaced by a literal of its value, as constant folding does,
and each NOT over a
+ * comparison replaced by the opposite comparison, through De Morgan's laws,
as boolean
+ * simplification does. Both keep the condition's meaning, including for
NULLs. Current-time
+ * functions stay, since streaming execution replaces them per batch with
expressions that are
+ * not folded, and so does an expression whose evaluation fails, which then
fails at run time.
+ * Unlike [[withIntervalLiterals]], this keeps timestampadd, which eviction
does not read in a
+ * range condition.
+ */
+ def withFoldedConstants(condition: Expression): Expression =
condition.transformDown {
Review Comment:
**Blocking (P1):** This fold is a `transformDown`, and a SQL or `expr()`
BETWEEN reaches it as a `Between`, a `RuntimeReplaceable` whose `input`,
`lower` and `upper` are case-class fields while its only child is the
replacement. The fold therefore rewrites only the replacement, but the solver's
`Between` case reads the fields, so the interval product in `rt BETWEEN lt AND
lt + INTERVAL 1 MINUTE * 30` is still a `MultiplyDTInterval` that
`collectTerms` cannot read. Eviction solves the optimized condition, where the
optimizer has already turned that BETWEEN into `rt >= lt AND rt <= lt +
INTERVAL 30 MINUTES`, so it does bound the left state.
Reading the code, take a left semi join with watermarks on `lt` and `rt` on
`lk = rk AND rt BETWEEN lt AND lt + INTERVAL 1 MINUTE * 30 AND CAST(lt AS
BIGINT) > 10`. Released versions and the base branch start it, because the
constant counted as a bound, and evict its left state at the watermark less 30
minutes with correct results. With this PR the upper bound is unreadable at
admission and the constant no longer counts, so with
`spark.sql.streaming.join.checkFinalization.enabled` at its default the query
fails at start. A left outer join with the same condition, the case this PR
sets out to finalize, fails the same way, and the error and the warning logged
with the check disabled both say that the state then stays unbounded, which is
wrong for these joins.
This holds when the BETWEEN's input stays in place in the planned condition,
as a column or an expression over both inputs does. A BETWEEN whose input the
optimizer computes into a separate column, such as `CAST(rt AS DOUBLE)`, gives
eviction no bound either, so rejecting it matches this PR's rule for joins
bounded only by constants. The DataFrame `between()` method, which builds two
comparisons, and a BETWEEN with literal intervals are not affected.
This extends existing discussions
[1](https://github.com/apache/spark/pull/60284#issuecomment-6961429000),
[2](https://github.com/apache/spark/pull/60284#discussion_r4598373596).
**Recommended change:** Make StreamingJoinHelper.withFoldedConstants
(StreamingJoinHelper.scala:749-771) give a BETWEEN the form the optimizer plans
for it. The optimizer substitutes the BETWEEN's input into both comparisons in
three cases: when the BETWEEN's replacement already holds the plain
comparisons, as under spark.sql.alwaysInlineCommonExpr; when the input is
deterministic and cheap as CollapseProject.isCheap judges it, such as a column
or a field of one; and when the input reads both join inputs. In those cases,
replace the BETWEEN with input >= lower AND input <= upper, built from the
input and bounds it holds, before the transform descends, so that the existing
fold also reaches those bounds, and leave any other BETWEEN as it is now. The
fold then needs the outputs of the join's two inputs, which the finalization
check passes where it builds the folded condition
(UnsupportedOperationChecker.scala:726-727), and the fold's Scaladoc should
name the BETWEEN rewrite next to
constant folding and the NOT rewrite. Add admission-check tests and streaming
join tests for BETWEEN bounds beside a constant-only conjunct. The fold came in
d38d50da16e for comparisons and NOT; no commit of this PR handled a BETWEEN in
it.
**Why this works:** A BETWEEN keeps its input and bounds as fields and
exposes only its replacement as a child (Between.scala:44-62), so the fold's
transformDown folds that replacement, which the solver never reads, while the
solver's BETWEEN case reads the unfolded fields
(StreamingJoinHelper.scala:899-900) and finds no bound in an interval such as
INTERVAL 1 MINUTE * 30. At eviction the optimizer has already replaced the
BETWEEN by its two comparisons and folded the bound, so eviction reads rt <= lt
+ INTERVAL 30 MINUTES and bounds the left state. Rewriting the BETWEEN into the
same comparisons before the transform visits them lets the existing fold turn
the bound into a literal, so the solver reads at admission the conjuncts it
reads at eviction, the check finds the cutoff that eviction uses, and the
constant-only conjunct is no longer needed to admit the join. Following the
optimizer's choice of where it substitutes the input keeps the rewrite from
reading computed bounds thro
ugh an input that eviction sees only as a separate computed column, in which
eviction finds no bound.
**Compatibility:** A join whose admission does not depend on a BETWEEN with
a computed bound keeps its current result. This includes a join bounded only by
constant-only conjuncts, which still fails analysis with the finalization check
enabled, and a BETWEEN with literal intervals or one built by the DataFrame
between() method, which the check already reads.
**Risks:** The fold now copies the optimizer's choice of where it
substitutes a BETWEEN's input. If that choice changes, for example in what
CollapseProject.isCheap counts as cheap, the check and eviction disagree again
for such inputs until the fold follows, so the fold should call
CollapseProject.isCheap and test determinism as the optimizer does rather than
restate the rule. Joins bounded only by such a BETWEEN, with no constant-only
conjunct beside it, also start, although the base branch and this head reject
them at start. Their planned condition bounds the state, as for the comparison
spellings that the fold already admits, and no configuration rolls this back.
**Constraints:** Only the finalization check's folded condition changes: the
rule of earlier versions kept with the check disabled still reads the analyzed
condition, and eviction, V4 range scans and the restart compatibility check
keep reading the conditions they read now. The fold keeps its handling of
current-time functions, of expressions whose evaluation fails and of a NOT over
a comparison, and a BETWEEN that is foldable as a whole still folds to a
literal.
**Exclusions:**
- A BETWEEN whose input the optimizer computes once into a separate column,
such as CAST(rt AS DOUBLE) BETWEEN CAST(lt AS DOUBLE) AND CAST(lt AS DOUBLE) +
1800, keeps its current treatment. The check on the base branch and at this
head reads that input in place and can admit a join whose planned condition
gives eviction no bound, and aligning the check with eviction for such inputs
would newly reject joins that start today, which is a question separate from
this regression.
**Verification:**
- **Regression:** With the finalization check at its default, a left semi
join and a left outer join with watermarks on both inputs on lk = rk AND rt
BETWEEN lt AND lt + INTERVAL 1 MINUTE * 30 AND CAST(lt AS BIGINT) > 10 start
instead of failing analysis; the left outer join outputs an unmatched left row
padded with nulls once the right watermark passes that row's lt by more than 30
minutes, and the left semi join returns its matches and drops such a left row
from its state.
- **Behavior:** Beside a constant-only conjunct on the finalized input's
column, the check admits a BETWEEN whose bound is computed from constants and
finds the same cutoff as for that bound written as two comparisons, for each
spelling of the bound (an interval product or quotient, make_dt_interval, a
string cast to an interval, and numeric arithmetic in an interval's multiplier)
and for each input the optimizer substitutes: the other input's column, the
finalized input's column, as in lt BETWEEN rt - INTERVAL 1 MINUTE * 30 AND rt,
and an input that reads both join inputs, as in CAST(rt AS DOUBLE) - CAST(lt AS
DOUBLE) BETWEEN 0 AND 60 * 30.
- **Compatibility:** A BETWEEN whose input the optimizer computes once into
a separate column of the input it reads, such as CAST(rt AS DOUBLE) BETWEEN
CAST(lt AS DOUBLE) AND CAST(lt AS DOUBLE) + 60 * 30 beside CAST(lt AS BIGINT) >
10 in a left outer join, still fails analysis with the check at its default, as
at this head, since eviction finds no bound in that column.
- **Compatibility:** With spark.sql.alwaysInlineCommonExpr enabled, under
which the optimizer keeps every BETWEEN input in place, a left outer join on lk
= rk AND CAST(rt AS DOUBLE) BETWEEN CAST(lt AS DOUBLE) AND CAST(lt AS DOUBLE) +
60 * 30 AND CAST(lt AS BIGINT) > 10 starts, because eviction then reads its
bound through CAST(rt AS DOUBLE) and the check reads it the same way.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -17,36 +17,802 @@
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.trees.TreePattern
+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]]. 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)
+ case Between(input, lower, upper, _) => lowerBound(input, lower) ++
lowerBound(upper, input)
+ case _ => Nil
+ }.filter { case (x, y, _) => keyColumns.contains(x) &&
eventTimeColumns.contains(y) }
+ .map { case (x, y, shift) =>
+ val below = lagBelow(keyInput, key, x, keyLow, Some(0L),
unwatermarkedUnion)
+ val above = lagBelow(eventTimeInput, y, eventTime, Some(0L),
eventTimeHigh,
+ unwatermarkedUnion)
+ if (below.unrelated || above.unrelated) {
+ EventTimeLag.unrelated
+ } else {
+ shift.filter(_ => !below.unbounded && !above.unbounded).flatMap {
c =>
+ Try(Math.subtractExact(Math.addExact(below.micros,
above.micros), c)).toOption
+ }.map(lag => EventTimeLag(math.max(0L, lag), unrelated = false,
unbounded = false))
+ .getOrElse(EventTimeLag.unbounded)
+ }
+ }
+ }
+ lags.filter(lag => !lag.unrelated &&
!lag.unbounded).sortBy(_.micros).headOption
+ .getOrElse(if (lags.exists(_.unbounded)) EventTimeLag.unbounded else
EventTimeLag.unrelated)
+ }
+
+ // An offset too large to count in microseconds has no bound.
+ private def addOffsets(a: Option[Long], b: Option[Long]): Option[Long] =
+ for (x <- a; y <- b; sum <- Try(Math.addExact(x, y)).toOption) yield sum
+
+ /** The only attribute that `e` references, if there is one. */
+ private def singleReference(e: Expression): Option[Attribute] =
e.references.toSeq match {
+ case Seq(a) => Some(a)
+ case _ => None
+ }
+
+ /**
+ * The step of [[lagBelow]] for the key's projection entry `entry`: the
column it follows and the
+ * smallest that the entry is above it, None without bound.
+ */
+ private def keyStep(entry: NamedExpression): Option[Step] = entry match {
+ case a: Attribute => Some(Step(a.exprId, Some(0L)))
+ case Alias(a: Attribute, _) => Some(Step(a.exprId, Some(0L)))
+ // A window ends after its time column.
+ case Alias(child, _) if entry.metadata.contains(TimeWindow.marker) =>
+ timeWindowSource(child).map(source => Step(source.exprId, Some(0L)))
+ case Alias(child, _) if entry.metadata.contains(SessionWindow.marker) =>
+ sessionWindowSource(child).map(source => Step(source.exprId, Some(0L)))
+ case Alias(child, _) if child.dataType == TimestampType =>
+ singleReference(child).filter(_.dataType == TimestampType).flatMap {
source =>
+ // A shift whose whole days, months or years can move a time backward
has no bound
+ // here, as for equality keys.
+ intervalShift(child, source).map { shift =>
+ Step(source.exprId, Some(shift.min).filter(_ => shift.exact ||
shift.forward))
+ }
+ }
+ case _ => None
+ }
+
+ /**
+ * The step of [[lagBelow]] for the late-filtered column's projection entry
`entry`: the column
+ * it follows and the largest that the entry is above it, None without bound.
+ */
+ private def eventTimeStep(entry: NamedExpression): Option[Step] = entry
match {
+ case a: Attribute => Some(Step(a.exprId, Some(0L)))
+ case Alias(a: Attribute, _) => Some(Step(a.exprId, Some(0L)))
+ case Alias(child, _) if entry.metadata.contains(TimeWindow.marker) =>
+ timeWindowSource(child).map(source => Step(source.exprId,
timeWindowLength(child, source)))
+ // A session ends its gap after the column, or without bound for a gap
that is not constant.
+ case Alias(child, _) if entry.metadata.contains(SessionWindow.marker) =>
+ sessionWindowSource(child).map { source =>
+ val end = child match {
+ case CreateNamedStruct(Seq(_, _, _, end)) =>
Some(withoutConversions(end))
+ case _ => None
+ }
+ Step(source.exprId, end.flatMap(intervalShift(_, source)).map(_.max))
+ }
+ case _ => None
+ }
+
+ /**
+ * The length of the time window that `window` builds from `source`,
evaluated with `source` at
+ * the epoch. Spark counts window durations in fixed microseconds, so it is
the same for every
+ * time.
+ */
+ private def timeWindowLength(window: Expression, source: Attribute):
Option[Long] = {
+ try {
+ window.transform {
+ case a: Attribute if a.exprId == source.exprId => Literal(0L,
source.dataType)
+ }.eval() match {
+ case row: InternalRow if !row.isNullAt(0) && !row.isNullAt(1) =>
+ Some(row.getLong(1) - row.getLong(0))
+ case _ => None
+ }
+ } catch {
+ case NonFatal(_) => None
+ }
+ }
+
+ /**
+ * The time column of a time window, when the window is built from that
column itself: the
+ * rewrite of window() reads its time column only through a conversion to
microseconds.
+ */
+ private def timeWindowSource(window: Expression): Option[Attribute] =
+ window.collect { case PreciseTimestampConversion(time, _, LongType) =>
time }.distinct match {
+ case Seq(a: Attribute) if window.references.toSeq == Seq(a) => Some(a)
+ case _ => None
+ }
+
+ /** The time column of a session window, which is its start. */
+ private def sessionWindowSource(window: Expression): Option[Attribute] =
window match {
+ case CreateNamedStruct(Seq(_, start, _, _)) => withoutConversions(start)
match {
+ case a: Attribute => Some(a)
+ case _ => None
+ }
+ case _ => None
+ }
+
+ /** The expression without the conversions that the session window rewrite
adds around it. */
+ private def withoutConversions(e: Expression): Expression = e match {
+ case PreciseTimestampConversion(child, _, _) => withoutConversions(child)
+ case KnownNullable(child) => withoutConversions(child)
+ case other => other
+ }
+
+ /**
+ * Get the cutoff for the opposite input's equality key at `ordinal`, given
this input's
+ * watermark. `keys` and `inputAttributes` belong to this input, whose
future rows have an event
+ * time above the watermark. When the key is that event time, the equal key
of any state row
+ * they can still match is above the watermark too; with `lags`, so is a key
on another
+ * watermarked column, less its lag. When the key is the event time shifted
by exact intervals,
+ * solving `stateKey >= rightTime + INTERVAL 10 SECONDS` shifts the cutoff
by that interval, less
+ * 1 ms as for range conditions. When the shift has whole days, months or
years but never moves a
+ * time backward, the cutoff is the watermark itself. Returns None for any
other key, including a
+ * shift with whole days, months or years that can move a time backward.
+ */
+ def getStateKeyWatermark(
+ keys: Seq[Expression],
+ inputAttributes: Seq[Attribute],
+ ordinal: Int,
+ eventWatermark: Option[Long],
+ lags: Option[EventTimeLags] = None): Option[Long] = {
+ // The watermark that bounds a watermarked column of this input.
+ def watermarkOf(column: NamedExpression): Option[Long] = lags match {
+ case Some(l) => l.lagOf(column, inputAttributes).flatMap { lag =>
+ eventWatermark.flatMap(lag.keyWatermark)
+ }
+ case None => eventWatermark.filter { _ =>
+
inputAttributes.find(_.metadata.contains(delayKey)).exists(_.semanticEquals(column))
+ }
+ }
+ keys(ordinal) match {
+ case column: NamedExpression if watermarkOf(column).isDefined =>
watermarkOf(column)
+ case key => shiftOfKey(key, inputAttributes, lags.isDefined).flatMap {
+ case KeyShift(eventTime, true, _) =>
+ val stateKey = AttributeReference("stateKey", TimestampType)()
+ getStateValueWatermark(AttributeSet(Seq(stateKey)),
AttributeSet(Seq(eventTime)),
+ Some(GreaterThanOrEqual(stateKey, withIntervalLiterals(key))),
+ watermarkOf(eventTime))
+ // The solver cannot count this shift, but it keeps the key of every
future row at or
+ // above that row's event time, which is above the watermark.
+ case KeyShift(eventTime, false, true) => watermarkOf(eventTime)
+ case _ => None
+ }
+ }
+ }
+
+ /**
+ * Get the cutoff for this input's range-bounded columns `stateAttributes`
from the opposite
+ * input's watermark, as [[getStateValueWatermark]] does with the opposite
input's
+ * `otherInputAttributes`. Without `lags`, only the opposite input's first
watermarked column
+ * counts as its event time; with them, each of its watermarked columns does
at its own
+ * watermark, the watermark less its lag, where they bound it; see
[[EventTimeLag]].
+ * `exactForUnwatermarkedColumns` is passed on to
[[getStateValueWatermark]], which this
+ * always asks to give no cutoff from a watermark term with the sign of an
unwatermarked column.
Review Comment:
**Nit (P3):** Since d38d50da16e dropped `signedForUnwatermarkedColumns`,
this method passes only `exactForUnwatermarkedColumns`, and the solver gives no
column a cutoff from a negated watermark term unless `baseAdmissionRules` is
set, so this sentence now describes a rule limited to unwatermarked columns and
an argument that no longer exists. For example:
```suggestion
* `exactForUnwatermarkedColumns` is passed on to
[[getStateValueWatermark]], which gives no
* column a cutoff from a watermark term with the sign of the bounded
column, since this
* method never sets `baseAdmissionRules`.
```
The solver test at `StreamingJoinHelperSuite.scala:427` keeps the old name,
'a watermark term with the sign of an unwatermarked column gives it no cutoff',
although it now also asserts that `leftEventTime`, a watermarked column, gets
none; a name such as 'a watermark term with the sign of the bounded column
gives no cutoff, also to a column with its own watermark' would match what it
checks.
**Verification:**
- **Inspection:** No comment in the range-bound solver and no solver test
name still describes a sign rule limited to columns without their own watermark
or an argument that asks for it, and the renamed test keeps its assertions.
--
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]