HeartSaVioR commented on code in PR #60286: URL: https://github.com/apache/spark/pull/60286#discussion_r4604045365
########## sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinLegacyEventTimeKeySuite.scala: ########## @@ -0,0 +1,590 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.spark.sql.streaming + +import java.sql.Timestamp + +import org.apache.spark.sql.{AnalysisException, DataFrame, Row} +import org.apache.spark.sql.catalyst.analysis.{EventTimeLag, StreamingJoinHelper} +import org.apache.spark.sql.catalyst.plans.Inner +import org.apache.spark.sql.catalyst.plans.logical.{Join, JoinHint, LogicalPlan, Union} +import org.apache.spark.sql.execution.streaming.runtime.MemoryStream +import org.apache.spark.sql.execution.streaming.state.RocksDBStateStoreProvider +import org.apache.spark.sql.functions._ +import org.apache.spark.sql.internal.SQLConf + +/** + * With spark.sql.streaming.statefulOperator.allowMultiple=false, an input filters late rows by + * its first watermarked column. An equality key on a later watermarked column bounds the other + * input's state, as in Spark 4.3, lowered by how far the plan shows that some rows of the input + * can hold the key below a watermarked column before it, and not at all when the plan shows no + * bound on that. + */ +class StreamingJoinLegacyEventTimeKeySuite extends StreamTest { + import testImplicits._ + + private val legacyMode = SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key -> "false" + + /** Adds the key column `<side>w` to an input whose event time is `<side>t`. */ + private type KeyBuilder = (DataFrame, String) => DataFrame + + private val tumbling: KeyBuilder = + (df, side) => df.withColumn(s"${side}w", window(col(s"${side}t"), "10 seconds")) + private val sliding: KeyBuilder = + (df, side) => df.withColumn(s"${side}w", window(col(s"${side}t"), "10 seconds", "5 seconds")) + private val copy: KeyBuilder = (df, side) => df.withColumn(s"${side}w", col(s"${side}t")) + private val copyThenWindow: KeyBuilder = (df, side) => + df.withColumn(s"${side}c", col(s"${side}t")) + .withColumn(s"${side}w", window(col(s"${side}c"), "10 seconds")) + private val renamedWindow: KeyBuilder = (df, side) => + df.withColumn(s"${side}x", window(col(s"${side}t"), "10 seconds")) + .filter(col(s"${side}k") >= 0) + .withColumnRenamed(s"${side}x", s"${side}w") + // Each session is [t, t + 10 seconds), as no aggregation merges sessions. + private val sessionWindow: KeyBuilder = + (df, side) => df.withColumn(s"${side}w", session_window(col(s"${side}t"), "10 seconds")) + // Adds the event time less 20 seconds, in a column that keeps the event time's watermark. + private def withShifted(df: DataFrame, side: String): DataFrame = { + val time = s"${side}t" + df.select(col("*"), + (col(time) - expr("INTERVAL 20 SECONDS")).as(s"${side}s", df.schema(time).metadata)) + } + // A window over the shifted time. Its end can be at or below the watermark while the event + // time is above. + private val shiftedWindow: KeyBuilder = (df, side) => + withShifted(df, side).withColumn(s"${side}w", window(col(s"${side}s"), "10 seconds")) + private val shiftedCopy: KeyBuilder = (df, side) => + withShifted(df, side).withColumnRenamed(s"${side}s", s"${side}w") + // A window over the shifted time without a watermark, which a window over an expression drops. + private val unwatermarkedWindow: KeyBuilder = (df, side) => + df.withColumn(s"${side}w", + window(col(s"${side}t") - expr("INTERVAL 20 SECONDS"), "10 seconds")) + + /** Puts a node that keeps the input's columns between an input and the join. */ + private type Through = (DataFrame, String) => DataFrame + + private val throughNodes: Seq[(String, Through)] = Seq( + "repartition" -> ((df, _) => df.repartition(3)), + "temporary view read from SQL" -> { (df, side) => + df.createOrReplaceTempView(s"legacy_$side") + spark.sql(s"SELECT * FROM legacy_$side") + }, + "typed filter" -> ((df, _) => df.filter((r: Row) => !r.isNullAt(0))), + "observe" -> ((df, side) => df.observe(s"legacy_$side", count(lit(1)))), + "hint" -> ((df, _) => df.hint("broadcast")), + "stream-static join" -> { (df, side) => + df.join(Seq(1, 2, 3, 9).toDF("sk"), col(s"${side}k") === $"sk") + .select(col(s"${side}k"), col(s"${side}t"), col(s"${side}w")) + }) + + private def eventTimeInput(memory: MemoryStream[(Int, Int)], side: String): DataFrame = + memory.toDF().toDF(s"${side}k", "time") + .select(col(s"${side}k"), timestamp_seconds($"time").as(s"${side}t")) + .withWatermark(s"${side}t", "1 second") + + private def keyed(memory: MemoryStream[(Int, Int)], side: String, key: KeyBuilder): DataFrame = + key(eventTimeInput(memory, side), side) + .select(col(s"${side}k"), col(s"${side}t"), col(s"${side}w")) + + /** The lags of the join inputs' watermarked columns other than lag zero, by column name. */ + private def lags(df: DataFrame, planned: Boolean = false): Map[String, EventTimeLag] = { + val plan = if (planned) df.queryExecution.optimizedPlan else df.queryExecution.analyzed + val names = plan.flatMap(_.output).map(a => a.exprId -> a.name).toMap + StreamingJoinHelper.findEventTimeLags(plan, planned).lags + .filter(_._2 != EventTimeLag.zero).map { case (id, lag) => names(id) -> lag } + } + + private def lagOf(seconds: Int): EventTimeLag = + EventTimeLag(seconds * 1000000L, unrelated = false, unbounded = false) + + private def joinWithRight(left: DataFrame, key: KeyBuilder = tumbling): DataFrame = + left.join(keyed(MemoryStream[(Int, Int)], "r", key), expr("lk = rk AND lw = rw")) + + Seq( + "tumbling window" -> tumbling, + "sliding window" -> sliding, + "session window" -> sessionWindow, + "copy" -> copy, + "window over a copy" -> copyThenWindow, + "renamed window after a filter" -> renamedWindow).foreach { case (name, key) => + test(s"$name of the event time after it has lag zero") { + assert(lags(joinWithRight(keyed(MemoryStream[(Int, Int)], "l", key), key)).isEmpty) + } + } + + throughNodes.foreach { case (name, through) => + test(s"window of the event time behind a $name has lag zero") { + withTempView("legacy_l", "legacy_r") { + val left = through(keyed(MemoryStream[(Int, Int)], "l", tumbling), "l") + val right = through(keyed(MemoryStream[(Int, Int)], "r", tumbling), "r") + assert(lags(left.join(right, expr("lk = rk AND lw = rw"))).isEmpty) + } + } + } + + test("window or copy of a time shifted backward has the shift as its lag") { + val left = shiftedWindow(eventTimeInput(MemoryStream[(Int, Int)], "l"), "l") + // ls is 20 seconds below lt in every row, and lw ends after ls. + assert(lags(joinWithRight(left)) === Map("lw" -> lagOf(20), "ls" -> lagOf(20))) + assert(lags(joinWithRight(keyed(MemoryStream[(Int, Int)], "l", shiftedCopy), copy)) + === Map("lw" -> lagOf(20))) + } + + private val shiftedSlidingWindow: KeyBuilder = (df, side) => + withShifted(df, side).withColumn(s"${side}w", + window(col(s"${side}s"), "10 seconds", "5 seconds")) + + test("sliding window over a time shifted backward has the shift as its lag") { + // The walk follows the key through the expansion of the sliding window, to its source ls. + val left = shiftedSlidingWindow(eventTimeInput(MemoryStream[(Int, Int)], "l"), "l") + assert(lags(joinWithRight(left)) === Map("lw" -> lagOf(20), "ls" -> lagOf(20))) + } + + test("window over a time shifted backward has the shift as its lag behind a stream-static " + + "join") { + // The walk follows both columns into the streaming input of the join. + val left = throughNodes.toMap.apply("stream-static join")( + keyed(MemoryStream[(Int, Int)], "l", shiftedWindow), "l") + assert(lags(joinWithRight(left)) === Map("lw" -> lagOf(20))) + } + + // The shifted copy ls is 20 seconds below the event time lt in every row. The column before it + // is a window over lt, which ends up to 10 seconds after lt, so ls is up to 30 seconds below + // it. The walk follows that window through each way that the rewrite builds one. + Seq( + "tumbling" -> ((df: DataFrame) => df.withColumn("lw", window($"lt", "10 seconds"))), + "sliding" -> ((df: DataFrame) => df.withColumn("lw", window($"lt", "10 seconds", "5 seconds"))), + "session" -> ((df: DataFrame) => df.withColumn("lw", session_window($"lt", "10 seconds"))) + ).foreach { case (kind, addWindow) => + test(s"copy of a time shifted backward after a $kind window over the event time has the " + + "shift and the window's length as its lag") { + val left = withShifted(addWindow(eventTimeInput(MemoryStream[(Int, Int)], "l")), "l") + .select($"lk", $"lw", $"ls") + val right = keyed(MemoryStream[(Int, Int)], "r", copy) + assert(lags(left.join(right, expr("lk = rk AND ls = rw"))) === Map("ls" -> lagOf(30))) + } + } + + test("window over a time shifted forward has lag zero") { + def forwardWindow(df: DataFrame, side: String): DataFrame = { + val forward = df.select(col("*"), (col(s"${side}t") + expr("INTERVAL 5 SECONDS")) + .as(s"${side}f", df.schema(s"${side}t").metadata)) + forward.withColumn(s"${side}w", window(col(s"${side}f"), "10 seconds")) + } + val left = forwardWindow(eventTimeInput(MemoryStream[(Int, Int)], "l"), "l") + assert(lags(joinWithRight(left)).isEmpty) + } + + test("window over a time shifted backward has the shift as its lag behind a repartition") { + val left = keyed(MemoryStream[(Int, Int)], "l", shiftedWindow).repartition(3) + assert(lags(joinWithRight(left)) === Map("lw" -> lagOf(20))) + } + + test("copy of a time shifted forward has lag zero") { + def forward(df: DataFrame, side: String): DataFrame = df.select(col("*"), + (col(s"${side}t") + expr("INTERVAL 1 DAY")).as(s"${side}w", df.schema(s"${side}t").metadata)) + assert(lags(joinWithRight(keyed(MemoryStream[(Int, Int)], "l", forward), copy)).isEmpty) + } + + test("copy of a time shifted backward by a whole day has no bound") { + def backward(df: DataFrame, side: String): DataFrame = df.select(col("*"), + (col(s"${side}t") - expr("INTERVAL 1 DAY")).as(s"${side}w", df.schema(s"${side}t").metadata)) + assert(lags(joinWithRight(keyed(MemoryStream[(Int, Int)], "l", backward), copy)) === + Map("lw" -> EventTimeLag.unbounded)) + } + + test("copy of the event time after a window over it has the window's length as its lag") { + // The planned input filters late rows by lw if the optimizer prunes lt, and lc is then + // above the watermark less the 10 seconds of lw. + Seq(tumbling -> 10, sliding -> 10, sessionWindow -> 10).foreach { case (window, length) => + val left = window(eventTimeInput(MemoryStream[(Int, Int)], "l"), "l") + .withColumn("lc", $"lt") + assert(lags(joinWithRight(left)) === Map("lc" -> lagOf(length))) + } + // A session ends its gap after the event time, which is not bounded for a gap from a column. + val dynamicGap = eventTimeInput(MemoryStream[(Int, Int)], "l") + .withColumn("lw", session_window($"lt", when($"lk" > 0, "10 seconds").otherwise("1 hour"))) + .withColumn("lc", $"lt") + assert(lags(joinWithRight(dynamicGap)) === Map("lc" -> EventTimeLag.unbounded)) + } + + test("window after a longer window has the longer window's length as its lag") { + val left = eventTimeInput(MemoryStream[(Int, Int)], "l") + .withColumn("lh", window($"lt", "60 seconds")) + .withColumn("lw", window($"lt", "10 seconds")) + assert(lags(joinWithRight(left)) === Map("lw" -> lagOf(60))) + } + + test("planned lags are against the column that the planned input filters late rows by") { + def withCopy(memory: MemoryStream[(Int, Int)], side: String): DataFrame = + tumbling(eventTimeInput(memory, side), side).withColumn(s"${side}c", col(s"${side}t")) + val leftInput = MemoryStream[(Int, Int)] + val rightInput = MemoryStream[(Int, Int)] + val joined = withCopy(leftInput, "l") + .join(withCopy(rightInput, "r"), expr("lk = rk AND lc = rc")) + def plannedLags(times: Seq[String]): Map[String, EventTimeLag] = { + var result: Map[String, EventTimeLag] = Map.empty + withSQLConf(legacyMode) { + testStream(joined.select((Seq("lk", "rk") ++ times).map(col): _*))( + AddData(leftInput, (1, 5)), + CheckNewAnswer(), + Execute { query => + val plan = query.lastExecution.optimizedPlan + val names = plan.flatMap(_.output).map(a => a.exprId -> a.name).toMap + result = StreamingJoinHelper.findEventTimeLags(plan, planned = true).lags + .filter(_._2 != EventTimeLag.zero).map { case (id, lag) => names(id) -> lag } + }) + } + result + } + // With the event times read after the join, they filter late rows, so the copies have lag + // zero. Without them, the windows do, and the copies are up to 10 seconds below them. + assert(plannedLags(Seq("lt", "rt")).isEmpty) + assert(plannedLags(Seq("lw", "rw")) === Map("lc" -> lagOf(10), "rc" -> lagOf(10))) + } + + // The earlier join outputs at from its left input and bt from its right one. Its condition + // relates them where every row that it outputs with a non-NULL bt satisfies at = bt: in an + // inner join, and in a left outer join, which pads bt's input. Otherwise the key keeps its + // bound, as in Spark 4.3, but a range condition gets none from it. + Seq( + ("ak = bk AND at = bt", "inner", true), + ("ak = bk AND at = bt", "left_outer", true), + ("ak = bk AND at = bt", "right_outer", false), 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 [ab59957f358](https://github.com/apache/spark/pull/60280/commits/ab59957f3582d270164fd563b24f31603ff5e54c) on #60280. A lag test builds the earlier join as `B.join(A, ..., "right_outer")` with B on the padded left side, shifts `bt` back by 20 seconds, and expects a 20-second lag. A second test, in legacy mode on state formats 2 and 3, joins that column with C by a right outer join on `ct BETWEEN bs AND bs + INTERVAL 1 HOUR`: it passes analysis, which needs the 20-second bound for C, and C's row 15 seconds below the watermark still matches the AB row that arrives after the watermark has passed it. It uses a range, not an equality key, because the optimizer turns the earlier right outer join into an inner join in the executed plan when a later equality rejects a NULL `bs`, so only analysis, which reads the analyzed plan, still depends on the branch. Dropping the `RightOuter` branch of `lagThroughJoinCondition` makes both tests fail, which I checked. <!-- sp2k-review11 reply 4599498507 --> ########## sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelperSuite.scala: ########## @@ -48,6 +91,306 @@ 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) { + // 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, which passes just the two event times and runs only for a side with a + // value-eviction predicate on its own event time. The left semi exact cutoff keeps + // only conjuncts shifted by literal intervals, so neither condition reaches the + // solver there. + assert(StreamingJoinHelper.getStateValueWatermark( + AttributeSet(Seq(leftTime)), AttributeSet(Seq(rightTime)), + Some(condition), Some(10000L)) === None) + } + } + } + assert(!logAppender.loggingEvents.exists( + _.getMessage.getFormattedMessage.contains("Error trying to extract state constraint"))) + } + + test("equality key watermark on the event time plus a constant") { + val metadata = new MetadataBuilder().putLong(EventTimeWatermark.delayKey, 1000).build() + val eventTime = AttributeReference("eventTime", TimestampType, metadata = metadata)() + val other = AttributeReference("other", TimestampType)() + + case class DummyLeafNode() extends LeafNode { + override def output: Seq[Attribute] = Seq(eventTime, other) + override def computeStats(): Statistics = Statistics(sizeInBytes = BigInt(0)) + } + + def key(keyStr: String): Expression = { + val plan = Filter(EqualTo(CatalystSqlParser.parseExpression(keyStr), Literal(null)), + DummyLeafNode()) + SimpleAnalyzer.execute(plan).asInstanceOf[Filter].condition + .asInstanceOf[EqualTo].left + } + + val cases = Seq( + // The event time itself is bounded by the watermark. + ("eventTime", Some(10000L), Some(10000L)), + // A constant shifts the bound, less 1 ms as for range conditions. + ("eventTime + INTERVAL 2 SECONDS", Some(11999L), Some(7999L)), + ("eventTime - INTERVAL 2 SECONDS", Some(7999L), Some(11999L)), + // A foldable interval expression gives the bound of its value. + ("eventTime + INTERVAL 1 SECOND * 2", Some(11999L), Some(7999L)), + ("eventTime - INTERVAL 1 SECOND * 2", Some(7999L), Some(11999L)), + ("eventTime + make_dt_interval(0, 2, 0, 0)", Some(7209999L), Some(-7190001L)), + ("eventTime + INTERVAL 2 HOURS", Some(7209999L), Some(-7190001L)), + // timestampadd adds a sub-day unit exactly. + ("timestampadd(SECOND, 2, eventTime)", Some(11999L), Some(7999L)), + ("timestampadd(SECOND, -2, eventTime)", Some(7999L), Some(11999L)), + ("timestampadd(HOUR, 2, eventTime)", Some(7209999L), Some(-7190001L)), 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 [ab59957f358](https://github.com/apache/spark/pull/60280/commits/ab59957f3582d270164fd563b24f31603ff5e54c) on #60280. `StreamingJoinHelperSuite` now has solver cases for `timestampadd(HOUR, 48, ...)`, `timestampadd(HOUR, -48, ...)`, `timestampadd(MINUTE, 1440, ...)` and `timestampadd(MINUTE, -1440, ...)`. They check the key cutoff, the event-time bound and the key ordinal that admission reads, and the cutoffs are the watermark shifted by the exact amount less 1 ms, not counted as whole days. They pass on the current code, so they pin the documented rule against the change you describe. <!-- sp2k-review11 reply 4599498515 --> -- 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]
