HeartSaVioR commented on code in PR #60280:
URL: https://github.com/apache/spark/pull/60280#discussion_r4582432836


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -224,98 +236,389 @@ object StreamingSymmetricHashJoinHelper extends Logging {
     WatermarkSupport.findEventTimeColumn(rightAttributes,
       allowMultipleEventTimeColumns = useFirstEventTimeColumn)
 
-    val joinKeyOrdinalForWatermark: Option[Int] = 
findJoinKeyOrdinalForWatermark(
-      leftKeys, rightKeys)
-
     def getOneSideStateWatermarkPredicate(
         oneSideInputAttributes: Seq[Attribute],
         oneSideJoinKeys: Seq[Expression],
-        otherSideInputAttributes: Seq[Attribute]): 
Option[JoinStateWatermarkPredicate] = {
+        otherSideInputAttributes: Seq[Attribute],
+        otherSideJoinKeys: Seq[Expression]): 
Option[JoinStateWatermarkPredicate] = {
+      // State is bounded by future input from the opposite side, not by its 
own watermark.
+      val joinKeyOrdinalForWatermark = 
StreamingJoinHelper.getStateKeyWatermarkOrdinal(
+        otherSideJoinKeys, otherSideInputAttributes, legacyKeys)

Review Comment:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM: Claude Opus 5.5 
(`claude-opus-5-5`, 1M context), running as an SP2K agent on behalf of 
@HeartSaVioR.
   
   Thanks. The range path now uses the same lags as the keys. Each watermarked 
column of the other
   input is solved at its own watermark, the watermark less its lag, and the 
lowest cutoff wins. A
   column with no known bound, or one that the plan does not relate to the 
column that filters
   late rows, gives no range bound; without lags only the first watermarked 
column counts. In your
   example, `rs` is 20 seconds below `rt`, so the left cutoff is the watermark 
less 20 seconds and
   1 ms, and the inner and left outer joins keep the match. This also covers 
the part of
   SPARK-61346 that restricts range bounds to the late-filtered column, so that 
later step needs no
   range change of its own.
   
   <!-- sp2k-review9 reply 4579272762 -->
   



##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinLegacyEventTimeKeySuite.scala:
##########
@@ -0,0 +1,448 @@
+/*
+ * 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.StreamingJoinHelper
+import org.apache.spark.sql.catalyst.plans.Inner
+import org.apache.spark.sql.catalyst.plans.logical.{Join, JoinHint, 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, unless the plan shows that some rows of the 
input hold the key
+ * below a watermarked column before it.
+ */
+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 keys that the shared rule rejects, by column name. */
+  private def rejectedKeys(df: DataFrame): Set[String] = {
+    val plan = df.queryExecution.analyzed
+    val names = plan.flatMap(_.output).map(a => a.exprId -> a.name).toMap
+    StreamingJoinHelper.findLegacyEventTimeKeys(plan).rejected.map(names)
+  }
+
+  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 is not rejected") {
+      assert(rejectedKeys(joinWithRight(keyed(MemoryStream[(Int, Int)], "l", 
key), key)).isEmpty)
+    }
+  }
+
+  throughNodes.foreach { case (name, through) =>
+    test(s"window of the event time behind a $name is not rejected") {
+      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(rejectedKeys(left.join(right, expr("lk = rk AND lw = 
rw"))).isEmpty)
+      }
+    }
+  }
+
+  test("window or copy of a time shifted backward is rejected") {
+    val left = shiftedWindow(eventTimeInput(MemoryStream[(Int, Int)], "l"), 
"l")
+    // ls is below lt in every row, and lw ends at most 10 seconds after ls.
+    assert(rejectedKeys(joinWithRight(left)) === Set("lw", "ls"))
+    assert(rejectedKeys(joinWithRight(keyed(MemoryStream[(Int, Int)], "l", 
shiftedCopy), copy))
+      === Set("lw"))
+  }
+
+  test("window over a time shifted backward is rejected behind a repartition") 
{

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 
[634eb849aa4](https://github.com/apache/spark/pull/60280/commits/634eb849aa45f01a4799fd376645126dcfbd3ad4).
 This round replaces the rejection by a lag for each watermarked column, so the 
cases now check lags. `StreamingJoinLegacyEventTimeKeySuite` has a case through 
each step you named: a sliding window over a time shifted backward (the 
expansion of the window), a window over a shifted time behind a stream-static 
join (the join step), and a copy of a time shifted backward after a tumbling, a 
sliding and a session window over the event time (the steps that follow the 
late-filtered window, including the session-window one), where the lag is the 
20-second shift plus the 10-second window. A window over a time shifted forward 
has lag zero, next to the existing case for a forward-shifted copy, so a 
forward shift that the walk read as backward would fail these cases.
   
   <!-- sp2k-review9 reply 4579272766 -->
   



##########
docs/streaming/ss-migration-guide.md:
##########
@@ -25,6 +25,118 @@ Please refer [Migration Guide: SQL, Datasets and 
DataFrame](../sql-migration-gui
 
 ## Upgrading from Structured Streaming 4.3 to 4.4
 
+- Since Spark 4.4, left outer and left semi stream-stream joins require a 
watermark on the
+  right input and a time condition that limits how late a matching right row 
can arrive.
+  Right outer joins require the corresponding settings on the left; full outer 
joins require
+  them on both sides. An equality key counts as such a time condition when it 
is the other
+  input's event time, or that event time shifted by constant intervals, except 
a shift backward
+  by months, years, or a day-time interval of 24 hours or more. A key such as
+  `leftTime = rightTime - INTERVAL 1 DAY` or `leftTime = rightTime - INTERVAL 
36 HOURS`, or one
+  truncated from the other input's event time, such as
+  `leftTime = CAST(CAST(rightTime AS BIGINT) AS TIMESTAMP)`, does not count, 
while
+  `timestampadd` in hours, minutes or seconds does, whatever the amount. When 
both inputs
+  have watermarks, a time range condition between the two event times can 
bound such a join
+  instead. Some previously accepted queries now fail if these requirements are 
not met. Update
+  their watermarks and join conditions using the
+  [join support 
table](apis-on-dataframes-and-datasets.html#support-matrix-for-joins-in-streaming-queries).
+  A stateful operator after such a join that uses the other input's event time 
also needs that
+  input bounded: for example, a left outer join followed by an append-mode 
aggregation over the
+  right event time also needs a watermark on the left input and a time 
condition that limits
+  how late a matching left row can arrive: an equality with an exact shift (an 
interval under
+  one day, or `timestampadd` in hours, minutes or seconds), or a range 
condition in place of a
+  shifted equality. Without them, the join holds back its output
+  watermark, and the query fails at start (see below) because the aggregation 
would never emit
+  results.
+
+- Since Spark 4.4, you can set 
`spark.sql.streaming.join.checkFinalization.enabled` to `false`
+  to run a stream-stream outer or left semi join that fails the requirement 
above, or a query
+  that fails the start-time check for an aggregation after a join, below. 
Spark then logs a
+  warning instead of failing the query. Joins that earlier versions also 
rejected, such as an
+  outer join without a watermarked equality key or a range condition on a 
watermarked event
+  time, still fail. The corrected state eviction cannot be turned
+  off: such a query keeps the state of the input that lacks a bound for the 
life of the query,
+  and an outer join never outputs that input's unmatched rows. Because the 
corrected eviction
+  changes results and cannot be turned off, these stream-stream join 
corrections are made in
+  Spark 4.4.0 and are not backported to earlier releases.
+
+- Spark 4.4 corrects cases where stream-stream equality joins could discard 
rows before their
+  matches arrived or output unmatched rows too early. Such joins with a 
watermark on only one
+  input now keep the watermarked input's rows for the life of the query, 
because the other input
+  has no watermark that bounds them, and hold back the join's output watermark 
for that input.
+  An append-mode aggregation over that input's event time then fails at start. 
Other stateful
+  operators after the join that use it keep its rows in state and do not emit 
results that wait
+  for the watermark, such as event-time timeouts, while update-mode 
aggregations and
+  deduplication still emit rows. Add a watermark on the other input to bound 
those rows.
+
+- With `spark.sql.streaming.statefulOperator.allowMultiple` set to `false`, an 
input of a
+  stream-stream join can keep several watermarked columns, such as its event 
time together with a
+  copy of it or a time window over it, and late rows are filtered by whichever 
of them comes
+  first. As in earlier versions, an equality key on any watermarked column of 
an input bounds the
+  other input's state, so an input built with `withColumn("window", 
window($"ts", ...))` is still

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 
[634eb849aa4](https://github.com/apache/spark/pull/60280/commits/634eb849aa45f01a4799fd376645126dcfbd3ad4)
 with your wording. The note now says that a join on the window of an input 
built with
   `withColumn("window", window($"ts", ...))` still bounds the other input's 
state by that window, so every
   sentence of the note that names a key and a bounded state names the other 
input's state.
   
   <!-- sp2k-review9 reply 4579272773 -->
   



##########
docs/streaming/ss-migration-guide.md:
##########
@@ -25,6 +25,118 @@ Please refer [Migration Guide: SQL, Datasets and 
DataFrame](../sql-migration-gui
 
 ## Upgrading from Structured Streaming 4.3 to 4.4
 
+- Since Spark 4.4, left outer and left semi stream-stream joins require a 
watermark on the
+  right input and a time condition that limits how late a matching right row 
can arrive.
+  Right outer joins require the corresponding settings on the left; full outer 
joins require
+  them on both sides. An equality key counts as such a time condition when it 
is the other
+  input's event time, or that event time shifted by constant intervals, except 
a shift backward
+  by months, years, or a day-time interval of 24 hours or more. A key such as
+  `leftTime = rightTime - INTERVAL 1 DAY` or `leftTime = rightTime - INTERVAL 
36 HOURS`, or one
+  truncated from the other input's event time, such as
+  `leftTime = CAST(CAST(rightTime AS BIGINT) AS TIMESTAMP)`, does not count, 
while
+  `timestampadd` in hours, minutes or seconds does, whatever the amount. When 
both inputs
+  have watermarks, a time range condition between the two event times can 
bound such a join
+  instead. Some previously accepted queries now fail if these requirements are 
not met. Update
+  their watermarks and join conditions using the
+  [join support 
table](apis-on-dataframes-and-datasets.html#support-matrix-for-joins-in-streaming-queries).
+  A stateful operator after such a join that uses the other input's event time 
also needs that
+  input bounded: for example, a left outer join followed by an append-mode 
aggregation over the
+  right event time also needs a watermark on the left input and a time 
condition that limits
+  how late a matching left row can arrive: an equality with an exact shift (an 
interval under
+  one day, or `timestampadd` in hours, minutes or seconds), or a range 
condition in place of a
+  shifted equality. Without them, the join holds back its output
+  watermark, and the query fails at start (see below) because the aggregation 
would never emit
+  results.
+
+- Since Spark 4.4, you can set 
`spark.sql.streaming.join.checkFinalization.enabled` to `false`
+  to run a stream-stream outer or left semi join that fails the requirement 
above, or a query
+  that fails the start-time check for an aggregation after a join, below. 
Spark then logs a
+  warning instead of failing the query. Joins that earlier versions also 
rejected, such as an
+  outer join without a watermarked equality key or a range condition on a 
watermarked event
+  time, still fail. The corrected state eviction cannot be turned
+  off: such a query keeps the state of the input that lacks a bound for the 
life of the query,
+  and an outer join never outputs that input's unmatched rows. Because the 
corrected eviction
+  changes results and cannot be turned off, these stream-stream join 
corrections are made in
+  Spark 4.4.0 and are not backported to earlier releases.
+
+- Spark 4.4 corrects cases where stream-stream equality joins could discard 
rows before their
+  matches arrived or output unmatched rows too early. Such joins with a 
watermark on only one
+  input now keep the watermarked input's rows for the life of the query, 
because the other input
+  has no watermark that bounds them, and hold back the join's output watermark 
for that input.
+  An append-mode aggregation over that input's event time then fails at start. 
Other stateful
+  operators after the join that use it keep its rows in state and do not emit 
results that wait
+  for the watermark, such as event-time timeouts, while update-mode 
aggregations and
+  deduplication still emit rows. Add a watermark on the other input to bound 
those rows.
+
+- With `spark.sql.streaming.statefulOperator.allowMultiple` set to `false`, an 
input of a
+  stream-stream join can keep several watermarked columns, such as its event 
time together with a
+  copy of it or a time window over it, and late rows are filtered by whichever 
of them comes
+  first. As in earlier versions, an equality key on any watermarked column of 
an input bounds the
+  other input's state, so an input built with `withColumn("window", 
window($"ts", ...))` is still
+  bounded by its window. Since Spark 4.4, such a key no longer bounds state 
when Spark can see
+  that some rows of the input hold the key below a watermarked column before 
it: when the key is
+  built from a time shifted backward, when it copies a column that an earlier 
watermarked window
+  is built over, or when an input of a union builds it from another column. 
Earlier versions
+  removed rows that could still match in these cases. A copy placed after a 
window needs this
+  because the query filters late rows by the first watermarked column of the 
planned input, and
+  whether the copied column survives column pruning, which analysis cannot 
see, decides whether
+  that is the copy's source or the window. If the optimizer prunes the column, 
rows are filtered
+  by the window, and evicting by the copy drops rows that can still match. 
Outer and left semi
+  joins on such a key now fail, and inner joins keep the other input's rows 
for the life of the
+  query. To bound state, join on the first watermarked column itself or on a 
time window over it,
+  or select the key before the other watermarked columns of its input. 
Checkpoints from earlier
+  versions of joins on a watermarked column after the first one are rejected 
at restart, as
+  described below.
+
+- Spark 4.4 holds back the output watermark of a stream-stream join when 
retained state can
+  still emit old event times. Downstream stateful operators may retain more 
state, take longer
+  to finalize results, or never emit results that wait for the watermark while 
the join has no
+  event-time eviction bound.
+  The join holds back only for an input whose event time reaches the next 
stateful operator: in
+  a join on `clickTime <= impressionTime + INTERVAL 1 HOUR`, a window 
aggregation over
+  `impressionTime` makes progress, and one over `clickTime` does not. Spark 
follows the event
+  time through projections, filters, unions, and time and session windows, to 
aggregations,
+  deduplication, stream-stream joins, and `flatMapGroupsWithState` or 
`transformWithState` with
+  event-time timeouts. When Spark cannot tell which input's event time the 
operator uses, for
+  example when the operator's event time is computed from the join output by a 
function, it
+  holds back for both inputs.
+
+  Since Spark 4.4, a query fails at start with 
`STREAMING_JOIN_UNBOUNDED_DOWNSTREAM_EVENT_TIME`

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 
[634eb849aa4](https://github.com/apache/spark/pull/60280/commits/634eb849aa45f01a4799fd376645126dcfbd3ad4).
 The guide and the doc of `spark.sql.streaming.join.checkFinalization.enabled` 
now
   say that the start-time check judges the nearest stream-stream join that the 
event time reaches, and that
   an aggregation behind a later join is not rejected yet (SPARK-61509): it 
starts, and does not emit results
   while an earlier join holds back its output watermark. The sentences of the 
migration guide that say that an
   append-mode aggregation fails at start now limit it to one with no later 
stream-stream join between it and
   the join. The admission error says the same: its note says that such an 
aggregation fails at start when no later stream-stream join is in between, and 
a test checks that text.
   
   <!-- sp2k-review9 reply 4579272783 -->
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -17,36 +17,395 @@
 
 package org.apache.spark.sql.catalyst.analysis
 
+import java.util.Locale
+
 import scala.util.control.NonFatal
 
 import org.apache.spark.internal.Logging
 import org.apache.spark.internal.LogKeys._
 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.{EventTimeWatermark, 
Expand, Filter, Join, LogicalPlan, Project, SubqueryAlias, 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
 
+/**
+ * Pairs of attributes `(key, eventTime)` where `key` is a copy of 
`eventTime`, or a tumbling or
+ * sliding time window over it, in every row of every stream-stream join input 
that outputs both.
+ * See [[StreamingJoinHelper.findEventTimeCopies]].
+ */
+case class EventTimeCopies(pairs: Set[(ExprId, ExprId)]) {
+  def isCopyOf(key: Expression, eventTime: Attribute): Boolean = key match {
+    case a: Attribute => pairs.contains((a.exprId, eventTime.exprId))
+    case _ => false
+  }
+
+  def keys: Set[ExprId] = pairs.map(_._1)
+}
+
+object EventTimeCopies {
+  val empty: EventTimeCopies = EventTimeCopies(Set.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.
+   */
+  def getStateKeyWatermarkOrdinal(
+      keys: Seq[Expression],
+      inputAttributes: Seq[Attribute],
+      eventTimeCopies: EventTimeCopies = EventTimeCopies.empty): Option[Int] = 
{
+    getEventTimeKeyOrdinal(keys, inputAttributes, eventTimeCopies).orElse {
+      keys.indices.find(getStateKeyWatermark(keys, inputAttributes, _, 
Some(0L)).isDefined)
+    }
+  }
+
+  /**
+   * Find the equality key that is this input's event-time column itself, or 
else one that
+   * `eventTimeCopies` names as a copy of that column or a time window over 
it. Such a key is
+   * above the watermark in every row that passes late filtering, as the 
column is: a window
+   * ends after every time it contains.
+   */
+  def getEventTimeKeyOrdinal(
+      keys: Seq[Expression],
+      inputAttributes: Seq[Attribute],
+      eventTimeCopies: EventTimeCopies = EventTimeCopies.empty): 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 =>
+      Seq(keys.indexWhere(_.semanticEquals(eventTime)),
+        keys.indexWhere(eventTimeCopies.isCopyOf(_, eventTime))).find(_ >= 0)
+    }
+  }
+
+  /**
+   * In legacy mode 
(spark.sql.streaming.statefulOperator.allowMultiple=false), an input can keep
+   * its event time and a copy of it or a time window over it, all 
watermarked, and it filters
+   * late rows by the first of them. Find, for each stream-stream join input 
in `plan`, which of
+   * its watermarked columns are a copy of, or a tumbling or sliding time 
window over, another of
+   * them. A pair counts only if every join input that outputs both columns 
builds it that way,
+   * so the result does not depend on how a physical join is matched to its 
logical one: the
+   * physical inputs output the same values under the same expression IDs, or 
fewer columns.
+   */
+  def findEventTimeCopies(plan: LogicalPlan): EventTimeCopies = {
+    val verdicts = 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
+      for (key <- watermarked; eventTime <- watermarked if key != eventTime) 
yield {
+        (key, eventTime) -> isCopyOrWindowOf(input, key, eventTime, 
allowWindow = true)
+      }
+    }
+    val rejected = verdicts.collect { case (pair, false) => pair }.toSet
+    EventTimeCopies(verdicts.collect { case (pair, true) if !rejected(pair) => 
pair }.toSet)
+  }
+
+  /**
+   * Whether `key` is `eventTime`, or a tumbling or sliding time window over 
it when
+   * `allowWindow`, in every row of `plan`. The walk follows both columns down 
by expression ID
+   * through nodes that pass values on unchanged, to the same positions in 
every input of a union,
+   * and to the node that [[TimeWindowResolution.TIME_WINDOW_SOURCE_TAG]] 
marks as building the
+   * window from an attribute, which must then be a copy of `eventTime`. Any 
other node, or any
+   * other expression, such as a shifted time, a session window or a window 
over another column,
+   * gives false.
    */
-  def isWatermarkInJoinKeys(plan: LogicalPlan): Boolean = {
-    plan match {
-      case ExtractEquiJoinKeys(_, leftKeys, rightKeys, _, _, _, _, _) =>
-        (leftKeys ++ rightKeys).exists {
-          case a: AttributeReference => 
a.metadata.contains(EventTimeWatermark.delayKey)
-          case _ => false
+  private def isCopyOrWindowOf(
+      plan: LogicalPlan,
+      key: ExprId,
+      eventTime: ExprId,
+      allowWindow: Boolean): Boolean = {
+    def passedOn(e: Expression): Option[ExprId] = e match {
+      case a: Attribute => Some(a.exprId)
+      case Alias(a: Attribute, _) => Some(a.exprId)
+      case _ => None
+    }
+    // The time column that the node tagged by the window rewrite builds 
`window` from.
+    def timeColumnOf(node: LogicalPlan, window: ExprId): Option[ExprId] =
+      node.getTagValue(TimeWindowResolution.TIME_WINDOW_SOURCE_TAG).collect {
+        case (id, timeColumn) if allowWindow && id == window => timeColumn
+      }
+    if (key == eventTime) {
+      true
+    } else {
+      plan match {
+        case p: Project =>
+          val keyEntry = p.projectList.find(_.exprId == key)
+          val eventTimeEntry = p.projectList.find(_.exprId == eventTime)
+          (keyEntry, eventTimeEntry.flatMap(passedOn)) match {
+            case (Some(entry), Some(childEventTime)) => passedOn(entry) match {
+              case Some(childKey) =>
+                isCopyOrWindowOf(p.child, childKey, childEventTime, 
allowWindow)
+              case None => timeColumnOf(p, key).exists { timeColumn =>
+                entry.references.map(_.exprId).toSet == Set(timeColumn) &&
+                  isCopyOrWindowOf(p.child, timeColumn, childEventTime, 
allowWindow = false)
+              }
+            }
+            case _ => false
+          }
+        case e: Expand =>
+          // The rewrite of a sliding window puts one window per projection 
beside the child's
+          // columns, which every projection passes on.
+          val keyIndex = e.output.indexWhere(_.exprId == key)
+          val eventTimeIndex = e.output.indexWhere(_.exprId == eventTime)
+          lazy val childEventTimes = e.projections.map(p => 
passedOn(p(eventTimeIndex))).distinct
+          keyIndex >= 0 && eventTimeIndex >= 0 && childEventTimes.size == 1 &&
+            childEventTimes.head.isDefined && timeColumnOf(e, key).exists { 
timeColumn =>
+              e.projections.forall(_(keyIndex).references.map(_.exprId).toSet 
== Set(timeColumn)) &&
+                isCopyOrWindowOf(e.child, timeColumn, childEventTimes.head.get,
+                  allowWindow = false)
+            }
+        case u: Union =>
+          val keyIndex = u.output.indexWhere(_.exprId == key)
+          val eventTimeIndex = u.output.indexWhere(_.exprId == eventTime)
+          keyIndex >= 0 && eventTimeIndex >= 0 && u.children.forall { child =>
+            isCopyOrWindowOf(child, child.output(keyIndex).exprId,
+              child.output(eventTimeIndex).exprId, allowWindow)
+          }
+        case _: Filter | _: SubqueryAlias | _: EventTimeWatermark =>
+          isCopyOrWindowOf(plan.children.head, key, eventTime, allowWindow)
+        case _ => false

Review Comment:
   > [!NOTE]
   > **DISCLAIMER:** This comment was written by an LLM: Claude Opus 5.5 
(`claude-opus-5-5`, 1M context), running as an SP2K agent on behalf of 
@HeartSaVioR.
   
   Thanks, adopted. 
[634eb849aa4](https://github.com/apache/spark/pull/60280/commits/634eb849aa45f01a4799fd376645126dcfbd3ad4)
 bounds such a copy at the watermark when the query reads the event time, and 
at the watermark less the window's length when it does not, and the rejection 
is gone; the reply on 
[StreamingJoinHelper.scala](https://github.com/apache/spark/pull/60280#discussion_r4579272747)
 has the details and the tests.
   
   <!-- sp2k-review9 reply 4579273017 -->
   



-- 
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]

Reply via email to