spark-test commented on code in PR #60283:
URL: https://github.com/apache/spark/pull/60283#discussion_r4607464034
##########
sql/core/src/test/scala/org/apache/spark/sql/DataFrameTimeWindowingSuite.scala:
##########
@@ -632,6 +635,98 @@ class DataFrameTimeWindowingSuite extends
SharedSparkSession {
)
}
+ test("window column records its duration, and window_time drops it") {
+ val df = Seq("2016-03-27 19:38:18").toDF("time")
+ .select(window($"time", "10 seconds", "5 seconds").as("window"))
+ val windowMetadata = df.schema("window").metadata
+ assert(windowMetadata.getBoolean(TimeWindow.marker))
+ assert(TimeWindow.durationRange(windowMetadata) === Some((10000000L,
10000000L)))
+
+ val withWindowTime = df.select(window_time($"window").as("wt"))
+ val windowTimeMetadata = withWindowTime.schema("wt").metadata
+ assert(!windowTimeMetadata.contains(TimeWindow.marker))
+ assert(!windowTimeMetadata.contains(TimeWindow.minDurationKey))
+ assert(!windowTimeMetadata.contains(TimeWindow.maxDurationKey))
+ checkAnswer(withWindowTime.select($"wt".cast("string")),
+ Seq(Row("2016-03-27 19:38:19.999999"), Row("2016-03-27
19:38:24.999999")))
+ }
+
+ test("union records the shortest and longest window length of its children")
{
+ val time = spark.range(1).select(timestamp_seconds($"id").as("time"))
+ val fiveSeconds = time.select(window($"time", "5 seconds").as("window"))
+ val tenSeconds = time.select(window($"time", "10 seconds").as("window"))
+ val twentySeconds = time.select(window($"time", "20 seconds", "1
second").as("window"))
+ val plainStruct = time.select(struct($"time".as("start"),
$"time".as("end")).as("window"))
+ def outputMetadata(df: DataFrame): Seq[Metadata] = {
+ val physical = df.queryExecution.sparkPlan.collectFirst {
+ case u: UnionExec => u.output.head.metadata
+ }
+ val metadata = Seq(df.queryExecution.analyzed.output.head.metadata) ++
physical
+ assert(metadata.size == 2)
+ metadata
+ }
+
+ val seconds = 1000000L
+ Seq(
+ tenSeconds.union(twentySeconds) -> Some((10 * seconds, 20 * seconds)),
+ twentySeconds.union(tenSeconds) -> Some((10 * seconds, 20 * seconds)),
+ tenSeconds.union(twentySeconds).union(fiveSeconds) -> Some((5 * seconds,
20 * seconds)),
+ tenSeconds.union(tenSeconds) -> Some((10 * seconds, 10 * seconds)),
+ // A child that records no length leaves the union with none.
+ tenSeconds.union(plainStruct) -> None,
+ plainStruct.union(tenSeconds) -> None).foreach { case (df, range) =>
+ outputMetadata(df).foreach(m => assert(TimeWindow.durationRange(m) ===
range))
+ }
+ // The union keeps its first child's other metadata, including the window
marker.
+ outputMetadata(tenSeconds.union(plainStruct)).foreach { m =>
+ assert(m.getBoolean(TimeWindow.marker))
+ }
+ }
+
+ test("window lengths stay with the query whose window() builds the column") {
+ val time = spark.range(1).select(timestamp_seconds($"id").as("time"))
+ val twentySeconds = time.select(window($"time", "20 seconds").as("window"))
+ val tenSeconds = time.select(window($"time", "10 seconds").as("window"))
+ val tenSecondRange = Some((10000000L, 10000000L))
+ def assertNoLength(metadata: Metadata): Unit = {
+ // window_time() and other readers of stored window columns rely on the
marker.
+ assert(metadata.getBoolean(TimeWindow.marker))
+ assert(TimeWindow.durationRange(metadata) === None)
+ assert(!metadata.contains(TimeWindow.minDurationKey))
+ assert(!metadata.contains(TimeWindow.maxDurationKey))
+ }
+
+ withTable("windows") {
+ twentySeconds.write.format("parquet").saveAsTable("windows")
+ // The stored schema keeps the length, but rows appended later can have
other lengths.
+ tenSeconds.write.format("parquet").mode("append").saveAsTable("windows")
+ assertNoLength(spark.table("windows").schema("window").metadata)
+
checkAnswer(spark.table("windows").select(window_time($"window").cast("long")),
+ Seq(Row(19L), Row(9L)))
+ }
+ withTempPath { path =>
+ tenSeconds.write.parquet(path.getCanonicalPath)
+
assertNoLength(spark.read.parquet(path.getCanonicalPath).schema("window").metadata)
+ assertNoLength(spark.readStream.schema(twentySeconds.schema)
+ .parquet(path.getCanonicalPath).schema("window").metadata)
+ }
+ assertNoLength(spark.createDataFrame(tenSeconds.collect().toList.asJava,
+ twentySeconds.schema).schema("window").metadata)
+ // A window nested in a struct of a supplied schema gives no length either.
+ val nested = time.select(struct(window($"time", "20
seconds").as("w")).as("s"))
+ assertNoLength(spark.createDataFrame(nested.collect().toList.asJava,
nested.schema)
+ .select($"s.w").schema("w").metadata)
+ // Dataset.to keeps the column's own length, not the supplied schema's.
+
assert(TimeWindow.durationRange(tenSeconds.to(twentySeconds.schema).schema("window")
Review Comment:
**Nit (P3):** This assertion covers only the branch of
`TimeWindow.withDurationOf` in which the column records its own lengths. No
test applies a schema that records lengths to a column that records none, which
is the branch that keeps the supplied schema's lengths off the column. If that
branch regressed to copying the supplied metadata,
`spark.table("windows").to(twentySeconds.schema)` would record 20 seconds for
rows of any length, a stream-stream join over that column could evict windows
that later rows still match, and every test in this PR would still pass.
`Dataset.to` cases for a window column read from a table, a plain struct, and a
missing nullable field filled with NULL would cover it.
**Verification:**
- **Regression:** Dataset.to with a 20-second window schema applied to a
table's window column, to a plain struct and to a missing nullable window field
records no window length, and the check fails when the supplied schema's
lengths are copied onto those columns.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/UnsupportedOperationChecker.scala:
##########
@@ -705,33 +716,172 @@ object UnsupportedOperationChecker extends Logging {
plan = operator)
}
- 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
- }
+ private def checkForStreamStreamJoinWatermark(
+ join: Join,
+ eventTimeLags: EventTimeLags): Unit = {
+ val keys = ExtractEquiJoinKeys.unapply(join)
+ val leftKeys = keys.map(_._2).getOrElse(Nil)
+ val rightKeys = keys.map(_._3).getOrElse(Nil)
+
+ // TODO(SPARK-61349): this 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],
+ exactForUnwatermarkedColumns: Boolean = true): Boolean = {
+ // Any watermarked column of the other input can bound state: each
planned input keeps one
+ // distinct watermarked column when multiple stateful operators are
allowed, or execution
+ // fails at start, and in legacy mode its lag lowers the cutoff.
+ StreamingJoinHelper.getStateKeyWatermarkOrdinal(
+ otherKeys, otherInput.output, Some(eventTimeLags)).isDefined ||
+
StreamingJoinHelper.getStateValueWatermarkForLags(stateInput.outputSet,
otherInput.output,
+ join.condition, Some(1000000), Some(eventTimeLags),
+ exactForUnwatermarkedColumns).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), baseAdmissionRules = true).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"
+ }
+ val allowMultiple =
SQLConf.get.getConf(SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE)
+ // The join holds back its output watermark for an input whose state is
unbounded. Legacy
+ // mode gives every operator the one global watermark and ignores the
join's output
+ // watermark, so a later operator neither fails at start nor stalls
there.
+ val downstreamRequirement = join.joinType match {
+ case _ if !allowMultiple => None
+ case LeftOuter => Some(("right", "left"))
+ case RightOuter => Some(("left", "right"))
+ case _ => None
+ }
+ // The error says that such an aggregation fails at start, when no later
stream-stream join
+ // separates it from this one, which is the only one that the start-time
check judges. The
+ // warning is logged only with the finalization check disabled, which
lets the query start,
+ // so such an aggregation never emits instead.
+ def downstreamNote(aggregationOutcome: String): String =
+ downstreamRequirement.map { case (eventTimeInput, boundingInput) =>
+ s" A stateful operator after the join that uses the $eventTimeInput
input's event " +
+ s"time 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 " +
+ s"an append-mode aggregation over that event time
$aggregationOutcome, and other " +
+ "operators, such as an aggregation behind a later stream-stream
join, 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 several watermarked columns and
filters late rows by
+ // the first of them. A later watermarked key bounds state, lowered by
how far the plan
+ // shows that some rows can hold it below a watermarked column before it.
+ val legacyKeyNote = if (allowMultiple) {
+ ""
+ } else {
+ def keyNote(input: LogicalPlan, inputKeys: Seq[Expression], side:
String): String = {
+ val eventTime =
input.output.find(_.metadata.contains(EventTimeWatermark.delayKey))
+ val rejectedKey = inputKeys.collectFirst {
+ case n: NamedExpression
+ if eventTimeLags.lagOf(n, input.output).exists(_.unbounded) =>
n
+ }
+ val note = for (first <- eventTime; key <- rejectedKey) yield {
+ s" With ${SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key}=false, the
$side input " +
+ s"filters late rows by its first watermarked column,
${first.name}, and some of " +
+ s"its rows can hold the key ${key.name} below a watermarked
column before it by " +
+ s"an amount that analysis cannot bound, so ${key.name} does not
bound state. " +
+ s"This happens when ${key.name} is built from a time shifted
backward by whole " +
+ "days, months or years, when it copies a column that an earlier
session window " +
+ "with a gap that is not constant is built over, or when an input
of a union " +
+ "builds it from a column without a watermark. Column pruning can
change which " +
+ "column the planned input filters late rows by, and analysis
cannot see it. Join " +
+ s"on ${first.name} itself or on a time window over it, or put
${key.name} before " +
+ "the other watermarked columns of that input."
+ }
+ note.getOrElse("")
+ }
+ val leftNote = if (rightCanEvict) "" else keyNote(join.left, leftKeys,
"left")
+ val rightNote = if (leftCanEvict) "" else keyNote(join.right,
rightKeys, "right")
+ join.joinType match {
+ case LeftOuter | LeftSemi => rightNote
+ case RightOuter => leftNote
+ case _ => leftNote + rightNote
+ }
+ }
+ // A side that only an inexact bound would finalize has the watermark
and the time
+ // constraint; say why they are not enough.
+ def finalizedOnlyByInexactBound(side: String): Boolean = side match {
+ case "left" => !leftCanEvict &&
+ canEvictState(join.left, join.right, rightKeys,
exactForUnwatermarkedColumns = false)
+ case _ => !rightCanEvict &&
+ canEvictState(join.right, join.left, leftKeys,
exactForUnwatermarkedColumns = false)
+ }
+ val requiredSides = join.joinType match {
+ case FullOuter => Seq("left", "right")
+ case RightOuter => Seq("right")
+ case _ => Seq("left")
+ }
+ val inexactNote = requiredSides.filter(finalizedOnlyByInexactBound).map
{ side =>
+ s" The time constraint bounds the $side input only on a column without
its own " +
+ "watermark, through an interval of a day or more or a truncating
cast such as " +
+ "CAST(ts AS BIGINT), and such a bound does not finalize rows. Use an
exact bound " +
+ "instead, such as a bound shorter than a day on the TIMESTAMP
columns in place of " +
+ "the cast. A watermark on that input lets the join run, but its
cutoff then counts a " +
+ "day as 24 hours and reads the cast as exact."
+ }.mkString
+ 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 errorOutcome = "fails at start when no later stream-stream join is
in between"
+ 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. " +
+ "A time range condition must bound a TIMESTAMP column of the
finalized input by " +
+ "the other input's event time, or compare time windows as a whole
when the " +
+ "finalized input's windows are at least as long as the other
input's. " +
Review Comment:
**Nit (P3):** A join rejected because its long-enough window column was read
from a table, from files or under a supplied schema gets this message, which by
its wording says the query already qualifies and does not tell the user to
build the window with `window()` in the query. For example, a left outer join
of `spark.readStream.table` over 20-second window columns with watermarked
10-second `window()` columns, bounded only by `lw > rw`, fails with this
message. The join guide and the migration guide's inner-join bullet state the
limit; the first Spark 4.4 bullet of `docs/streaming/ss-migration-guide.md`
needs the same addition as the message:
```suggestion
"the other input's event time, or compare time windows as a whole
when the " +
"finalized input's windows are at least as long as the other
input's. Only window " +
"columns whose lengths the running query records qualify: a time
window column " +
"read from a table, from files or under a supplied schema records
none. " +
```
**Verification:**
- **Behavior:** A left outer stream-stream join over a window column read
from a table, bounded only by a whole-window comparison with shorter windows,
fails analysis with a message that says such a column records no window length.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -198,13 +1013,85 @@ object StreamingJoinHelper extends PredicateHelper with
Logging {
}
}.reduceLeft(Add(_, _))
+ // Callers can pass only the constrained column and the opposite event
time, so a term on any
+ // other column passes the occurrence check above. Its value is unknown
here.
+ if (exprWithWatermarkSubstituted.references.nonEmpty) {
+ logDebug(s"Failed to extract state constraint: unresolved
$exprWithWatermarkSubstituted")
+ return None
+ }
+
// Calculate the constraint value
logInfo(log"Final expression to evaluate " +
log"constraint:\t${MDC(WATERMARK_CONSTRAINT,
exprWithWatermarkSubstituted)}")
val constraintValue =
exprWithWatermarkSubstituted.eval().asInstanceOf[java.lang.Double]
Some((Double2double(constraintValue) / 1000.0).toLong)
}
+ /** Whether a column of a join input can take a range cutoff: TIMESTAMP, or
a time window. */
+ def canTakeRangeCutoff(column: Attribute): Boolean =
+ column.dataType == TimestampType || windowDurationRange(column).isDefined
+
+ /**
+ * The shortest and the longest window length in a column of time windows,
when the column
+ * records them: window() in the running query does, and a union does from
its children's.
+ */
+ private def windowDurationRange(column: Attribute): Option[(Long, Long)] =
+ Option(column.metadata).filter(_.contains(TimeWindow.marker))
Review Comment:
**Blocking (P1):** `windowDurationRange` accepts only columns that carry the
`spark.timeWindow` marker and recorded lengths, while `session_window()` gives
its column the time column's metadata plus only the `spark.sessionWindow`
marker, so a whole-window comparison on a session column never gets a cutoff.
For a constant gap, this loses a safe cutoff. By this review's reading of the
code, with `ls = session_window($"lt", "20 seconds")` as the left input's only
watermarked column and watermarked right windows `rw = window($"rt", "10
seconds")`, a `left_outer` join on `lk = rk AND ls > rw` fails analysis by
default. Each such session is `[lt, lt + 20 s)`, so a session evicted by its
end at the watermark starts at least 20 seconds before it, while every later
right window starts less than 10 seconds before it and orders above it. Spark
4.3.0 and the base branch admit that join and output unmatched sessions; as an
inner join it now keeps every session and holds back the output waterma
rk for the left input. Session windows were left out on the premise that their
cutoff cannot be shown safe, which does not hold for a constant gap. A session
column can still record only a lower bound, because a session-window
aggregation can merge sessions that last longer, so it qualifies only as the
stored side of the rule.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60283#discussion_r4523339214).
**Recommended change:** Record a session column's window lengths when
session_window() has a constant gap without month or day parts: the gap as its
shortest length, and an unbounded longest length because sessions that an
aggregation merges can last longer. Let the solver's window-length lookup read
session columns as well as time-window columns, so a stored session column
takes a cutoff when its gap is at least the other input's longest window, while
a session column on the watermarked side never lets an eviction pass. Say in
the join guide and the migration guide that such session windows count as the
stored side of a whole-window comparison. Add stream-stream join tests for
session windows compared as a whole with shorter and with longer windows,
before and after a session-window aggregation, and window function tests for
the lengths that a session column records.
**Why this works:** Each session that session_window() builds spans from its
time to its time plus the gap, and merging only extends it, so the gap bounds
every row's length from below; with an unbounded longest length, the existing
rule that the stored shortest length must reach the other input's longest
admits exactly the safe orderings and never trusts a session's length on the
watermarked side.
**Compatibility:** Session window aggregations keep their output and state;
only the session column's field metadata gains the length keys.
**Risks:** session_window() output columns gain the two window-length keys
in their field metadata, visible in their schemas; the state schema check
ignores field metadata, and removing the recording rolls the change back.
**Constraints:** Record nothing for a gap that is not a constant interval or
that has month or day parts, whose length depends on the session time zone. A
session column must never count as the watermarked side of the window-length
rule.
**Exclusions:**
- A session column whose gap is an expression over the input's columns keeps
getting no cutoff.
**Verification:**
- **Regression:** A left outer and an inner stream-stream join whose stored
input is a watermarked session_window() column with a 20-second gap, compared
as a whole with 10-second right windows, pass analysis, output unmatched
sessions and evict them across micro-batches.
- **Behavior:** A session column records its gap as its shortest length and
an unbounded longest length for a constant gap, records nothing for a gap from
a column or with a day part, and keeps that lower bound after a session-window
aggregation.
- **Regression:** A whole-window comparison of stored sessions with a
5-second gap against 10-second windows, or of stored windows against a
watermarked session column, gives no cutoff, and its left outer join fails
analysis.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/complexTypeExtractors.scala:
##########
@@ -260,7 +260,9 @@ case class GetStructField(child: Expression, ordinal: Int,
name: Option[String]
override protected def withNewChildInternal(newChild: Expression):
GetStructField =
copy(child = newChild)
- def metadata: Metadata = childSchema(ordinal).metadata
+ // A nested field's window lengths can come from a stored or supplied
schema, so they need not
+ // hold for its rows; see TimeWindow.withoutDuration.
+ def metadata: Metadata =
TimeWindow.withoutDuration(childSchema(ordinal).metadata)
Review Comment:
**Blocking (P1):** This strips the window lengths of every extracted field,
including fields of a struct that the running query builds. `CreateNamedStruct`
copies a field's `NamedExpression` metadata, so `struct(window($"lt", "20
seconds").as("w")).as("s")` records the window's lengths in field `w`, but
`$"s.w"` or `s.*` then yields a column that keeps the window marker and the
watermark key and has no lengths. By this review's reading of the code, a
`left_outer` join of such a 20-second `lw` with watermarked 10-second right
windows on `lk = rk AND lw > rw` therefore fails analysis by default. Spark
4.3.0 and the base branch admit that join and evict each left window by its
end, which is safe because every later 10-second right window starts after it.
As an inner join it now keeps every left window and holds back the output
watermark for the left input, and with the finalization check disabled the
outer join runs but never outputs those unmatched windows. The reply on the
earlier
thread describes dropping lengths only for nested fields of stored or supplied
schemas.
This extends existing discussions
[1](https://github.com/apache/spark/pull/60283#discussion_r4523339214),
[2](https://github.com/apache/spark/pull/60283#discussion_r4598327168).
**Recommended change:** Record the window lengths of a query-built struct's
fields in the struct column's own metadata, and let field extraction take a
field's lengths only from that record. When an alias names a struct that
struct() or named_struct() builds, record for each field the lengths that its
value records, nested structs included; when a field is extracted from a column
that carries such a record, give the extracted column that field's lengths, and
otherwise none, as now. Treat the record as a window-length key wherever
TimeWindow's helpers handle lengths: relation conversion and window_time()
remove it, Dataset.to and view resolution keep the column's own, and unions
merge it field by field with the smallest shortest and the largest longest
length, or none when a child records none. 6ffda93fc12 added the recorded
length, which nested fields then carried in their data type, and 1ee972a3d0a
removed it from every extracted field because a stored or supplied schema's
length
s need not hold for its rows; start from 6ffda93fc12's recording where
window() is resolved and keep 1ee972a3d0a's removal for fields whose column
carries no record. Add stream-stream join tests over windows extracted from
query-built structs, directly, through star expansion and through unions, and
window function tests for the lengths that extraction gives.
**Why this works:** Every boundary where a stored or supplied schema becomes
a column already removes or replaces the top-level length keys, so a field
record in a struct column's own metadata exists only when the running query
built the struct from window columns. Field extraction that trusts only that
record restores the lengths of query-built windows, while a field of a table's,
a file's or a supplied struct, whose column carries no record, still gets none.
**Compatibility:** Fields of structs from stored or supplied schemas keep
getting no window lengths, as they do at this head.
**Risks:** A struct column that the query builds from window columns gains
one field-metadata key, visible in its schema; the state schema check ignores
field metadata, and the key can be removed later without a format change. A
place that copies top-level metadata without TimeWindow's helpers would carry a
record that it should drop, so every place that handles the length keys must
handle the record too.
**Constraints:** A nested field of a struct read from a table, from files,
under readStream.schema, through createDataFrame or from a supplied struct type
still records no lengths. A union records a field's lengths only when every
child records them for that field.
**Exclusions:**
- Window structs inside arrays or maps keep getting no lengths when
generators or collection functions extract them.
**Verification:**
- **Regression:** A left outer and an inner stream-stream join whose stored
input extracts a 20-second window() column from a struct built in the query,
compared as a whole with 10-second windows, pass analysis, output unmatched
windows and evict them across micro-batches, for extraction by field name and
through star expansion.
- **Behavior:** Extracting a window field from a query-built struct gives
the window's lengths, through a union of such structs gives the smallest
shortest and the largest longest length, and from a struct of a table, of
files, under readStream.schema, through createDataFrame or from from_json with
a schema that records lengths gives none.
- **Compatibility:** Dataset.to and view resolution keep a struct column's
own field record and never a supplied schema's, and window_time() output
records no lengths.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/TimeWindow.scala:
##########
@@ -187,6 +187,66 @@ case class TimeWindow(
object TimeWindow {
val marker = "spark.timeWindow"
+ // The shortest and the longest window length in microseconds of the rows in
a column,
+ // recorded next to the marker. A stream-stream join compares them to decide
whether an
+ // ordering of two window columns can evict state. Only window() in the
running query and
+ // unions of its columns record them, so they hold for every row of the
column.
+ val minDurationKey = "spark.timeWindow.minDurationUs"
+ val maxDurationKey = "spark.timeWindow.maxDurationUs"
+ private val durationKeys = Seq(minDurationKey, maxDurationKey)
+
+ /** The shortest and the longest window length that the metadata records, if
it records both. */
+ def durationRange(metadata: Metadata): Option[(Long, Long)] =
+ if (metadata.contains(minDurationKey) &&
metadata.contains(maxDurationKey)) {
+ Some((metadata.getLong(minDurationKey),
metadata.getLong(maxDurationKey)))
+ } else {
+ None
+ }
+
+ /** The metadata with `min` and `max` as the shortest and the longest window
length. */
+ def withDuration(metadata: Metadata, min: Long, max: Long): Metadata =
+ new MetadataBuilder().withMetadata(metadata)
+ .putLong(minDurationKey, min).putLong(maxDurationKey, max).build()
+
+ /**
+ * The metadata without window lengths. A column built from a stored or
supplied schema, such
+ * as a table's, holds rows that other queries wrote, so the lengths there
need not hold for its
+ * rows. This keeps the metadata as is when it records none.
+ */
+ def withoutDuration(metadata: Metadata): Metadata =
+ if (durationKeys.exists(metadata.contains)) {
+ val builder = new MetadataBuilder().withMetadata(metadata)
+ durationKeys.foreach(builder.remove)
+ builder.build()
+ } else {
+ metadata
+ }
+
+ /**
+ * The metadata of `metadata`, a stored or supplied schema's, with the
window lengths of
+ * `column`, the column it applies to, instead of its own.
+ */
+ def withDurationOf(metadata: Metadata, column: Metadata): Metadata =
+ durationRange(column) match {
+ case Some((min, max)) => withDuration(metadata, min, max)
+ case None => withoutDuration(metadata)
+ }
+
+ /**
+ * The metadata of a union's output column, given the children's columns at
its position: the
+ * first child's, which a union keeps, with the smallest shortest and the
largest longest window
+ * length of the children, which bound the length of every row. It records
none when any child
+ * records none, so that a join does not read one child's lengths for
another child's rows.
+ */
+ def unionOutputMetadata(columns: Seq[Attribute]): Metadata = {
+ val first = columns.head.metadata
+ val ranges = columns.map(c => durationRange(c.metadata))
Review Comment:
**Nit (P3):** Every column of every union, batch or streaming, now runs this
pass over all children and allocates a `Seq` of `Option`s, and
`UnionExec.output` is a `def` that recomputes it on each call, although the
result is the first child's metadata whenever that child records no window
length, which covers every query without `window()`. Returning `first` right
away when it carries neither length key, and reading the other children only
otherwise, gives the same metadata for every column without that work.
**Verification:**
- **Inspection:** The union output metadata merge reads the other children's
metadata only when the first child's metadata carries a window-length key.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/TimeWindow.scala:
##########
@@ -187,6 +187,25 @@ case class TimeWindow(
object TimeWindow {
val marker = "spark.timeWindow"
+ // Window length in microseconds, recorded next to the marker. A
stream-stream join compares
+ // it to decide whether an ordering of two window columns can evict state.
+ val durationKey = "spark.timeWindow.durationUs"
+
+ /**
+ * The metadata of a union's output column, given the children's columns at
its position: the
+ * first child's, which a union keeps, but without the window length unless
every child records
+ * the same one. Otherwise a join would read the first child's length for
every child's rows.
+ */
+ def unionOutputMetadata(columns: Seq[Attribute]): Metadata = {
+ val first = columns.head.metadata
+ def sameDuration(metadata: Metadata): Boolean =
+ metadata.contains(durationKey) && metadata.getLong(durationKey) ==
first.getLong(durationKey)
+ if (first.contains(durationKey) && !columns.tail.forall(c =>
sameDuration(c.metadata))) {
Review Comment:
Thanks, verified at 1ee972a3d0a: a window column now records its shortest
and longest window length, a union records the smallest shortest and the
largest longest of its children, and a whole-window comparison takes a cutoff
when the stored column's shortest window lasts at least as long as the other
column's longest. A left outer join of 20-second left windows with a union of
10- and 5-second right windows now passes analysis and outputs its unmatched
left windows, and the inner join evicts them.
<!-- SPARK_DEV_REVIEW_REPLY
{"feedback_id":"inline:4598327146","thread_id":"inline:4598327146","verdict_sha256":"0bebf9d3ee7af94e86e54c34b264802f09d9faa05a0f5394fd05692dd3e7dea5"}
-->
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -198,13 +932,80 @@ object StreamingJoinHelper extends PredicateHelper with
Logging {
}
}.reduceLeft(Add(_, _))
+ // Callers can pass only the constrained column and the opposite event
time, so a term on any
+ // other column passes the occurrence check above. Its value is unknown
here.
+ if (exprWithWatermarkSubstituted.references.nonEmpty) {
+ logDebug(s"Failed to extract state constraint: unresolved
$exprWithWatermarkSubstituted")
+ return None
+ }
+
// Calculate the constraint value
logInfo(log"Final expression to evaluate " +
log"constraint:\t${MDC(WATERMARK_CONSTRAINT,
exprWithWatermarkSubstituted)}")
val constraintValue =
exprWithWatermarkSubstituted.eval().asInstanceOf[java.lang.Double]
Some((Double2double(constraintValue) / 1000.0).toLong)
}
+ /** Whether a column of a join input can take a range cutoff: TIMESTAMP, or
a time window. */
+ def canTakeRangeCutoff(column: Attribute): Boolean =
+ column.dataType == TimestampType || windowDuration(column).isDefined
+
+ /** The length of the windows in a column built by window(), when the column
records it. */
+ private def windowDuration(column: Attribute): Option[Long] = {
+ val metadata = column.metadata
+ if (metadata.contains(TimeWindow.marker) &&
metadata.contains(TimeWindow.durationKey)) {
Review Comment:
Thanks, verified at 1ee972a3d0a: columns read from tables, files,
`readStream.schema` or `createDataFrame` keep the window marker but no length,
`Dataset.to` keeps the column's own length, and the table example now keeps its
10-second window. The view premise holds for persistent views, which cannot be
read as streams, but not for SQL-text temporary and global temporary views.
Such a view is stored as its text and schema, re-analyzed on every use against
the temp views registered then, and given its stored field metadata, lengths
included. For example, take `CREATE TEMP VIEW v AS SELECT * FROM src`, where
the temp view `src` holds 20-second windows from a stream without a watermark.
After `src` is replaced with 10-second windows, the window column of `v` still
records 20 seconds. An inner join that compares that column as a whole with
right windows of 15 seconds sliding by 1 second then evicts the stored
10-second windows by their end and loses matches that the base branch outputs
. View resolution needs the same rule as `Dataset.to`: keep the rebuilt
column's own lengths, or none. This review also raises a related problem:
removing the lengths at every struct field extraction also removes them from
structs that the query builds from `window()` columns, which then lose the
cutoff that Spark 4.3.0 applies.
<!-- SPARK_DEV_REVIEW_REPLY
{"feedback_id":"inline:4598327168","thread_id":"inline:4598327168","verdict_sha256":"0bebf9d3ee7af94e86e54c34b264802f09d9faa05a0f5394fd05692dd3e7dea5"}
-->
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -66,13 +752,27 @@ 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
+ * TIMESTAMP column or a time window,
which Spark 4.4
+ * added to the solver. It does not
skip the inexact
+ * arithmetic check for columns without
their own
+ * watermark, which
exactForUnwatermarkedColumns alone
+ * controls; leave that false too for
the result of
+ * earlier versions. Only the admission
rule that stays
+ * in force with the finalization check
disabled sets it.
Review Comment:
Thanks, verified at 1ee972a3d0a: the doc now names both callers that set the
flag, and no other call in the main code sets it. They are the admission rule
that stays in force with the finalization check disabled, and the restart
compatibility check's solve of the bound that older versions derived.
<!-- SPARK_DEV_REVIEW_REPLY
{"feedback_id":"inline:4598327179","thread_id":"inline:4598327179","verdict_sha256":"0bebf9d3ee7af94e86e54c34b264802f09d9faa05a0f5394fd05692dd3e7dea5"}
-->
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/StreamingJoinHelper.scala:
##########
@@ -198,13 +932,80 @@ object StreamingJoinHelper extends PredicateHelper with
Logging {
}
}.reduceLeft(Add(_, _))
+ // Callers can pass only the constrained column and the opposite event
time, so a term on any
+ // other column passes the occurrence check above. Its value is unknown
here.
+ if (exprWithWatermarkSubstituted.references.nonEmpty) {
+ logDebug(s"Failed to extract state constraint: unresolved
$exprWithWatermarkSubstituted")
+ return None
+ }
+
// Calculate the constraint value
logInfo(log"Final expression to evaluate " +
log"constraint:\t${MDC(WATERMARK_CONSTRAINT,
exprWithWatermarkSubstituted)}")
val constraintValue =
exprWithWatermarkSubstituted.eval().asInstanceOf[java.lang.Double]
Some((Double2double(constraintValue) / 1000.0).toLong)
}
+ /** Whether a column of a join input can take a range cutoff: TIMESTAMP, or
a time window. */
+ def canTakeRangeCutoff(column: Attribute): Boolean =
+ column.dataType == TimestampType || windowDuration(column).isDefined
+
+ /** The length of the windows in a column built by window(), when the column
records it. */
+ private def windowDuration(column: Attribute): Option[Long] = {
+ val metadata = column.metadata
+ if (metadata.contains(TimeWindow.marker) &&
metadata.contains(TimeWindow.durationKey)) {
+ Some(metadata.getLong(TimeWindow.durationKey))
+ } else {
+ None
+ }
+ }
+
+ /**
+ * Whether evicting `stateWindow` by its end is safe when a range condition
compares it, as a
+ * whole, with `watermarkWindow`, the other input's watermarked time window.
Ordering windows
+ * compares their starts first. A window evicted at a cutoff no higher than
the watermark
+ * starts at least its own duration before the watermark, while a later
window of 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 later
window therefore
+ * starts after every evicted window and orders above it. Shorter stored
windows get no cutoff.
Review Comment:
Thanks, verified at 1ee972a3d0a: TODO(SPARK-61510) now sits at the
window-length rule and says what shorter stored windows do until then: an inner
join keeps their state, and an outer or left semi join bounded only that way
fails analysis.
<!-- SPARK_DEV_REVIEW_REPLY
{"feedback_id":"inline:4598327220","thread_id":"inline:4598327220","verdict_sha256":"0bebf9d3ee7af94e86e54c34b264802f09d9faa05a0f5394fd05692dd3e7dea5"}
-->
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinHelper.scala:
##########
@@ -224,98 +238,392 @@ object StreamingSymmetricHashJoinHelper extends Logging {
WatermarkSupport.findEventTimeColumn(rightAttributes,
allowMultipleEventTimeColumns = useFirstEventTimeColumn)
- val joinKeyOrdinalForWatermark: Option[Int] =
findJoinKeyOrdinalForWatermark(
- leftKeys, rightKeys)
-
def getOneSideStateWatermarkPredicate(
oneSideInputAttributes: Seq[Attribute],
oneSideJoinKeys: Seq[Expression],
- otherSideInputAttributes: Seq[Attribute]):
Option[JoinStateWatermarkPredicate] = {
- val isWatermarkDefinedOnInput =
oneSideInputAttributes.exists(_.metadata.contains(delayKey))
+ otherSideInputAttributes: Seq[Attribute],
+ otherSideJoinKeys: Seq[Expression]):
Option[JoinStateWatermarkPredicate] = {
+ // State is bounded by future input from the opposite side, not by its
own watermark.
+ val joinKeyOrdinalForWatermark =
StreamingJoinHelper.getStateKeyWatermarkOrdinal(
+ otherSideJoinKeys, otherSideInputAttributes, eventTimeLags)
val isWatermarkDefinedOnJoinKey = joinKeyOrdinalForWatermark.isDefined
if (isWatermarkDefinedOnJoinKey) { // case 1 and 3 in the
StreamingSymmetricHashJoinExec docs
+ val ordinal = joinKeyOrdinalForWatermark.get
val keyExprWithWatermark = BoundReference(
- joinKeyOrdinalForWatermark.get,
- oneSideJoinKeys(joinKeyOrdinalForWatermark.get).dataType,
- oneSideJoinKeys(joinKeyOrdinalForWatermark.get).nullable)
- val expr = watermarkExpression(Some(keyExprWithWatermark),
eventTimeWatermarkForEviction)
- expr.map { e =>
- // V4 can skip keys at or below the previous watermark only if
late-input filtering
- // rejects new rows in that range on this same key. A watermark on
the other input's
- // equality key can drive eviction even when this input has no
watermark, or has one
- // on a different column. New rows can then pass late-input
filtering with keys
- // already eligible for eviction. V4 must scan from the beginning to
find them;
- // otherwise, outer joins can fail to emit null rows for these
unmatched inputs.
- val prevStateKeyWatermark =
- if (oneSideInputAttributes.find(_.metadata.contains(delayKey))
-
.exists(oneSideJoinKeys(joinKeyOrdinalForWatermark.get).semanticEquals)) {
- eventTimeWatermarkForLateEvents
- } else {
- None
- }
- // watermarkExpression only provides the expression when
eventTimeWatermarkForEviction
- // is defined.
- JoinStateKeyWatermarkPredicate(
- e,
- eventTimeWatermarkForEviction.get,
- prevStateKeyWatermark)
- }
- } else if (isWatermarkDefinedOnInput) { // case 2 in the
StreamingSymmetricHashJoinExec docs
- val stateValueWatermark = StreamingJoinHelper.getStateValueWatermark(
- attributesToFindStateWatermarkFor =
AttributeSet(oneSideInputAttributes),
- attributesWithEventWatermark =
AttributeSet(otherSideInputAttributes),
- condition,
- eventTimeWatermarkForEviction)
- // A row can pass late-input filtering but already be eligible for
eviction in this batch.
- // When the previous join-derived state cutoff is ahead of the
late-input watermark, a new
- // row can fall at or below that cutoff. V4 must scan from the
beginning to find such rows.
- val prevStateValueWatermark = eventTimeWatermarkForLateEvents.flatMap
{ lateWatermark =>
- StreamingJoinHelper.getStateValueWatermark(
- attributesToFindStateWatermarkFor =
AttributeSet(oneSideInputAttributes),
- attributesWithEventWatermark =
AttributeSet(otherSideInputAttributes),
- condition,
- eventTimeWatermarkForLateEvents).filter(_ <= lateWatermark)
+ ordinal, oneSideJoinKeys(ordinal).dataType,
oneSideJoinKeys(ordinal).nullable)
+ // The opposite watermark bounds this key when the opposite key is
that input's event
+ // time, possibly shifted by constant intervals: by the shift for an
exact interval, and
+ // unshifted for whole days, months or years that never move a time
backward. See
+ // StreamingJoinHelper.getStateKeyWatermark for which shifts qualify.
+ def keyWatermark(watermark: Option[Long]): Option[Long] =
+ StreamingJoinHelper.getStateKeyWatermark(
+ otherSideJoinKeys, otherSideInputAttributes, ordinal, watermark,
eventTimeLags)
+ keyWatermark(eventTimeWatermarkForEviction).flatMap { stateWatermark =>
+ watermarkExpression(Some(keyExprWithWatermark),
Some(stateWatermark)).map { e =>
+ // V4 can skip keys at or below the previous watermark only if
late-input filtering
+ // rejects new rows in that range on this same key. A watermark on
the other input's
+ // equality key can drive eviction even when this input has no
watermark, or has one
+ // on a different column. New rows can then pass late-input
filtering with keys
+ // already eligible for eviction. V4 must scan from the beginning
to find them;
+ // otherwise, outer joins can fail to emit null rows for these
unmatched inputs.
+ val prevStateKeyWatermark =
+ if (oneSideInputAttributes.find(_.metadata.contains(delayKey))
+ .exists(oneSideJoinKeys(ordinal).semanticEquals)) {
+ // Late filtering drops new keys at or below the late-input
watermark, and the
+ // previous batch evicted keys up to its cutoff, which is the
cutoff at that
+ // watermark. A shifted cutoff can lie on either side of the
watermark, so the
+ // scan starts after the lower of the two.
+ eventTimeWatermarkForLateEvents.flatMap { lateWatermark =>
+ keyWatermark(Some(lateWatermark)).map(math.min(_,
lateWatermark))
+ }
+ } else {
+ None
+ }
+ JoinStateKeyWatermarkPredicate(e, stateWatermark,
prevStateKeyWatermark)
+ }
}
- val inputAttributeWithWatermark =
oneSideInputAttributes.find(_.metadata.contains(delayKey))
- val expr = watermarkExpression(inputAttributeWithWatermark,
stateValueWatermark)
- expr.map { e =>
- // watermarkExpression only provides the expression when
eventTimeWatermarkForEviction
- // is defined
- JoinStateValueWatermarkPredicate(e, stateValueWatermark.get,
prevStateValueWatermark)
+ } else { // case 2 in the StreamingSymmetricHashJoinExec docs
+ // Future matches are limited by the opposite watermark. This input
needs no watermark;
+ // its event-time column may also have been pruned from the physical
join.
+ getStateValueWatermarkForInput(oneSideInputAttributes,
otherSideInputAttributes, condition,
+ eventTimeWatermarkForEviction, eventTimeLags).flatMap { case
(attribute, watermark) =>
+ // Late filtering only constrains the input's event-time column. A
different indexed
+ // column can admit values below the previous cutoff and must be
scanned from the start.
+ val prevStateValueWatermark = eventTimeWatermarkForLateEvents.filter
{ _ =>
+ oneSideInputAttributes.find(_.metadata.contains(delayKey))
+ .exists(_.semanticEquals(attribute))
+ }.flatMap { lateWatermark =>
+ // Also scan from the start if the derived cutoff exceeds the
late-input watermark.
+
StreamingJoinHelper.getStateValueWatermarkForLags(AttributeSet(Seq(attribute)),
+ otherSideInputAttributes, condition, Some(lateWatermark),
eventTimeLags)
+ .filter(_ <= lateWatermark)
+ }
+ watermarkExpression(Some(attribute), Some(watermark)).map { e =>
+ JoinStateValueWatermarkPredicate(e, watermark,
prevStateValueWatermark)
+ }
}
- } else {
- None
}
}
val leftStateWatermarkPredicate =
- getOneSideStateWatermarkPredicate(leftAttributes, leftKeys,
rightAttributes)
+ getOneSideStateWatermarkPredicate(leftAttributes, leftKeys,
rightAttributes, rightKeys)
val rightStateWatermarkPredicate =
- getOneSideStateWatermarkPredicate(rightAttributes, rightKeys,
leftAttributes)
+ getOneSideStateWatermarkPredicate(rightAttributes, rightKeys,
leftAttributes, leftKeys)
JoinStateWatermarkPredicates(leftStateWatermarkPredicate,
rightStateWatermarkPredicate)
}
- private[join] def findJoinKeyOrdinalForWatermark(
+ /** Keep each cutoff attached to the column constrained by the join
condition. */
+ private def getStateValueWatermarkForInput(
+ inputAttributes: Seq[Attribute],
+ otherInputAttributes: Seq[Attribute],
+ condition: Option[Expression],
+ eventWatermark: Option[Long],
+ eventTimeLags: Option[EventTimeLags]): Option[(Attribute, Long)] = {
+ // TODO(SPARK-61508): an inner or left semi join side that is bounded only
through a column
+ // that is not TIMESTAMP, cast to TIMESTAMP, has no eviction predicate,
so it keeps its rows
+ // for the life of the query until eviction through the cast is
supported. Projecting the
+ // column to TIMESTAMP before the join bounds that state.
+ // TODO(SPARK-61349): a conjunct that uses only constants still caps the
cutoff, so it can
+ // stop eviction.
+ val eventTime = inputAttributes.find(_.metadata.contains(delayKey))
+ // First try the watermarked column. If it has no inferable bound, try the
other timestamp
+ // and time-window columns in input schema order and use the first with a
bound. This makes
+ // the indexed column deterministic for a fixed input schema and join
condition. The solver
+ // gives a cutoff for no other column, so the admission check, which tries
every column,
+ // accepts the same bounds.
+ val candidates = eventTime.toSeq ++ inputAttributes.filter { attribute =>
+ StreamingJoinHelper.canTakeRangeCutoff(attribute) &&
+ !eventTime.exists(_.semanticEquals(attribute))
+ }
+ candidates.iterator.flatMap { attribute =>
+
StreamingJoinHelper.getStateValueWatermarkForLags(AttributeSet(Seq(attribute)),
+ otherInputAttributes, condition, eventWatermark, eventTimeLags,
+ exactForUnwatermarkedColumns = true).map(attribute -> _)
+ }.take(1).toSeq.headOption
+ }
+
+ /**
+ * Get the equality-key ordinal at which a V4 state manager stores and looks
up a side's rows.
+ * A side evicted by key uses the key that the opposite input's watermark
bounds. Any other side
+ * stores each row at its own event time, unless it is evicted on another
column. When that
+ * event time is an equality key, its ordinal gives the same stored
timestamps and lets a lookup
+ * read one timestamp instead of scanning every timestamp of the key.
+ */
+ def getStateKeyOrdinalForLookup(
+ oneSideAttributes: Seq[Attribute],
+ oneSideKeys: Seq[Expression],
+ otherSideAttributes: Seq[Attribute],
+ otherSideKeys: Seq[Expression],
+ predicate: Option[JoinStateWatermarkPredicate]): Option[Int] = {
+ def storesRowsAtKey(ordinal: Int): Boolean = predicate match {
+ case Some(p: JoinStateValueWatermarkPredicate) =>
+ p.expr.references.forall(_.semanticEquals(oneSideKeys(ordinal)))
+ case _ => true
+ }
+ StreamingJoinHelper.getStateKeyWatermarkOrdinal(otherSideKeys,
otherSideAttributes).orElse(
+ StreamingJoinHelper.getEventTimeKeyOrdinal(oneSideKeys,
oneSideAttributes)
+ .filter(storesRowsAtKey))
+ }
+
+ /**
+ * Conservatively prove that older state can use the current watermark
semantics. Without
+ * watermarks there is no affected state. An input that neither version
evicts keeps the same
+ * rows, but its state watermark in the join's output watermark changed, so
such an input is
+ * accepted only when no stateful operator after the join reads it:
`consumedSides` names the
+ * inputs whose state watermark reaches a later operator through the join's
output watermark,
+ * both when that operator cannot be traced, and none when no stateful
operator follows, with a
+ * single global watermark, or for the right input of a left semi join. A
key-only join, with
+ * no other condition and no equality key that uses an event time, is
evicted by neither
+ * version, and V4 reads its rows by key prefix. Otherwise each side must
have exactly one
+ * event-time column, and either its own event time must be the sole
watermarked equality key
+ * at the same ordinal, or the join must be a time-interval join on the
event times (see
+ * [[isOwnEventTimeIntervalJoin]]). This excludes other range bounds. A key
computed from the
+ * event time by a constant is accepted only when it shifts the event time
forward, the other
+ * input's key at that ordinal is its own event time, no other equality key
uses an event time,
+ * and no stateful operator after the join reads the shifted input's event
time. Older versions
+ * evicted both sides at the unshifted watermark at that ordinal. For a
forward shift, that is
+ * the cutoff this version uses for the shifted side, and at or below the
one it uses for the
+ * other side, which can no longer match rows at or below it, and both
versions store V4 rows
+ * at that ordinal. Only the shifted input's bound in the output watermark
changes. Older
+ * versions evicted a backward shift before its last match. A NULL selected
key does not change
+ * the semantics: such a row can never match.
+ * Old V4 state indexed it at timestamp 0 under its own key, and the first
batch after the
+ * restart scans V4 state from the start, so it evicts the row and a
preserved side emits it
+ * unless an older version already joined it. V1 to V3 test every stored row
each batch and
+ * also evict such a row.
+ */
+ private[sql] def isWatermarkCheckpointCompatible(
+ leftAttributes: Seq[Attribute],
+ rightAttributes: Seq[Attribute],
leftKeys: Seq[Expression],
- rightKeys: Seq[Expression]): Option[Int] = {
- // Join keys of both sides generate rows of the same fields, that is, same
sequence of data
- // types. If one side (say left side) has a column (say timestamp) that
has a watermark on it,
- // then it will never consider joining keys that are < state key watermark
(i.e. event time
- // watermark). On the other side (i.e. right side), even if there is no
watermark defined,
- // there has to be an equivalent column (i.e., timestamp). And any right
side data that has the
- // timestamp < watermark will not match will not match with left side
data, as the left side get
- // filtered with the explicitly defined watermark. So, the watermark in
timestamp column in
- // left side keys effectively causes the timestamp on the right side to
have a watermark.
- // We will use the ordinal of the left timestamp in the left keys to find
the corresponding
- // right timestamp in the right keys.
- leftKeys.zipWithIndex.collectFirst {
- case (ne: NamedExpression, index) if ne.metadata.contains(delayKey) =>
index
- } orElse {
- rightKeys.zipWithIndex.collectFirst {
- case (ne: NamedExpression, index) if ne.metadata.contains(delayKey) =>
index
+ rightKeys: Seq[Expression],
+ condition: Option[Expression],
+ consumedSides: Set[JoinSide]): Boolean = {
+ val leftEventTime = leftAttributes.filter(_.metadata.contains(delayKey))
+ val rightEventTime = rightAttributes.filter(_.metadata.contains(delayKey))
+ val keyOnly = condition.isEmpty && !(leftKeys ++ rightKeys).exists { key =>
+ key.references.exists(_.metadata.contains(delayKey)) || (key match {
+ case named: NamedExpression => named.metadata.contains(delayKey)
+ case _ => false
+ })
+ }
+
+ def watermarkKeyOrdinals(keys: Seq[Expression]): Seq[Int] = {
+ keys.zipWithIndex.collect {
+ case (key: NamedExpression, index) if key.metadata.contains(delayKey)
=> index
}
}
+
+ val leftOrdinals = watermarkKeyOrdinals(leftKeys)
+ val rightOrdinals = watermarkKeyOrdinals(rightKeys)
+ if (leftEventTime.isEmpty && rightEventTime.isEmpty) {
+ leftOrdinals.isEmpty && rightOrdinals.isEmpty
+ } else if (keyOnly && consumedSides.isEmpty) {
+ true
+ } else if (leftEventTime.size == 1 && rightEventTime.size == 1) {
+ val leftOrdinal = StreamingJoinHelper.getEventTimeKeyOrdinal(leftKeys,
leftAttributes)
+ val rightOrdinal = StreamingJoinHelper.getEventTimeKeyOrdinal(rightKeys,
rightAttributes)
+ val alignedOwnEventTimeKeys = leftOrdinal.isDefined && leftOrdinal ==
rightOrdinal &&
+ leftOrdinals == leftOrdinal.toSeq && rightOrdinals ==
rightOrdinal.toSeq
+ // One input's own event-time key paired with a forward shift of the
other input's.
+ def forwardShiftedKey(
+ ownOrdinal: Option[Int],
+ ownWatermarkOrdinals: Seq[Int],
+ shiftedKeys: Seq[Expression],
+ shiftedAttributes: Seq[Attribute],
+ shiftedWatermarkOrdinals: Seq[Int],
+ shiftedSide: JoinSide): Boolean = ownOrdinal.exists { ordinal =>
+ ownWatermarkOrdinals == Seq(ordinal) &&
shiftedWatermarkOrdinals.isEmpty &&
+ StreamingJoinHelper.isForwardShiftOfEventTime(shiftedKeys(ordinal),
shiftedAttributes) &&
+ leftKeys.indices.filter(_ != ordinal).forall { i =>
+ !(leftKeys(i).references ++ rightKeys(i).references)
+ .exists(_.metadata.contains(delayKey))
+ } && !consumedSides(shiftedSide)
+ }
+ alignedOwnEventTimeKeys ||
+ forwardShiftedKey(leftOrdinal, leftOrdinals, rightKeys,
rightAttributes, rightOrdinals,
+ RightSide) ||
+ forwardShiftedKey(rightOrdinal, rightOrdinals, leftKeys,
leftAttributes, leftOrdinals,
+ LeftSide) ||
+ isOwnEventTimeIntervalJoin(leftAttributes, rightAttributes, leftKeys,
rightKeys,
+ condition, leftEventTime.head, rightEventTime.head, consumedSides)
+ } else {
+ false
+ }
+ }
+
+ /**
+ * Whether every ordering conjunct compares the two inputs' TIMESTAMP event
times, each only cast
+ * or offset by constants (see [[StreamingJoinHelper.isConstantOffsetOf]]),
or gives no bound to
+ * either input in either version, and each event time either gets a range
bound or gets none and
+ * is not in `consumedSides`. Each half of a BETWEEN counts as one conjunct,
as the solver reads
+ * it. Older versions and this one solve such conjuncts the same way for
columns with their own
+ * watermark, and older versions solved every column of an input but then
found bounds only in the
+ * same conjuncts, so they derived the same value predicates, scan starts
and V4 index columns,
+ * and neither evicts an input that gets no bound. Old V4 stored a null
event time at timestamp 0
+ * under the row's own key; both versions scan that entry the same way. No
equality key may use an
+ * event time: older versions evicted both sides of such a key at the
unshifted watermark, which
+ * [[isWatermarkCheckpointCompatible]] accepts only for a forward shift
whose shifted input no
+ * later stateful operator reads. Time windows are excluded: this version
still derives the older
Review Comment:
Thanks, verified at 1ee972a3d0a: the restart check's scaladoc and the
comment on the suite's time-window case now describe the rule at this head:
this version derives the older ordering bound only for stored windows that last
at least as long as the other input's, and the check does not apply that rule,
so it rejects every ordering of whole windows.
<!-- SPARK_DEV_REVIEW_REPLY
{"feedback_id":"inline:4598327235","thread_id":"inline:4598327235","verdict_sha256":"0bebf9d3ee7af94e86e54c34b264802f09d9faa05a0f5394fd05692dd3e7dea5"}
-->
--
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]