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


##########
sql/core/src/test/resources/structured-streaming/checkpoint-version-4.3.0-streaming-join-null-equality-key/state/0/_metadata/v2/0:
##########
@@ -0,0 +1,2 @@
+v2
+{"operatorInfo":{"operatorId":0,"operatorName":"symmetricHashJoin"},"stateStoreInfo":[{"storeName":"default","numColsPrefixKey":0,"numPartitions":5,"stateSchemaFilePaths":["file:/home/jungtaek.lim/.sp2k/scratch/5d72f621-80ec-485b-b62a-0022af2517f5/fixture-out/nullkey/state/0/_stateSchema/default/0_07ea1ca8-a130-4ef6-b81e-9d1cbf7c5128"]}],"operatorPropertiesJson":"{\"useVirtualColumnFamilies\":true}"}

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.
   
   Thanks. Fixed in 
[470c0cc6b63](https://github.com/apache/spark/pull/60280/commits/470c0cc6b6373c58c1c7b3423972d84f6d69c1bf),
 and in 
[c9700aba6b5](https://github.com/apache/spark/pull/60279/commits/c9700aba6b5664f7a636847f3a70d3a9ab9ac482)
 for the NULL event time checkpoint of #60279.
   
   The test no longer follows the path in the bundled metadata. It copies the 
checkpoint through a helper, `copyCheckpointFixture`, that points the copied 
operator metadata at the state schema file inside the copy and deletes the 
checksum file of the rewritten metadata. The helper also fails if the schema 
file that the metadata names is not in the copy, so a restart cannot pass as a 
first run. The bundled metadata of both checkpoints now names a placeholder 
directory instead of a home directory and scratch path, and has no checksum 
file. No other file of either checkpoint holds such a path; we also looked 
inside the RocksDB zips.
   
   To check that the restart compares the schemas, we changed a column type in 
the copied schema file of each checkpoint. The restart then fails with 
`STATE_STORE_KEY_SCHEMA_NOT_COMPATIBLE`, which names the type stored in the 
file and the type of the restarted plan.
   
   <!-- sp2k-review7 reply 4571565179 -->
   



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelperSuite.scala:
##########
@@ -48,6 +52,159 @@ 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
+          // left semi exact cutoff, which pass only the opposite event time; 
eviction passes the
+          // whole opposite input, so its occurrence check already returns 
None. The second
+          // condition also reaches it through eviction, which passes only the 
constrained column
+          // because leftOffset is in neither attribute set.
+          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.

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.
   
   Thanks. Fixed in 
[470c0cc6b63](https://github.com/apache/spark/pull/60280/commits/470c0cc6b6373c58c1c7b3423972d84f6d69c1bf).
 The key watermark table now has `timestampadd` keys in MICROSECOND, 
MILLISECOND and MINUTE, each with a positive and a negative amount: 3,000,000 
microseconds, 2,500 milliseconds and 2 minutes. At a watermark of 10,000 ms, 
each amount gives a key cutoff and an event-time bound that change if the unit 
had the length of a neighboring unit. For example, 2 minutes gives 129,999 and 
-110,001, where a unit of an hour would give 7,209,999. The test checks the key 
cutoff, the event-time bound and the key ordinal, as for the other units.
   
   <!-- sp2k-review7 reply 4571565188 -->
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -706,32 +707,122 @@ object UnsupportedOperationChecker extends Logging {
   }
 
   private def checkForStreamStreamJoinWatermark(join: Join): Unit = {
-    val watermarkInJoinKeys = StreamingJoinHelper.isWatermarkInJoinKeys(join)
-
-    // Check if the nullable side has a watermark, and there's a range 
condition which
-    // implies a state value watermark on the first side.
-    val hasValidWatermarkRange = join.joinType match {
-      case LeftOuter | LeftSemi => StreamingJoinHelper.getStateValueWatermark(
-        join.left.outputSet, join.right.outputSet, join.condition, 
Some(1000000)).isDefined
-      case RightOuter => StreamingJoinHelper.getStateValueWatermark(
-        join.right.outputSet, join.left.outputSet, join.condition, 
Some(1000000)).isDefined
-      case FullOuter =>
-        Seq((join.left.outputSet, join.right.outputSet),
-          (join.right.outputSet, join.left.outputSet)).exists {
-          case (attributesToFindStateWatermarkFor, 
attributesWithEventWatermark) =>
-            
StreamingJoinHelper.getStateValueWatermark(attributesToFindStateWatermarkFor,
-              attributesWithEventWatermark, join.condition, 
Some(1000000)).isDefined
-        }
+    val keys = ExtractEquiJoinKeys.unapply(join)
+    val leftKeys = keys.map(_._2).getOrElse(Nil)
+    val rightKeys = keys.map(_._3).getOrElse(Nil)
+
+    // TODO(SPARK-61347): this accepts a range bound on an input without its 
own watermark,
+    //   which eviction does not finalize yet.
+    // TODO(SPARK-61348): this also accepts a range bound on a column that is 
not TIMESTAMP,
+    //   which eviction never finalizes.
+    // TODO(SPARK-61349): this also accepts a bound that uses only constants, 
which does not
+    //   follow the other input's watermark and so cannot finalize unmatched 
state.
+    def canEvictState(
+        stateInput: LogicalPlan,
+        otherInput: LogicalPlan,
+        otherKeys: Seq[Expression]): Boolean = {
+      val eventTime = 
otherInput.output.find(_.metadata.contains(EventTimeWatermark.delayKey))
+      StreamingJoinHelper.getStateKeyWatermarkOrdinal(otherKeys, 
otherInput.output).isDefined ||
+        StreamingJoinHelper.getStateValueWatermark(stateInput.outputSet,
+          AttributeSet(eventTime.toSeq), join.condition, 
Some(1000000)).isDefined
+    }
+
+    // The rule of Spark versions before 4.4: a watermarked equality key, or a 
range bound that the
+    // solver finds for a finalized input. Disabling the finalization check 
never goes below it.
+    def admittedBeforeFinalizationCheck: Boolean = {
+      def hasRangeBound(stateInput: LogicalPlan, otherInput: LogicalPlan): 
Boolean =
+        StreamingJoinHelper.getStateValueWatermark(stateInput.outputSet, 
otherInput.outputSet,
+          join.condition, Some(1000000)).isDefined
+      (leftKeys ++ rightKeys).exists {
+        case a: AttributeReference => 
a.metadata.contains(EventTimeWatermark.delayKey)
+        case _ => false
+      } || (join.joinType match {
+        case LeftOuter | LeftSemi => hasRangeBound(join.left, join.right)
+        case RightOuter => hasRangeBound(join.right, join.left)
+        case _ => hasRangeBound(join.left, join.right) || 
hasRangeBound(join.right, join.left)
+      })
+    }
+
+    val leftCanEvict = canEvictState(join.left, join.right, rightKeys)
+    val rightCanEvict = canEvictState(join.right, join.left, leftKeys)
+    val hasRequiredWatermarks = join.joinType match {
+      case LeftOuter | LeftSemi => leftCanEvict
+      case RightOuter => rightCanEvict
+      case FullOuter => leftCanEvict && rightCanEvict
       case _ =>
         throwError(
           s"Join type ${join.joinType} is not supported with streaming 
DataFrame/Dataset")(join)
     }
 
-    if (!watermarkInJoinKeys && !hasValidWatermarkRange) {
-      throwError(
+    if (!hasRequiredWatermarks) {
+      val requirement = join.joinType match {
+        case FullOuter => "watermarks on both inputs and time constraints in 
both directions"
+        case RightOuter => "a watermark on the left input and a time 
constraint"
+        case _ => "a watermark on the right input and a time constraint"
+      }
+      // The join holds back its output watermark for an input whose state is 
unbounded.
+      val downstreamRequirement = join.joinType match {
+        case LeftOuter => Some(("right", "left"))
+        case RightOuter => Some(("left", "right"))
+        case _ => None
+      }
+      val downstreamNote = downstreamRequirement.map { case (eventTimeInput, 
boundingInput) =>
+        s" A stateful operator after the join that uses the $eventTimeInput 
input's event time " +
+          s"also needs a watermark on the $boundingInput input and a reverse 
time constraint; " +
+          "otherwise the join holds back its output watermark for that input, 
so an " +
+          "append-mode aggregation over that event time fails at start, and 
other operators " +
+          "keep that input's rows in state and do not emit results that wait 
for the watermark."
+      }.getOrElse("")
+      // In legacy mode an input can keep its event time and a window over it, 
both watermarked.
+      // Late rows are filtered by the first of them, so only that column 
bounds state.
+      val legacyWindowNote = if 
(SQLConf.get.getConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE)) {
+        ""
+      } else {
+        def windowNote(input: LogicalPlan, inputKeys: Seq[Expression], side: 
String): String = {
+          val eventTime = 
input.output.find(_.metadata.contains(EventTimeWatermark.delayKey))
+          val windowKey = inputKeys.collectFirst {
+            case a: Attribute if a.metadata.contains(TimeWindow.marker) &&
+                a.metadata.contains(EventTimeWatermark.delayKey) &&
+                !eventTime.exists(_.semanticEquals(a)) => a
+          }
+          val note = for (first <- eventTime; window <- windowKey) yield {
+            s" With ${SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key}=false, the 
$side input " +
+              s"filters late rows by its first watermarked column, 
${first.name}, so its window " +
+              s"key ${window.name} is not a time constraint. Put 
${window.name} before " +
+              s"${first.name} in that input's columns, or drop ${first.name}, 
to bound state " +
+              "by the window."
+          }
+          note.getOrElse("")
+        }
+        val leftNote = if (rightCanEvict) "" else windowNote(join.left, 
leftKeys, "left")
+        val rightNote = if (leftCanEvict) "" else windowNote(join.right, 
rightKeys, "right")
+        join.joinType match {
+          case LeftOuter | LeftSemi => rightNote
+          case RightOuter => leftNote
+          case _ => leftNote + rightNote
+        }
+      }
+      val checkConf = SQLConf.STREAMING_JOIN_CHECK_FINALIZATION_ENABLED.key
+      val canDisableCheck = admittedBeforeFinalizationCheck
+      val disableNote = if (canDisableCheck) {
+        s" To run the query anyway, set $checkConf to false; the query then 
keeps that " +
+          "state without bound, and an outer join never outputs those 
unmatched rows."
+      } else {
+        ""
+      }
+      val message =
         s"Stream-stream ${join.joinType} join between two streaming 
DataFrame/Datasets " +
-          "is not supported without a watermark in the join keys, or a 
watermark on " +
-          "the nullable side and an appropriate range condition")(join)
+          s"is not supported: it requires $requirement " +
+          "that allow unmatched state to be finalized. " +
+          "The time constraint may be equality on event time or a time range 
condition. " +
+          "When upgrading an existing query, correct its watermarks and time 
constraints, " +
+          "then use a new checkpoint and replay the input, reconciling prior 
sink output." +
+          legacyWindowNote + downstreamNote + disableNote
+      if (SQLConf.get.streamingJoinCheckFinalizationEnabled || 
!canDisableCheck) {
+        throwError(message)(join)
+      } else {
+        logWarning(log"${MDC(ANALYSIS_ERROR, message)};\n${MDC(QUERY_PLAN, 
join)}")

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.
   
   Thanks, changed in 
[470c0cc6b63](https://github.com/apache/spark/pull/60280/commits/470c0cc6b6373c58c1c7b3423972d84f6d69c1bf).
 The warning logged with `spark.sql.streaming.join.checkFinalization.enabled` 
set to `false` now says that an append-mode aggregation over that event time 
never emits results. The error keeps "fails at start", because with the conf 
set to `true` the query does not start. A test checks the left outer warning 
for the new text and for the absence of "fails at start".
   
   <!-- sp2k-review7 reply 4571565279 -->
   



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -35,18 +35,253 @@ import org.apache.spark.unsafe.types.CalendarInterval
 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]): Option[Int] = {
+    getEventTimeKeyOrdinal(keys, inputAttributes).orElse {
+      keys.indices.find(getStateKeyWatermark(keys, inputAttributes, _, 
Some(0L)).isDefined)
+    }
+  }
+
+  /** Find the equality key that is this input's event-time column itself. */
+  def getEventTimeKeyOrdinal(
+      keys: Seq[Expression],
+      inputAttributes: Seq[Attribute]): 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 =>

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, fixed in 
[470c0cc6b63](https://github.com/apache/spark/pull/60280/commits/470c0cc6b6373c58c1c7b3423972d84f6d69c1bf),
 following your conservative rule. In legacy mode an equality key on a later 
watermarked column now bounds the other input's state when the analyzed plan 
shows that every row builds it from the column that input filters late rows by: 
as a plain copy, or as a tumbling or sliding time window over that column. The 
check follows both columns by expression ID through projections that pass or 
rename a column, filters, watermarks and unions whose inputs all pass at the 
same positions, and it stops at the node that the time-window rewrite now tags 
as building the window from an attribute. Anything else keeps the current 
behavior: a window over a shifted time, a window over another input's event 
time, a session window, a union whose inputs differ, or any other node.
   
   The decision is made once. One function reads the analyzed plan and returns 
the accepted (key, event time) pairs, and both the analysis check and execution 
use it, execution through the state watermark predicates and the V4 key 
ordinals. A pair counts only if no join input that outputs both columns rejects 
it, so execution can apply it to the planned join by expression ID without 
matching physical joins to logical ones. If planning changes which column an 
input filters late rows by, for example because the optimizer prunes the event 
time, an outer or left semi join that relied on such a key now fails at start 
with `STREAMING_JOIN_EVENT_TIME_KEY_NOT_PLANNED`, or only logs it when 
`spark.sql.streaming.join.checkFinalization.enabled` is `false`.
   
   Tests cover tumbling windows, sliding windows and copies for inner, left 
outer, right outer, full outer and left semi joins in state formats 2 and 3, a 
restart, and the rejected shapes. A window over the event time less 20 seconds 
still matches a row whose window has ended. State format 4 is not affected: its 
state manager rejects an input with two watermarked columns on the base branch 
too. Checkpoints of these inputs from earlier versions are still rejected at 
restart, as you noted under Exclusions. The error hint and the migration guide 
say which keys bound state.
   
   <!-- sp2k-review7 reply 4571565358 -->
   



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