HeartSaVioR commented on code in PR #60280:
URL: https://github.com/apache/spark/pull/60280#discussion_r4596400859
##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelperSuite.scala:
##########
@@ -48,6 +52,185 @@ class StreamingJoinHelperSuite extends AnalysisTest {
}
}
+ test("state watermark extraction ignores columns outside both attribute
sets") {
+ val leftTime = AttributeReference("leftTime", TimestampType)()
+ val leftOffset = AttributeReference("leftOffset", LongType)()
+ val metadata = new MetadataBuilder().putLong(EventTimeWatermark.delayKey,
1000).build()
+ val rightTime = AttributeReference("rightTime", TimestampType, metadata =
metadata)()
+ val rightDelay = AttributeReference("rightDelay", DayTimeIntervalType())()
+ val conditions = Seq(
+ leftTime > TimestampAddInterval(rightTime, rightDelay),
+ leftTime.cast(LongType) + leftOffset > rightTime.cast(LongType))
+ val logAppender = new LogAppender("state watermark extraction")
+ withLogAppender(logAppender, level = Some(Level.WARN)) {
+ conditions.foreach { condition =>
+ withClue(condition.sql) {
+ // The first condition reaches the references check through the V4
range scan and the
Review Comment:
> [!NOTE]
> **DISCLAIMER:** This comment was written by an LLM: Claude Sonnet 5.5
(`claude-sonnet-5-5`, 1M context), running as an SP2K agent on behalf of
@HeartSaVioR.
Fixed in
[1a36b6c97e2](https://github.com/apache/spark/pull/60280/commits/1a36b6c97e28e2666ca2503c4a4f77bdbe21a45d).
The comment now says that both conditions reach the references check through
eviction's
range path, which passes one watermarked column of the opposite input at a
time, and through the V4 range scan,
and that the left semi exact cutoff reaches neither.
<!-- sp2k-review10 reply 4587582072 -->
##########
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
Review Comment:
> [!NOTE]
> **DISCLAIMER:** This comment was written by an LLM: Claude Sonnet 5.5
(`claude-sonnet-5-5`, 1M context), running as an SP2K agent on behalf of
@HeartSaVioR.
Fixed in
[1a36b6c97e2](https://github.com/apache/spark/pull/60280/commits/1a36b6c97e28e2666ca2503c4a4f77bdbe21a45d).
The scaladoc of `lagBelow` now says that a union input that does not watermark
the column
gives an unbounded lag.
<!-- sp2k-review10 reply 4587582084 -->
##########
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] =
Review Comment:
> [!NOTE]
> **DISCLAIMER:** This comment was written by an LLM: Claude Sonnet 5.5
(`claude-sonnet-5-5`, 1M context), running as an SP2K agent on behalf of
@HeartSaVioR.
Added in
[1a36b6c97e2](https://github.com/apache/spark/pull/60280/commits/1a36b6c97e28e2666ca2503c4a4f77bdbe21a45d)
for the unbounded lag: a legacy-mode inner join with a range condition on a
column shifted back by a day keeps its left row until a right row 86,435
seconds later matches it, on state formats 2 and 3. With an unbounded lag
treated as zero, the test fails in both state formats. The unrelated lag is
covered by the chained-join tests of this round: after a key-only or a full
outer earlier join, a range condition on the earlier join's column gets no
bound, so the right outer form fails analysis and the inner form keeps the
match of a new row with an old one.
<!-- sp2k-review10 reply 4587582120 -->
##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinPlanRobustBoundSuite.scala:
##########
@@ -0,0 +1,341 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.streaming
+
+import java.sql.Timestamp
+
+import org.apache.spark.sql.{AnalysisException, Column, DataFrame, Row}
+import org.apache.spark.sql.execution.streaming.runtime.MemoryStream
+import org.apache.spark.sql.execution.streaming.state.RocksDBStateStoreProvider
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.internal.SQLConf
+
+/**
+ * Stream-stream joins whose bound must hold whatever column pruning leaves in
the planned
+ * inputs: keys and range conditions on a watermarked column that follows the
input's event time,
+ * and keys that shift the event time by several intervals.
+ */
+class StreamingJoinPlanRobustBoundSuite extends StreamTest {
+ import testImplicits._
+
+ private val legacyMode = SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key ->
"false"
+ private val defaultMode = SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key ->
"true"
+
+ /** An input of (key, seconds) with the event time `<side>t` and a watermark
delay of 1 s. */
+ private def eventTimeInput(memory: MemoryStream[(Int, Int)], side: String):
DataFrame =
+ memory.toDF().toDF(s"${side}k", "time")
+ .select(col(s"${side}k"), timestamp_seconds($"time").as(s"${side}t"))
+ .withWatermark(s"${side}t", "1 second")
+
+ /** Adds `<side>w`, a 10-second window over the event time. */
+ private def windowed(memory: MemoryStream[(Int, Int)], side: String):
DataFrame =
+ eventTimeInput(memory, side).withColumn(s"${side}w",
window(col(s"${side}t"), "10 seconds"))
+
+ /** Adds a watermarked column `<side>s` that holds the event time shifted by
`shift`. */
+ private def withShifted(df: DataFrame, side: String, shift: String):
DataFrame = {
+ val time = s"${side}t"
+ df.select(col("*"), (col(time) + expr(shift)).as(s"${side}s",
df.schema(time).metadata))
+ }
+
+ private def testJoin(conf: (String, String)*)(result: DataFrame)(
+ actions: StreamAction*): Unit = {
+ withSQLConf(Seq(
+ SQLConf.STATE_STORE_PROVIDER_CLASS.key ->
classOf[RocksDBStateStoreProvider].getName,
+ SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> "false") ++
conf: _*) {
+ testStream(result)(StartStream() +: actions: _*)
+ }
+ }
+
+ private def restartActions(restart: Boolean): Seq[StreamAction] =
+ if (restart) Seq(StopStream, StartStream()) else Nil
+
+ private def assertStateRows(rows: Long): StreamAction = Execute { query =>
+ assert(query.lastProgress.stateOperators.head.numRowsTotal === rows)
+ }
+
+ /** Checks the state rows of a join that keeps every row until eviction, as
all but semi do. */
+ private def assertStateRows(joinType: String, rows: Long): Seq[StreamAction]
=
+ if (joinType == "left_semi") Nil else Seq(assertStateRows(rows))
+
+ private def version(v: Int): (String, String) =
+ SQLConf.STREAMING_JOIN_STATE_FORMAT_VERSION.key -> v.toString
+
+ /** The window of `seconds` seconds that starts at `start` seconds. */
+ private def windowRow(start: Int, seconds: Int = 10): Row =
+ Row(new Timestamp(start * 1000L), new Timestamp((start + seconds) * 1000L))
+
+ // With multiple stateful operators allowed, the planned input keeps one
watermarked column or
+ // the query fails at start. Here pruning removes the event time, so the
window filters late
+ // rows, and the base branch evicted both inputs at the window end.
Review Comment:
> [!NOTE]
> **DISCLAIMER:** This comment was written by an LLM: Claude Sonnet 5.5
(`claude-sonnet-5-5`, 1M context), running as an SP2K agent on behalf of
@HeartSaVioR.
Fixed in
[1a36b6c97e2](https://github.com/apache/spark/pull/60280/commits/1a36b6c97e28e2666ca2503c4a4f77bdbe21a45d),
with your wording.
<!-- sp2k-review10 reply 4587582170 -->
--
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]