HeartSaVioR commented on code in PR #60280: URL: https://github.com/apache/spark/pull/60280#discussion_r4596402249
########## 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. + for { + joinType <- Seq("left_outer", "left_semi", "full_outer") + v <- Seq(2, 3, 4) + restart <- Seq(false, true) + } { + test(s"default-mode $joinType join on a window after the event time, with the event time " + + s"pruned, evicts at the window end, V$v${if (restart) ", restart" else ""}") { + val leftInput = MemoryStream[(Int, Int)] + val rightInput = MemoryStream[(Int, Int)] + val joined = windowed(leftInput, "l") + .join(windowed(rightInput, "r"), expr("lk = rk AND lw = rw"), joinType) + val result = if (joinType == "left_semi") { + joined.select($"lk", $"lw.start".cast("int")) + } else { + joined.select($"lk", $"lw.start".cast("int"), $"rk", $"rw.start".cast("int")) + } + val (matched, unmatched) = joinType match { + case "left_semi" => (Row(1, 0), Nil) + case _ => (Row(1, 0, 1, 0), Seq(Row(2, 0, null, null))) + } + testJoin(defaultMode, version(v))(result)(Seq( + MultiAddData(leftInput, (1, 5), (2, 6))(rightInput, (1, 5)), + CheckNewAnswer(matched), + // The watermark is 30 seconds from the next batch on. + MultiAddData(leftInput, (3, 31))(rightInput, (9, 31)), + CheckNewAnswer()) ++ restartActions(restart) ++ Seq( + AddData(rightInput, (9, 40)), + // The windows [0, 10) end below the watermark, so their unmatched rows are output. + CheckNewAnswer(unmatched: _*)) ++ assertStateRows(joinType, 3): _*) + } + } + + // A range condition on a copy of the right event time placed after it. Without rt in the + // output, the planned right input keeps only the copy, which then filters late rows itself. + for { + (modeName, mode) <- Seq("default" -> defaultMode, "legacy" -> legacyMode) + joinType <- Seq("left_outer", "left_semi") + v <- Seq(2, 3) + } { + test(s"$modeName-mode $joinType join with a range on a copy of the event time evicts by " + + s"it, V$v") { + val leftInput = MemoryStream[(Int, Int)] + val rightInput = MemoryStream[(Int, Int)] + val right = eventTimeInput(rightInput, "r").withColumn("rc", $"rt") + val joined = eventTimeInput(leftInput, "l").join(right, + expr("lk = rk AND lt BETWEEN rc - INTERVAL 5 SECONDS AND rc + INTERVAL 5 SECONDS"), + joinType) + val result = if (joinType == "left_semi") { + joined.select($"lk", $"lt".cast("int")) + } else { + joined.select($"lk", $"lt".cast("int"), $"rk") + } + val (matched, unmatched) = if (joinType == "left_semi") { + (Row(1, 10), Nil) + } else { + (Row(1, 10, 1), Seq(Row(2, 12, null))) + } + testJoin(mode, version(v))(result)(Seq( + MultiAddData(leftInput, (1, 10), (2, 12))(rightInput, (1, 12)), + CheckNewAnswer(matched), + MultiAddData(leftInput, (3, 40))(rightInput, (9, 40)), + CheckNewAnswer(), + // At the watermark of 39 seconds, a right row has rc above 39 seconds, so left rows + // below 34 seconds can no longer match. + AddData(rightInput, (9, 41)), + CheckNewAnswer(unmatched: _*)) ++ assertStateRows(joinType, 3): _*) + } + } + + // Legacy mode: a copy of the event time placed after a window over it. The planned input + // filters late rows by the event time when the query reads it after the join, and by the + // window otherwise, so a row's copy is above the watermark less the window's 10 seconds. + for { + joinType <- Seq("inner", "left_outer", "right_outer", "full_outer", "left_semi") + v <- Seq(2, 3) + } { + def withCopy(memory: MemoryStream[(Int, Int)], side: String): DataFrame = + windowed(memory, side).withColumn(s"${side}c", col(s"${side}t")) + def expected(joinType: String, rows: Row*): Seq[Row] = joinType match { + case "left_semi" => rows.map(r => Row(r.get(0), r.get(1))) + case _ => rows + } + def project(joined: DataFrame, joinType: String, time: String => Column): DataFrame = + if (joinType == "left_semi") { + joined.select($"lk", time("l")) + } else { + joined.select($"lk", time("l"), $"rk", time("r")) + } + val outer = joinType == "left_outer" || joinType == "full_outer" + + test(s"legacy-mode $joinType join on a copy of the event time after a window over it, " + + s"with the event time kept, evicts at the watermark, V$v") { + 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"), joinType) + val result = project(joined, joinType, side => col(s"${side}t").cast("int")) + testJoin(legacyMode, version(v))(result)(Seq( + MultiAddData(leftInput, (1, 5), (2, 25))(rightInput, (1, 5)), + CheckNewAnswer(expected(joinType, Row(1, 5, 1, 5)): _*), + MultiAddData(leftInput, (9, 31))(rightInput, (9, 31)), + CheckNewAnswer(expected(joinType, Row(9, 31, 9, 31)): _*), + // The planned inputs filter late rows by their event times, so at the watermark of 30 + // seconds no later row matches the left row at 25 seconds or the right row at 5 seconds. + AddData(rightInput, (8, 32)), + CheckNewAnswer((if (outer) Seq(Row(2, 25, null, null)) else Nil): _*)) ++ + assertStateRows(joinType, 3): _*) + } + + test(s"legacy-mode $joinType join on a copy of the event time after a window over it, " + + s"with the event time pruned, evicts at the watermark less the window, V$v") { + 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"), joinType) + // The query reads the whole windows: reading only a field of one lets the optimizer prune + // the watermarked window, and the copy then filters late rows itself. + val result = project(joined, joinType, side => col(s"${side}w")) + testJoin(legacyMode, version(v))(result)(Seq( + MultiAddData(leftInput, (1, 5), (2, 25))(rightInput, (1, 5)), + CheckNewAnswer(expected(joinType, Row(1, windowRow(0), 1, windowRow(0))): _*), + MultiAddData(leftInput, (9, 31))(rightInput, (9, 31)), + CheckNewAnswer(expected(joinType, Row(9, windowRow(30), 9, windowRow(30))): _*), + // A later left row at 25 seconds passes late filtering by its window, which ends at 30 + // seconds, so the right state keeps rows above 20 seconds. 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: a left row passes late filtering only when its window ends after the 30-second watermark, so its copy is above 20 seconds. <!-- sp2k-review10 reply 4587582193 --> -- 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]
