spark-test commented on code in PR #60284:
URL: https://github.com/apache/spark/pull/60284#discussion_r4598373596
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -186,6 +910,48 @@ object StreamingJoinHelper extends PredicateHelper with
Logging {
return None
}
+ // The terms count a whole day as 24 hours, although Spark adds days in
the session time
+ // zone, where a day can be 23 or 25 hours, and read CAST(ts AS BIGINT) as
ts, although the
+ // cast drops the fraction of a second. Either can put the cutoff above a
row that can still
+ // match. A column with its own watermark keeps such a cutoff, as existing
queries rely on
+ // it. With exactForUnwatermarkedColumns, any other column, such as the
bounded column of an
+ // input without a watermark, gets no cutoff from such a condition.
+ val stateColumnHasWatermark = constraintTerm.exists {
+ case a: AttributeReference =>
+ attributesToFindStateWatermarkFor.contains(a) &&
a.metadata.contains(delayKey)
+ case _ => false
+ }
+ if (exactForUnwatermarkedColumns && !stateColumnHasWatermark &&
+ hasInexactArithmetic(allOnLeftExpr)) {
+ logDebug(s"Inexact arithmetic gives an unwatermarked column no cutoff:
$allOnLeftExpr")
+ return None
+ }
+
+ // State eviction compares this cutoff in timestamp units against the
constrained column, or
+ // against its end for a time window; see [[isWindowEvictionSafe]].
+ val stateColumn = constraintTerm.collectFirst {
+ case a: AttributeReference if
attributesToFindStateWatermarkFor.contains(a) => a
+ }
+ val watermarkColumn = terms.flatMap(_.collect {
+ case a: AttributeReference
+ if attributesWithEventWatermark.contains(a) &&
a.metadata.contains(delayKey) => a
+ }).headOption
+ val canEvictStateColumn = stateColumn.exists { column =>
+ column.dataType == TimestampType ||
watermarkColumn.exists(isWindowEvictionSafe(column, _))
+ }
+ if (!baseAdmissionRules && !canEvictStateColumn) return None
+
+ // A bound needs a term on the opposite input's watermarked event time; a
conjunct that uses
+ // only constants does not follow the watermark, and gives a cutoff only
with
+ // keepConstantOnly. The occurrence check above limits each input to one
attribute, so there
+ // can be at most one such term.
+ // TODO(SPARK-61350): a watermark term with a negative coefficient still
passes this check.
+ val watermarkTerms =
terms.filter(_.references.exists(attributesWithEventWatermark.contains))
+ if (!baseAdmissionRules && (watermarkTerms.isEmpty && !keepConstantOnly ||
Review Comment:
**Blocking (P1):** With this check a constant-only conjunct such as `CAST(lt
AS BIGINT) > 10` no longer gives a cutoff, and that exposes a gap between what
admission and eviction read. The admission check solves the analyzed condition:
`StreamingQueryManager.createQuery` hands `df.queryExecution.analyzed` to
`ResolveWriteToStream`, so `rt - INTERVAL 1 SECOND * 5` is still
`TimestampAddInterval(rt, UnaryMinus(MultiplyDTInterval(...)))`, which
`collectTerms` cannot read, and `NOT (lt <= rt - INTERVAL 5 SECONDS)` is still
a negation, which `stateWatermarkOf` does not match. Eviction solves the
planned condition, after the optimizer has folded the interval and turned the
negation into `lt > rt - ...`, and reads both.
For example, reading the code, take a left semi join with watermarks on `lt`
and `rt` on `lk = rk AND lt > rt - INTERVAL 1 SECOND * 5 AND CAST(lt AS BIGINT)
> 10`. On the base branch the constant counted as a bound, so the query
started, the optimizer pushed the constant into the left input, and the left
state was evicted at the watermark less 5 seconds, with correct results. Here
admission finds no bound for `lt`, so with
`spark.sql.streaming.join.checkFinalization.enabled` at its default the query
fails at start with an error that asks for a watermark and a time constraint
the query already has. The error's note that disabling the check keeps the
state without bound is wrong for this join too, because execution does bound
it. A left outer join with the same condition, which this PR means to finalize,
fails the same way. Without the constant, such a bound already fails admission
on the base branch, so the gap is older than this PR, but the constant used to
hide it.
**Recommended change:** Before the finalization check solves the join
condition, rewrite it into the form the optimizer gives the planned condition
that eviction solves: replace each foldable subexpression with the literal of
its value, as constant folding does, and turn a NOT of a comparison into the
opposite comparison, including through De Morgan's laws, as boolean
simplification does. withIntervalLiterals, which 9c618562e01 added so that
equality keys read foldable intervals at start, is the starting point:
generalize its folding of intervals to range conditions and numeric values,
skip the current-time functions that streaming execution evaluates per batch,
keep an expression unchanged when evaluating it fails, and leave the
earlier-version rule that applies with the check disabled as it is. Add
streaming admission tests for outer and left semi joins whose range bound uses
such expressions, or is written as a negated comparison, beside a constant-only
conjunct.
**Why this works:** Eviction solves the planned condition, which the
optimizer has rewritten: every foldable expression is a literal and a NOT over
a comparison is the opposite comparison. The admission check solves the
analyzed condition, in which an interval product such as INTERVAL 1 SECOND * 5,
a call such as make_dt_interval, or a bound written as NOT (lt <= rt - INTERVAL
5 SECONDS) is still a form the solver rejects. Applying the same rewrites
before the admission solve hands the solver the condition that eviction reads,
so admission finds the bound that eviction uses. Current-time functions stay
unfolded because streaming execution replaces them per batch only after
constant folding, so an expression built on them stays unreadable there too.
**Scope:** Rewrite the join condition before the finalization check solves
it, folding its constant expressions and simplifying negated comparisons as the
optimizer does, so that admission reads range bounds as eviction does, and
cover such bounds in the admission tests.
**Compatibility:** State eviction, V4 scan offsets and the restart check
keep reading the planned condition, so the folding changes no cutoff at run
time, and joins whose only bound is constant-only still fail analysis by
default.
**Risks:** Outer and left semi joins whose only bound on a finalized input
is written in such a form, which the base branch rejected at start, now start
and are finalized by that bound. This admits more queries, only ones whose
planned condition bounds the state, and no configuration rolls it back.
**Constraints:** Fold only what constant folding replaces before execution:
skip current_timestamp() and the other current-time functions, which streaming
execution replaces per batch, and do not apply the timestampadd rewrite that
withIntervalLiterals makes for equality keys, since execution does not read
timestampadd in a range bound, so admission never finds a bound that eviction
lacks. Keep an expression unchanged when evaluating it fails, such as an
interval product that overflows, so the check raises no new error at start.
Leave the earlier-version rule that applies with the finalization check
disabled reading the analyzed condition, so it keeps reproducing earlier
versions. Change only the admission check's input: eviction, V4 scan offsets
and the restart check keep solving the planned condition as they do now.
Rewrite negated comparisons only as the optimizer's boolean simplification
does, so the rewritten condition keeps the analyzed condition's meaning,
including for NUL
Ls.
**Success:** With the finalization check at its default, a left semi join
and a left outer join on lk = rk AND lt > rt - INTERVAL 1 SECOND * 5 AND
CAST(lt AS BIGINT) > 10 start, and their left state is evicted by the range
bound. Range bounds written with make_dt_interval, an interval divided by a
number, a string cast to an interval, or numeric arithmetic on constants count
at admission whenever the planned condition gives eviction a bound from them. A
bound written as a negated comparison, such as NOT (lt <= rt - INTERVAL 5
SECONDS), counts at admission as the opposite comparison lt > rt - INTERVAL 5
SECONDS does. A bound whose value depends on current_timestamp() still gives no
bound at admission. A join whose only bound on a finalized input is
constant-only still fails analysis by default.
**Verification:**
- **Regression:** With the finalization check at its default, a left semi
join and a left outer join with watermarks on both inputs on lk = rk AND lt >
rt - INTERVAL 1 SECOND * 5 AND CAST(lt AS BIGINT) > 10 pass the admission
check, and the left outer join then outputs an unmatched left row padded with
NULLs once the right watermark is 5 seconds past it; a left semi join on lk =
rk AND NOT (lt <= rt - INTERVAL 5 SECONDS) AND CAST(lt AS BIGINT) > 10 passes
the admission check too.
- **Behavior:** The admission check accepts an outer join whose only bound
on the finalized input is written with make_dt_interval, an interval divided by
a number, a string cast to an interval, numeric arithmetic on constants, or a
negated comparison, each of which the planned condition gives eviction as a
bound.
- **Compatibility:** A range bound whose interval is computed from
current_timestamp() still gives no bound at admission, and an interval
expression whose evaluation fails leaves the admission result as it was without
the rewrite.
##########
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:
Thanks for checking, and for confirming the gap. We would still treat it as
blocking for this PR on its own: any build of master with this PR but without
#60286 gives these outer joins a row padded with nulls and loses its match,
where released versions return the match on the default state format. A narrow
rule here would close it, for example leaving the constant out only when a
bound on the column has a positive watermark coefficient, or moving the sign
check from #60286 into this PR; #60286 can then replace it.
<!-- SPARK_DEV_REVIEW_REPLY
{"feedback_id":"inline:4537904293","thread_id":"inline:4537904293","verdict_sha256":"0f2e77f9b6b482bbbf0ee85963e03f9f8f3d56fa3846112833693d90b5be7c55"}
-->
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -66,24 +752,42 @@ object StreamingJoinHelper extends PredicateHelper with
Logging {
* @param attributesWithEventWatermark attributes of the other side which
has a watermark column
* @param joinCondition join condition
* @param eventWatermark watermark defined on the input event
data
+ * @param exactForUnwatermarkedColumns whether a column without its own
watermark gets no
+ * cutoff from a condition that the
solver counts
+ * inexactly. State eviction and the
admission check set
+ * it, so they agree.
+ * @param baseAdmissionRules whether to skip the check that the
bounded column is a
Review Comment:
**Nit (P3):** The flag now also skips the watermark-term check at line 950,
so with it set a constant-only conjunct such as `CAST(lt AS BIGINT) > 10` still
yields a cutoff, and `admittedBeforeFinalizationCheck` relies on that to admit
the joins bounded only by a constant that earlier versions admitted. This doc
names only the TIMESTAMP-or-window column rule, so a caller reading it would
expect constant-only bounds to stay excluded. Its last sentence is off as well:
the older-version solve in `isOwnEventTimeIntervalJoin` also sets the flag.
**Verification:**
- **Inspection:** The baseAdmissionRules doc names both checks the flag
skips, the TIMESTAMP or time-window column rule and the rule that a bound needs
a term on the other input's watermarked event time, and names both callers that
set it, the admission rule kept with the finalization check disabled and the
older-version solve of the restart check.
--
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]