spark-test commented on code in PR #60284:
URL: https://github.com/apache/spark/pull/60284#discussion_r4537904553
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -186,6 +297,22 @@ object StreamingJoinHelper extends PredicateHelper with
Logging {
return None
}
+ // State eviction compares this cutoff in timestamp units against the
constrained column.
+ val hasTimestampStateAttribute = constraintTerm.exists {
+ case a: AttributeReference =>
+ attributesToFindStateWatermarkFor.contains(a) && a.dataType ==
TimestampType
+ case _ => false
+ }
+ if (!hasTimestampStateAttribute) return None
+
+ // A bound must advance with the opposite watermark. The occurrence check
above limits
+ // each input to one attribute, so there can be at most one opposite
watermark term.
+ val watermarkTerms =
terms.filter(_.references.exists(attributesWithEventWatermark.contains))
+ if (watermarkTerms.isEmpty ||
Review Comment:
Thanks, this fixes the truncating-cast example, and whole-day bounds now
keep the constant's cap as well. One form from the original comment is still
exposed: the constant is still left out beside a bound whose watermark term has
a negative coefficient, when that bound's casts do not truncate. This review
raises that as a new finding.
<!-- SPARK_DEV_REVIEW_REPLY
{"feedback_id":"inline:4523590739","thread_id":"inline:4523590739","verdict_sha256":"16d1e9d35c9dc5b6e2cd711c096ac09021848f70df317096d59c88f8224807c0"}
-->
##########
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingJoinConstantWatermarkSuite.scala:
##########
@@ -0,0 +1,132 @@
+/*
+ * 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 org.apache.logging.log4j.Level
+
+import org.apache.spark.sql.Row
+import
org.apache.spark.sql.execution.streaming.operators.stateful.join.StreamingSymmetricHashJoinExec
+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
+
+class StreamingJoinConstantWatermarkSuite extends StreamTest {
+ import testImplicits._
+
+ for (version <- Seq(2, 3, 4)) {
+ test(s"static conjunct cannot stall left outer finalization, V$version") {
+ withSQLConf(
+ SQLConf.STREAMING_JOIN_STATE_FORMAT_VERSION.key -> version.toString,
+ SQLConf.STATE_STORE_PROVIDER_CLASS.key ->
classOf[RocksDBStateStoreProvider].getName,
+ SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> "false") {
+ val leftInput = MemoryStream[(Int, Long)]
+ val rightInput = MemoryStream[(Int, Long)]
+ val left = leftInput.toDF().toDF("leftKey", "time")
+ .select($"leftKey", timestamp_seconds($"time").as("lt"))
+ .withWatermark("lt", "1 second")
+ val right = rightInput.toDF().toDF("rightKey", "time")
+ .select($"rightKey", timestamp_seconds($"time").as("rt"))
+ .withWatermark("rt", "1 second")
+ val condition = expr("leftKey = rightKey AND lt > rt - INTERVAL 5
SECONDS AND " +
+ "CAST(lt AS BIGINT) > 10")
+ val joined = left.join(right, condition, "left_outer")
+ .select($"leftKey", $"lt".cast("long"), $"rt".cast("long"))
+
+ testStream(joined)(
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (1, 20L)), AddData(rightInput, (9, 20L)))),
+ CheckNewAnswer(),
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (8, 40L)), AddData(rightInput, (9, 40L)))),
+ CheckNewAnswer(),
+ AddData(rightInput, (9, 41L)),
+ CheckNewAnswer(Row(1, 20L, null)),
+ Execute { query =>
+ val join = query.lastExecution.executedPlan.collectFirst {
+ case j: StreamingSymmetricHashJoinExec => j
+ }.get
+ assert(join.eventTimeWatermarkForEviction.contains(39000L))
+ })
+ }
+ }
+
+ test(s"static conjunct still caps an inexact bound in a left outer join,
V$version") {
+ withSQLConf(
+ SQLConf.STREAMING_JOIN_STATE_FORMAT_VERSION.key -> version.toString,
+ SQLConf.STATE_STORE_PROVIDER_CLASS.key ->
classOf[RocksDBStateStoreProvider].getName,
+ SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> "false") {
+ val leftInput = MemoryStream[(Int, Long)]
+ val rightInput = MemoryStream[(Int, Long)]
+ val left = leftInput.toDF().toDF("leftKey", "ms")
+ .select($"leftKey", timestamp_millis($"ms").as("lt"))
+ .withWatermark("lt", "0 seconds")
+ val right = rightInput.toDF().toDF("rightKey", "ms")
+ .select($"rightKey", timestamp_millis($"ms").as("rt"))
+ .withWatermark("rt", "0 seconds")
+ // The truncating casts make the solver put the left cutoff at the
watermark plus 5
+ // seconds, above rows that can still match. The constant keeps
capping the cutoff.
+ val condition = expr("leftKey = rightKey AND " +
+ "CAST(lt AS BIGINT) >= CAST(rt AS BIGINT) + 5 AND CAST(lt AS BIGINT)
> 10")
+ val joined = left.join(right, condition, "left_outer")
+ .select($"leftKey", unix_millis($"lt"), unix_millis($"rt"))
+
+ testStream(joined)(
+ // The watermark becomes 10.9 seconds.
+ StreamProgressLockedActions(Seq(
+ AddData(leftInput, (1, 15500L)), AddData(rightInput, (9,
10900L)))),
+ CheckNewAnswer(),
+ AddData(rightInput, (8, 10910L)),
+ CheckNewAnswer(),
+ // 10.95 seconds is not late, and CAST(15.5 s) = 15 >= CAST(10.95 s)
+ 5 = 15.
+ AddData(rightInput, (1, 10950L)),
+ CheckNewAnswer(Row(1, 15500L, 10950L)))
+ }
+ }
+ }
+
+ // Earlier versions admitted a bound that uses only constants, so disabling
the finalization
+ // check runs this join. The left state is never evicted, so the matched
left row emits no
Review Comment:
**Nit (P3):** The matched `(1, 20 s)` row can never be NULL-padded on the
default state format, evicted or not, because evicted left rows are filtered by
their matched flag, so the "so" here links two unrelated facts. The row that
never-evicted left state actually withholds is the unmatched `(2, 100 s)`. The
last `CheckNewAnswer()` also runs at a 99-second watermark (event times of 100
s with 1-second delays), below that row, so the test passes whether or not the
left state is evicted, even though keeping that state is what the finalization
check's message says disabling it does. Rewording the comment to name the
unmatched row, and moving the watermark past 100 s before the last empty check,
would make the test show what the comment says.
**Verification:**
- **Inspection:** The comment above the disabled-check constant-only left
outer join test names the unmatched left row as the one never output with NULLs
and says nothing of the kind about the matched row.
- **Behavior:** With the finalization check disabled, the constant-only left
outer join test moves the eviction watermark past the unmatched left row's 100
seconds before its last check and asserts that no row with a NULL right side is
output, so the check fails if that state is evicted.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -114,7 +364,23 @@ object StreamingJoinHelper extends PredicateHelper with
Logging {
}
stateWatermark
}
- allStateWatermarks.reduceOption((x, y) => Math.min(x, y))
+
+ val conjuncts = splitConjunctivePredicates(joinCondition.get)
+ val boundingConjuncts = conjuncts.flatMap { predicate =>
+ stateWatermarkOf(predicate, keepConstantOnly = false).map(predicate -> _)
+ }
+ // A constant-only conjunct is left out when the other bounds follow the
watermark exactly.
+ // The solver can over-estimate an inexact bound, such as a truncating
cast or whole days,
+ // above a row that can still match. A constant's cutoff keeps that row,
as in earlier
+ // versions, so keep the constants in the minimum then.
+ val constantBounds =
+ if (boundingConjuncts.exists { case (predicate, _) =>
hasInexactArithmetic(predicate) }) {
Review Comment:
**Blocking (P1):** Reading the code, this rule keeps the constant's cutoff
only when `hasInexactArithmetic` flags a bound, and neither that test nor the
watermark-term check looks at the sign of the watermark term. So beside a bound
like `CAST(lt AS DOUBLE) > 100 - CAST(rt AS DOUBLE)`, whose casts do not
truncate, the constant is still left out, and the left cutoff is 100 s minus
the watermark: it falls as the watermark rises and sits above rows that a later
right row can still match.
Example: a left outer join with 0-second watermarks on `lt` and `rt`, on `lk
= rk AND CAST(lt AS DOUBLE) > 100 - CAST(rt AS DOUBLE) AND CAST(lt AS BIGINT) >
10`. A left row `(1, 60 s)` added together with a right row `(9, 30 s)` is
evicted at the end of that first batch, whose eviction watermark is 0 (a 100 s
cutoff), and is emitted as `(1, 60, null)`. The right row `(1, 50 s)` that
arrives next is not late, since the watermark is 30 s, and satisfies `60 > 100
- 50`, but finds no left state, so the match `(1, 60, 50)` is lost. On the base
branch, in Spark 4.3.0 and at the previous stack step, the constant's 10 s
cutoff stays in the minimum, and because the same conjunct is the left pre-join
filter, every stored row is above it, so on state formats 1 to 3 the join
returns `(1, 60, 50)`. On V4, the base branch's range-scan window for this
condition already misses the match, and this change adds the NULL-padded row.
The same holds for any left, right or full outer join where every bound on a
preserved column has a negated watermark term and no inexact arithmetic, beside
a lower-bound constant-only conjunct; DECIMAL casts with at least 6 fractional
digits, or a sum such as `CAST(lt AS DOUBLE) + CAST(rt AS DOUBLE) > 200`,
behave the same way. SPARK-61350 rejects such terms later in the stack, but a
build with this PR and without that one returns these results, and no test
covers a negated term beside a constant.
Keeping the constants in the minimum whenever no bound on the column has a
positive watermark coefficient, alongside the existing inexact-arithmetic rule,
would close this: the canonical terms already wrap a negated watermark term in
`UnaryMinus`, so the solver can report that sign with each cutoff. A column
that also has an advancing exact bound, such as `lt > rt - INTERVAL 5 SECONDS`,
would still finalize as it does now, and the TODO for SPARK-61350 can stay.
This extends existing discussions
[1](https://github.com/apache/spark/pull/60284#issuecomment-6792712277),
[2](https://github.com/apache/spark/pull/60284#discussion_r4523590739).
**Verification:**
- **Regression:** On state formats 1 to 3, a multi-batch left outer join on
`lk = rk AND CAST(lt AS DOUBLE) > 100 - CAST(rt AS DOUBLE) AND CAST(lt AS
BIGINT) > 10`, with 0-second watermarks on both inputs, adds a left row at 60
seconds together with a right row of another key at 30 seconds, so the
watermark stays at 30 seconds, then adds a matching right row at 50 seconds,
and asserts the joined row and no NULL-padded row for the left row.
- **Regression:** Solver tests assert that a lower-bound constant-only
conjunct still caps a column's cutoff whenever every bound on that column has a
negated watermark term: with DOUBLE casts, with DECIMAL casts of 6 fractional
digits, and with a sum of both event times such as `CAST(lt AS DOUBLE) +
CAST(rt AS DOUBLE) > 200`.
- **Behavior:** Solver tests assert that the constant is still left out
beside an exact bound with a positive watermark coefficient, also when another
bound on the column has a negated watermark term, and that a condition bounded
only by a constant still gives no cutoff.
- **Behavior:** The left outer join on `lt > rt - INTERVAL 5 SECONDS AND
CAST(lt AS BIGINT) > 10` still outputs its unmatched left row at eviction
watermark 39 seconds on state formats 2 to 4, the truncating-cast case still
keeps the constant's cap, and outer and left semi joins bounded only by a
constant still fail admission by default.
--
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]