spark-test commented on code in PR #60280:
URL: https://github.com/apache/spark/pull/60280#discussion_r4571565279
##########
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:
Thanks, the separate warning reads much better. One sentence still carries
over from the error: for left and right outer joins the warning appends the
downstream note, which says that an append-mode aggregation over the other
input's event time fails at start. With
`spark.sql.streaming.join.checkFinalization.enabled` set to `false`, the
start-time check only logs `STREAMING_JOIN_UNBOUNDED_DOWNSTREAM_EVENT_TIME` and
the query runs, so that aggregation never emits results instead. Since this
warning is only logged with the conf set to `false`, could its note say that
instead?
<!-- SPARK_DEV_REVIEW_REPLY
{"feedback_id":"inline:4537719919","thread_id":"inline:4537719919","verdict_sha256":"d6c94172fe61cc5c60827e829d81f106fc5aa3273dadcc302ced375b94d12505"}
-->
##########
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:
**Nit (P3):** Of the five sub-day units that `timestampAddUnitMicros` maps
to a fixed length, only `SECOND` and `HOUR` reach an assertion in this table,
and the other suites add only `HOUR`, `DAY` and `SECOND`. Each unit's constant
sets an eviction cutoff on its own: reading the code, mapping `MINUTE` to
`MICROS_PER_HOUR` would evict the left state of a left outer join on `lt =
timestampadd(MINUTE, 10, rt)` at the watermark plus 10 hours less 1 ms,
emitting null-padded rows that later right rows could still match, and every
current test would still pass. Adding `MICROSECOND`, `MILLISECOND` and `MINUTE`
keys of both signs here, with amounts in whole milliseconds whose expected
values change when a neighboring unit's length is used, would pin them.
**Verification:**
- **Behavior:** For timestampadd keys in MICROSECOND, MILLISECOND and MINUTE
with positive and negative amounts, the key cutoff is the watermark plus the
shift less 1 ms, the event-time bound is the watermark less the shift less 1
ms, and the key's ordinal is found.
- **Regression:** Mapping MINUTE to the length of an hour or a second, or
MILLISECOND or MICROSECOND to the length of a neighboring unit, makes at least
one of the new cases fail.
##########
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:
**Non-blocking (P2):** This line names the state schema file by an absolute
path in the home directory of the machine that wrote the fixture, not the file
shipped next to it under `state/0/_stateSchema/default`. The test that resumes
this fixture copies it to a temp directory, and on the first batch
`validateAndWriteStateSchema` passes that path to
`StateSchemaCompatibilityChecker`, whose constructor creates the path's parent
directory when it is missing and whose schema read treats a missing file as a
first run. Reading the code, the test therefore fails at restart for a user who
cannot create that directory, and where it can be created, for example as root,
it runs without comparing the restarted plan's state schema with the 4.3.0
schema, so it cannot catch a schema incompatibility on this restart. The line
also publishes a local user name and scratch path. Having the test's copy step
point the copied metadata at the copied schema file and delete its stale
`.crc`, and replacing
the recorded directory here, would fix it; the null-event-time fixture from
#60279 records the same kind of path and could use the same copy step.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60280#discussion_r4537719976).
**Verification:**
- **Behavior:** After the copy, the copied operator metadata names only the
state schema file inside the test's checkpoint directory, and resuming the
Spark 4.3.0 checkpoint with a NULL equality key passes without creating or
reading anything outside the test's temp directory.
- **Regression:** Replacing the copied state schema with one that does not
match the join's state makes the resume fail with the state schema
compatibility error, which shows that the restart compares the restarted plan
with the schema shipped in the fixture instead of treating the restart as a
first run.
- **Inspection:** No file of the bundled Spark 4.3.0 checkpoint with a NULL
equality key contains a path under a user's home directory or any other
location on the machine that wrote it.
##########
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:
Thanks for laying out the reasons. This review still treats it as blocking.
These joins are correct on the base branch, as in Spark 4.3.0: legacy mode
filters late rows on `t`, and a window built from `t` ends after it, so
evicting at `window.end <= watermark` never drops a row that can still match.
For inputs that the base branch already handles correctly, a change should only
improve behavior, but here outer and left semi joins on such a window now fail
analysis, and inner joins keep both inputs' rows for the life of the query
without any message. The internal conf and the forced new checkpoint narrow who
hits this, but these queries run correctly on the base branch, and the users
who hit it must change a query that worked. We agree that a wrong plan walk
would drop rows, so it should stay conservative: accept a key only when every
path builds it from the late-filtered column itself, as a copy or a window over
that column rather than over a shifted time, keep the current behavio
r for any shape it does not recognize, and fail at start if the planned inputs
no longer show a key that admission accepted.
<!-- SPARK_DEV_REVIEW_REPLY
{"feedback_id":"inline:4537719964","thread_id":"inline:4537719964","verdict_sha256":"d6c94172fe61cc5c60827e829d81f106fc5aa3273dadcc302ced375b94d12505"}
-->
--
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]