spark-test commented on code in PR #60283:
URL: https://github.com/apache/spark/pull/60283#discussion_r4523339235
##########
docs/streaming/apis-on-dataframes-and-datasets.md:
##########
@@ -1435,6 +1444,11 @@ Additional details on supported joins:
- Joins can be cascaded, that is, you can do `df1.join(df2, ...).join(df3,
...).join(df4, ....)`.
+- For stream-stream outer and semi joins, the time constraint that finalizes
an input's rows must
+ bound a timestamp column of that input by the other input's event time,
through an equality key
Review Comment:
**Nit (P3):** As worded, this excludes joins on event-time windows, which
still work. A windowed outer join such as `left.join(right, Seq("key",
"window"), "left_outer")`, the shape the windowed outer join tests in
`StreamingJoinSuite` use, bounds the left `window` column, which is a struct
rather than a timestamp column, through an equality key, and `canEvictState`
still admits it through `getStateKeyWatermarkOrdinal`. The new type check
affects range conditions only. This guide also lists `...JOIN ON leftTimeWindow
= rightTimeWindow` as one of the two ways to define the time constraint, and
the sentence this commit adds to `ss-migration-guide.md` has the same wording,
so readers with windowed joins may rewrite queries or start new checkpoints
they do not need.
Suggest wording both so that the timestamp-column rule applies to range
conditions, while equality on the other input's event time, including an
event-time window, still qualifies.
See **Shared repair plan 1** in the review body.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -706,32 +707,44 @@ 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)
+
+ 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
+ }
+
+ 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) {
+ 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"
+ }
throwError(
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. " +
Review Comment:
**Nit (P3):** Queries rejected only because of the new TIMESTAMP rule get
this message, which does not explain the rule. For the query in
`StreamingJoinNumericWatermarkSuite` (both inputs watermarked, `leftKey =
rightKey AND n > CAST(rt AS BIGINT)`), the error says the join "requires a
watermark on the right input and a time constraint that allow unmatched state
to be finalized. The time constraint may be equality on event time or a time
range condition." The query already has both, and nothing says that a range
condition must bound a TIMESTAMP column of the finalized input; only the join
guide and the migration note state that rule. Queries bounded by range
conditions on DATE or TIMESTAMP_NTZ columns, or by whole-window comparisons,
get the same message.
Suggest adding the range-condition rule here, keeping the existing statement
that equality on event time qualifies, and asserting the new text in the
numeric-bound test.
See **Shared repair plan 1** in the review body.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -186,6 +297,14 @@ 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
Review Comment:
**Blocking (P1):** This check also rejects window structs. When an input's
event-time column comes from `window()` over a watermarked time column, and the
only bound on that input is a whole-window comparison such as `lw > rw`, the
constrained attribute is a struct, so the solver now returns no cutoff, both
for analyzer admission (`canEvictState`) and for runtime eviction
(`getStateValueWatermarkForInput`).
The premise in the comment on line 300 does not hold for this case: runtime
eviction already handles a struct event-time column by comparing its `end`
field (`WatermarkSupport.watermarkExpression`), and on the base branch this
bound was admitted and evicted that way. That eviction is sound whenever the
stored windows last at least as long as the other input's. An evicted window
ends at or before the watermark W, so it starts at or before W minus its own
duration, while every later window from the other input ends after W and so
starts after W minus its duration; the evicted window therefore orders below
every later one. It is not sound when the stored windows are shorter (for
example left 10-second windows against right 20-second windows sliding by 1
second), so rejecting that case is right.
Example, from reading the code (not run): build both inputs as
`withWatermark("t", "10 seconds").select($"k", window($"t", "10
seconds").as("lw"))` (the right side uses `k2` and `rw`) and join on `$"k" ===
$"k2" && $"lw" > $"rw"`.
- `left_outer`, `left_semi`, or the mirrored `right_outer`: admitted on the
base branch, whose solver and runtime helper are the same as in Spark 4.3.0,
and now rejected with the unsupported stream-stream join error.
- Inner join: still starts, but left windows are never evicted, so its state
grows without bound.
TIMESTAMP bounds and window equality keys (`lw = rw`) are unaffected. No new
or existing test compares whole windows in a stream-stream join, so CI does not
catch this. The inner-join effect also means that this commit changes runtime
eviction, not only which queries pass analysis.
**Recommended change:** Let the state-column test accept a whole-window
ordering comparison between two window() columns when the finalized input's
windows last at least as long as the other input's, so outer and left semi
joins bounded that way pass analysis again and inner joins evict again, while
every other non-TIMESTAMP bound keeps yielding no cutoff. Record the window
duration in the window attribute's metadata next to the existing
spark.timeWindow marker when window() is resolved, and drop it where
window_time() already drops the marker. In getStateValueWatermark, accept a
struct constrained attribute only when it carries that marker and the watermark
delay key and the watermark attribute in the same comparison is a window column
whose recorded duration is no longer than the constrained window's. Offer such
watermarked window columns among the runtime eviction candidates, after the
event-time column, so every bound admission accepts is one eviction applies,
and keep the V4
range-scan offsets limited to TIMESTAMP event-time columns. Extend the join
guide and migration guide sentences this PR adds to say that a whole-window
comparison also qualifies when the finalized input's windows last at least as
long as the other input's, and add stream-stream join tests for admission and
multi-batch eviction. bc4367d9300 (SPARK-61348) added the TIMESTAMP-only test,
giving as its reason that state eviction compares the cutoff in timestamp units
against the constrained column; the base branch's solver, which accepted every
window column, is the starting point.
**Why this works:** Ordering two window structs compares their starts first.
A stored window that eviction removes ends at or below the cutoff, so it starts
at least its own duration before it; every later window from the other input
ends above the watermark, so it starts less than its own duration before it.
When the stored windows last at least as long as the other input's, every
evicted window therefore starts before every later window it is compared with
and orders below it, so the solver's cutoff, which runtime applies to the
stored window's end, is safe; when they are shorter, a later window from the
other input can start earlier and still order below the evicted one. Recording
the duration where window() is resolved lets the solver check that condition
from the two attributes in the comparison, and because admission and runtime
eviction both take their cutoff from the solver, both accept the same windows.
Windows without a recorded duration, or with a shorter finalized wind
ow, still yield no cutoff, so the base branch's unsafe case stays rejected.
**Scope:** Window-duration metadata at the window() rewrite, a window-aware
state-column test in the shared cutoff solver, matching runtime eviction
candidates and a V4 range-scan guard, plus the PR's doc sentences and
stream-stream join tests.
**Compatibility:** TIMESTAMP bounds, window equality keys and the rejection
of numeric, DATE and TIMESTAMP_NTZ bounds behave exactly as in this PR.
**Risks:** Like the existing window marker, the new metadata key shows
wherever the window column's field metadata is exposed or kept, such as Dataset
schemas, schema equality checks in user code and output schemas that keep field
metadata; the state schema check ignores field metadata, so existing
checkpoints stay readable, and the key can be removed later without a format
change. Whole-window comparisons whose finalized windows are shorter than the
other input's, session windows and user-built window structs stay rejected for
outer and left semi joins and unevicted for inner joins, as with this PR today,
although the base branch admitted them.
**Constraints:** Keep every non-TIMESTAMP bound that is not such a
whole-window comparison yielding no cutoff, so the rejection of numeric, DATE
and TIMESTAMP_NTZ bounds this PR adds is unchanged. Do not enable V4 range-scan
offsets for window event-time columns, because they read the event time as a
long. Keep the checkpoint watermark-semantics version at 4: the change only
restores, for safe windows, eviction that earlier generation-4 code already
applied to these joins, and evicting rows no future input can match keeps
existing state valid.
**Exclusions:**
- Whole-window comparisons whose finalized windows are shorter than the
other input's, session windows and window structs not built by window() stay
unsupported as a time constraint, because their cutoff cannot be shown safe.
- Left semi joins bounded on numeric, DATE or TIMESTAMP_NTZ columns are left
to the separate decision on whether to keep rejecting them.
**Success:** A left outer, right outer or left semi stream-stream join whose
only bound on the finalized input is a whole-window comparison between window()
columns, where the finalized input's windows last at least as long as the other
input's, passes analysis, and as an outer join emits each stored window as
unmatched once its end is at or below the eviction cutoff. An inner join with
such a bound removes stored windows whose end is at or below the cutoff. The
same comparisons where the finalized input's windows are shorter than the other
input's, and bounds on numeric, DATE or TIMESTAMP_NTZ columns, still yield no
cutoff, and the matching outer and left semi joins still fail analysis. V4
joins never compute range-scan offsets for a window event-time column, and
window_time() output carries no window-duration metadata.
**Verification:**
- **Regression:** A left outer stream-stream join of two 10-second tumbling
window() inputs bounded only by `lw > rw` passes analysis and, over several
micro-batches, emits a left window as unmatched only after the eviction
watermark passes its end, while the same bound passes analysis as a left semi
join and, mirrored, as a right outer join, and the left outer join also passes
analysis when the left input uses 20-second windows and the right input
10-second windows.
- **Regression:** An inner join with that bound removes left windows from
state once their end falls at or below the cutoff, with both the default state
format and state format 4.
- **Behavior:** The solver yields no cutoff for a whole-window comparison
whose finalized input uses 10-second windows while the other input uses
20-second windows sliding by 1 second, for a session window, and for a
watermarked struct column that window() did not build, and a left outer join
bounded only that way fails analysis.
- **Compatibility:** Numeric, DATE and TIMESTAMP_NTZ bounds still yield no
cutoff and their outer and left semi joins still fail analysis, and TIMESTAMP
range bounds keep their current cutoffs and output watermarks.
- **Inspection:** Every caller of the solver either applies the window case
consistently, namely admission, value eviction with its previous-cutoff scan,
and the output watermark, or excludes it, namely the V4 range-scan offsets.
--
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]