spark-test commented on code in PR #60379:
URL: https://github.com/apache/spark/pull/60379#discussion_r4609256386
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -230,6 +233,53 @@ case class StreamingSymmetricHashJoinExec(
private val useVirtualColumnFamilies = stateFormatVersion >= 3
+ // Only the V4 state manager reads these ordinals. They depend only on plan
fields, so
+ // doExecute computes them once on the driver instead of in every task.
+ private lazy val stateKeyOrdinalsForLookup: (Option[Int], Option[Int]) =
+ if (stateFormatVersion >= 4) {
+ (getStateKeyOrdinalForLookup(
+ left.output, leftKeys, right.output, rightKeys,
stateWatermarkPredicates.left),
+ getStateKeyOrdinalForLookup(
+ right.output, rightKeys, left.output, leftKeys,
stateWatermarkPredicates.right))
+ } else {
+ (None, None)
+ }
+
+ /**
+ * The window of the other side's state that a row of `joinSide` reads in
V4, or None to read
+ * every row for the key. V4 orders a side's state by a timestamp, unless
the side has a key
+ * ordinal (see getStateKeyOrdinalForLookup), whose lookups read the key's
exact timestamp.
+ * That timestamp is the column the side's value-eviction predicate
constrains, or its event
+ * time if it has no such predicate. The window bounds that column with the
join condition
+ * evaluated on the row; see [[MatchingScanWindow]]. For rightTime BETWEEN
leftTime AND expiry,
+ * the left side evicts on expiry: a left row reads right rows with
rightTime in
+ * [leftTime, expiry], and a right row reads left rows with expiry at or
above rightTime.
+ */
+ private[sql] def matchingScanWindow(joinSide: JoinSide):
Option[MatchingScanWindow] = {
+ val (inputAttributes, otherAttributes, otherKeyOrdinal, otherPredicate) =
joinSide match {
+ case LeftSide =>
+ (left.output, right.output, stateKeyOrdinalsForLookup._2,
stateWatermarkPredicates.right)
+ case RightSide =>
+ (right.output, left.output, stateKeyOrdinalsForLookup._1,
stateWatermarkPredicates.left)
+ }
+ if (stateFormatVersion < 4 || otherKeyOrdinal.isDefined) {
+ None
+ } else {
+
SymmetricHashJoinStateManager.valueTimestampColumnOrdinal(otherAttributes,
Review Comment:
Thanks. Recording each side's ordering fixes the restart example from the
earlier review: after a restart that adds a watermark on leftTime to the join
on leftKey = rightKey AND leftTime >= rightOther, right rows again read every
left row of their key, in that run and in later runs. This review raises five
follow-ups on the record: what happens when the join's operator metadata cannot
be read, the re-read of that metadata in every batch, the new guide sentence
about restarts from checkpoints written by earlier versions, a missing restart
test that changes how the right input's rows are ordered, and the flag's doc
comment, which does not mark exact key lookups and eviction as left to the
separate change.
<!-- SPARK_DEV_REVIEW_REPLY
{"feedback_id":"inline:4582134210","thread_id":"inline:4582134210","verdict_sha256":"2d03fde5ff3c8327d3a35be75f5bd9983389620c2755752077d7dcf961228cb4"}
-->
##########
docs/streaming/apis-on-dataframes-and-datasets.md:
##########
@@ -3587,7 +3650,12 @@ the effect of the change is not well-defined. For all of
them:
- *Streaming deduplication*: For example, `sdf.dropDuplicates("a")`. Any
change in number or type of deduplicating columns is not allowed.
- *Stream-stream join*: For example, `sdf1.join(sdf2, ...)` (i.e. both
inputs are generated with `sparkSession.readStream`). Changes
- in the schema or equi-joining columns are not allowed. Changes in join
type (outer or inner) are not allowed. Other changes in the join condition are
ill-defined.
+ in the schema or equi-joining columns are not allowed. Changes in join
type (outer or inner) are not allowed. Other changes in the join condition are
ill-defined. In particular, the join condition and the watermarks decide
+ which column Spark uses to find rows to remove from the state, so changing
either can remove rows that could still match.
+ With state format version 4, they also decide how Spark orders an input's
stored rows. When a
+ restart changes that order, a new row reads every stored row of that input
for its key to match
+ range conditions, but a lookup on an equality key over a time column can
still skip stored rows
+ that would match.
Review Comment:
**Nit (P3):** The join detects a changed order only against the ordering
record that this version writes into the join's operator metadata. Properties
written by an earlier version carry no orderings, so
`StreamingJoinOperatorProperties.fromJson` returns none and
`mixedStateOrderings` counts the checkpoint as ordered by the restarted query's
plan. Reading the code: a Spark 4.3 checkpoint of `leftKey = rightKey AND
rightTime <= leftTime + INTERVAL 5 SECONDS` with a watermark only on
`rightTime` holds left rows at bucket timestamps; restarted here with a
watermark added on `leftTime`, it passes the checkpoint compatibility check,
and each right row then reads left rows only from `rightTime - 5 seconds` up,
so it skips them. Users who upgrade and change the condition or the watermarks
in the same restart are told the opposite. Limiting the promise to checkpoints
that already record the order keeps the guide accurate, for example:
```suggestion
With state format version 4, they also decide how Spark orders an
input's stored rows. When a
restart changes that order in a checkpoint that already records it, a
new row reads every stored
row of that input for its key to match range conditions, but a lookup on
an equality key over a
time column can still skip stored rows that would match. A checkpoint
written by an earlier
Spark version does not record the order and is taken to be in the
restarted query's order, so
changing the join condition or the watermarks in the restart that
upgrades it can skip stored
rows that would match.
```
This extends an [existing
discussion](https://github.com/apache/spark/pull/60379#discussion_r4582134210).
**Verification:**
- **Inspection:** The stream-stream join item of the guide no longer
promises a full read after every restart that changes a state format 4 input's
order: it gives that promise only for checkpoints whose join already recorded
its ordering, and warns that a checkpoint from an earlier version is taken to
be in the restarted query's order, so changing the condition or the watermarks
in the restart that upgrades it can skip stored rows that would match.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala:
##########
@@ -335,11 +367,14 @@ class IncrementalExecution(
private def writeStateMetadata(
stateStoreWriter: StateStoreWriter,
metadata: OperatorStateMetadata): Unit = {
+ // A stream-stream join records the ordering of its V4 state, so the run
that can commit
+ // this batch replaces a record that an earlier, failed attempt at it
wrote.
val metadataWriter = OperatorStateMetadataWriter.createWriter(
new Path(checkpointLocation,
stateStoreWriter.getStateInfo.operatorId.toString),
hadoopConf,
metadata.version,
- Some(currentBatchId))
+ Some(currentBatchId),
+ overwrite =
stateStoreWriter.isInstanceOf[StreamingSymmetricHashJoinExec])
Review Comment:
**Nit (P3):** With `overwrite = true`, `OperatorStateMetadataV2Writer.write`
skips its exists check and replaces the file, and the ordering record relies on
that to follow the run that commits a batch. No test reaches this branch: the
V4 restart tests restart after committed batches, the batch-zero retry tests in
`StreamingJoinCheckpointCompatibilitySuite` and
`StreamingJoinRangeEvictionCheckpointSuite` fail at the checkpoint check before
any metadata is written, and `OperatorStateMetadataSuite` has no writer case
for an existing file. If this flag were dropped, a batch that a failed attempt
ran under one ordering and a retry reran under another would keep the failed
attempt's unflagged record, and a later run under the first ordering would
probe the retry's rows through windows and skip them. A writer test over an
existing file, plus a V4 test that deletes a first batch's commit, reruns the
batch under an ordering that stores one side's rows outside that side's window,
and then r
estarts under the first ordering, would catch that.
**Verification:**
- **Behavior:** Writing V2 operator metadata with overwrite for a batch that
already has a metadata file replaces the file, and the default write leaves the
existing file in place.
- **Regression:** After a run under an ordering that gives one side a scan
window writes the join's metadata for a batch and that batch's commit is
removed, rerunning the batch under an ordering that stores that side's rows
outside the window and then restarting under the first ordering leaves that
side without a window, and its rows stored during the rerun still match; the
check fails if the join's metadata write stops overwriting.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -230,6 +237,125 @@ case class StreamingSymmetricHashJoinExec(
private val useVirtualColumnFamilies = stateFormatVersion >= 3
+ // Only the V4 state manager reads these ordinals. They depend only on plan
fields, so
+ // doExecute computes them once on the driver instead of in every task.
+ private lazy val stateKeyOrdinalsForLookup: (Option[Int], Option[Int]) =
+ if (stateFormatVersion >= 4) {
+ (getStateKeyOrdinalForLookup(
+ left.output, leftKeys, right.output, rightKeys,
stateWatermarkPredicates.left),
+ getStateKeyOrdinalForLookup(
+ right.output, rightKeys, left.output, leftKeys,
stateWatermarkPredicates.right))
+ } else {
+ (None, None)
+ }
+
+ /**
+ * The window of the other side's state that a row of `joinSide` reads in
V4, or None to read
+ * every row for the key. V4 orders a side's state by a timestamp, unless
the side has a key
+ * ordinal (see getStateKeyOrdinalForLookup), whose lookups read the key's
exact timestamp.
+ * That timestamp is the column the side's value-eviction predicate
constrains, or its event
+ * time if it has no such predicate. The window bounds that column with the
join condition
+ * evaluated on the row; see [[MatchingScanWindow]]. For rightTime BETWEEN
leftTime AND expiry,
+ * the left side evicts on expiry: a left row reads right rows with
rightTime in
+ * [leftTime, expiry], and a right row reads left rows with expiry at or
above rightTime.
+ */
+ private[sql] def matchingScanWindow(joinSide: JoinSide):
Option[MatchingScanWindow] = {
+ val (inputAttributes, otherAttributes, otherKeyOrdinal, otherPredicate,
otherMixed) =
+ joinSide match {
+ case LeftSide => (left.output, right.output,
stateKeyOrdinalsForLookup._2,
+ stateWatermarkPredicates.right, mixedStateOrderings._2)
+ case RightSide => (right.output, left.output,
stateKeyOrdinalsForLookup._1,
+ stateWatermarkPredicates.left, mixedStateOrderings._1)
+ }
+ // Rows that an earlier run stored under another ordering lie outside the
window.
+ if (stateFormatVersion < 4 || otherKeyOrdinal.isDefined || otherMixed) {
+ None
+ } else {
+
SymmetricHashJoinStateManager.valueTimestampColumnOrdinal(otherAttributes,
+ stateValueWatermarkColumnOrdinal(otherPredicate,
otherAttributes)).flatMap { ordinal =>
+ MatchingScanWindow(condition.full, inputAttributes,
otherAttributes(ordinal))
+ }
+ }
+ }
+
+ /**
+ * How V4 orders a side's state under the current plan: by the timestamp of
an equality key at
+ * an ordinal, by that of a value column at an ordinal, or by none. The
checkpoint keeps each
+ * stored row under the ordering of the run that stored it.
+ */
+ private def v4StateOrdering(side: JoinSide, predicates:
JoinStateWatermarkPredicates): String = {
+ val (attributes, keys, otherAttributes, otherKeys, predicate) = side match
{
+ case LeftSide => (left.output, leftKeys, right.output, rightKeys,
predicates.left)
+ case RightSide => (right.output, rightKeys, left.output, leftKeys,
predicates.right)
+ }
+ getStateKeyOrdinalForLookup(attributes, keys, otherAttributes, otherKeys,
predicate)
+ .map(ordinal => s"key:$ordinal").getOrElse {
+ SymmetricHashJoinStateManager.valueTimestampColumnOrdinal(attributes,
+ stateValueWatermarkColumnOrdinal(predicate, attributes)).map {
ordinal =>
+ s"value:$ordinal:${attributes(ordinal).dataType.catalogString}"
+ }.getOrElse("none")
+ }
+ }
+
+ // The operator metadata is written while planning the first batch of a run,
before the
+ // eviction watermark and predicates are set, so this derives the predicates
as that batch
+ // would. Which columns they constrain does not depend on the watermark's
value.
+ private lazy val v4StateOrderings: Option[(String, String)] =
+ if (stateFormatVersion >= 4) {
+ val predicates = if (eventTimeWatermarkForEviction.isDefined) {
+ stateWatermarkPredicates
+ } else {
+ getStateWatermarkPredicates(left.output, right.output, leftKeys,
rightKeys,
+ condition.full, Some(0L), None, useFirstEventTimeColumn =
!allowMultipleStatefulOperators)
+ }
+ Some((v4StateOrdering(LeftSide, predicates), v4StateOrdering(RightSide,
predicates)))
+ } else {
+ None
+ }
+
+ /**
+ * Whether each side's V4 state may hold rows stored under another ordering
than the current
+ * plan's, as the operator metadata of an earlier batch records: a run
recorded another
+ * ordering, or recorded such rows. A probe then reads every row of that
side for its key, as
+ * before scan windows. The flag stays for the life of the checkpoint. A
checkpoint without the
+ * record, from an earlier version, counts as ordered by the current plan.
Review Comment:
**Nit (P3):** The flag only reaches `matchingScanWindow`, which gives a
flagged side no window. A side ordered by an equality-key timestamp gets no
window anyway, and its probes keep the exact lookup at the key's timestamp:
`getJoinedRows` and `getJoinedRowsAndRemoveMatched` read
`keyWithTsToValues.get(key, ts)` whenever `extractTimestampFromKey` returns one
(`SymmetricHashJoinStateManager.scala` lines 529-532 and 603-606), and
timestamp eviction ignores the flag too. Reading the code: a join on `leftKey =
rightKey AND leftTime = rightTime` that first runs without watermarks stores
its rows at bucket timestamps; after a restart that adds watermarks on both
times, both sides are flagged, yet each probe still looks up only its key's
timestamp and skips those rows. The author's reply in the restart discussion
leaves exact key lookups and eviction to a separate V4 checkpoint-format
change, and the guide warns users about the lookups, but the code says neither.
Saying what the flag cov
ers and marking the deferral would keep that visible, for example:
```suggestion
* ordering, or recorded such rows. A probe into that side then gets no
scan window and reads
* every row of the side for its key, unless the side is ordered by an
equality-key timestamp,
* whose lookups still read the key's exact timestamp; eviction also keeps
the current plan's
* layout. The flag stays for the life of the checkpoint. A checkpoint
without the record, from
* an earlier version, counts as ordered by the current plan.
* TODO: record and check each side's layout for exact key lookups and
eviction too, in the
* separate V4 checkpoint-format change.
```
This extends an [existing
discussion](https://github.com/apache/spark/pull/60379#discussion_r4582134210).
**Verification:**
- **Inspection:** The doc of the mixed-ordering flag in the stream-stream
join operator no longer says that every probe into a flagged side reads every
row of its key: it says that a flagged side gets no scan window, that a side
ordered by an equality-key timestamp keeps its exact lookup and that eviction
keeps the current plan's layout, and a TODO next to it names the separate V4
checkpoint-format change that is to cover them.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/SymmetricHashJoinStateManager.scala:
##########
@@ -106,11 +106,15 @@ trait SymmetricHashJoinStateManager {
* removing such rows would reduce state size further, but we need to weigh
the value of applying
* this optimization. This can be also impacted by the query changes during
restart, as we
* mentioned in NOTE in above, we do not define expected behavior for such
changes.
+ *
+ * @param timestampRange The same optimization hint as in [[getJoinedRows]].
Rows outside it
+ * are neither returned nor removed.
Review Comment:
**Nit (P3):** `getJoinedRows` documents the hint as one an implementation is
free to ignore, and two implementations here do ignore it:
`SymmetricHashJoinStateManagerBase`, used by state formats 1 to 3, walks every
value of the key and removes already-matched rows wherever they lie (lines
1234-1270), and the V4 manager reads the values at the key's timestamp,
whatever the range, for a side ordered by an equality-key timestamp (lines
603-606). No caller passes a range on either path today, since
`matchingScanWindow` gives no window below state format 4 or into a side with a
lookup key ordinal, but the sentence promises more than the trait guarantees.
For example:
```suggestion
* @param timestampRange The same optimization hint as in
[[getJoinedRows]]: implementations may
* ignore it, so rows outside it may still be returned or removed. The
V4 manager reads only the
* range unless the side is ordered by an equality-key timestamp.
```
This extends an [existing
discussion](https://github.com/apache/spark/pull/60379#discussion_r4549328862).
**Verification:**
- **Inspection:** The range hint's doc on getJoinedRowsAndRemoveMatched in
the join state manager trait matches every implementation: it lets an
implementation ignore the range, as the state formats 1 to 3 manager and the
state format 4 manager of a side ordered by an equality-key timestamp do, and
no longer promises for every implementation that rows outside the range are
neither returned nor removed.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -230,6 +237,125 @@ case class StreamingSymmetricHashJoinExec(
private val useVirtualColumnFamilies = stateFormatVersion >= 3
+ // Only the V4 state manager reads these ordinals. They depend only on plan
fields, so
+ // doExecute computes them once on the driver instead of in every task.
+ private lazy val stateKeyOrdinalsForLookup: (Option[Int], Option[Int]) =
+ if (stateFormatVersion >= 4) {
+ (getStateKeyOrdinalForLookup(
+ left.output, leftKeys, right.output, rightKeys,
stateWatermarkPredicates.left),
+ getStateKeyOrdinalForLookup(
+ right.output, rightKeys, left.output, leftKeys,
stateWatermarkPredicates.right))
+ } else {
+ (None, None)
+ }
+
+ /**
+ * The window of the other side's state that a row of `joinSide` reads in
V4, or None to read
+ * every row for the key. V4 orders a side's state by a timestamp, unless
the side has a key
+ * ordinal (see getStateKeyOrdinalForLookup), whose lookups read the key's
exact timestamp.
+ * That timestamp is the column the side's value-eviction predicate
constrains, or its event
+ * time if it has no such predicate. The window bounds that column with the
join condition
+ * evaluated on the row; see [[MatchingScanWindow]]. For rightTime BETWEEN
leftTime AND expiry,
+ * the left side evicts on expiry: a left row reads right rows with
rightTime in
+ * [leftTime, expiry], and a right row reads left rows with expiry at or
above rightTime.
+ */
+ private[sql] def matchingScanWindow(joinSide: JoinSide):
Option[MatchingScanWindow] = {
+ val (inputAttributes, otherAttributes, otherKeyOrdinal, otherPredicate,
otherMixed) =
+ joinSide match {
+ case LeftSide => (left.output, right.output,
stateKeyOrdinalsForLookup._2,
+ stateWatermarkPredicates.right, mixedStateOrderings._2)
+ case RightSide => (right.output, left.output,
stateKeyOrdinalsForLookup._1,
+ stateWatermarkPredicates.left, mixedStateOrderings._1)
+ }
+ // Rows that an earlier run stored under another ordering lie outside the
window.
+ if (stateFormatVersion < 4 || otherKeyOrdinal.isDefined || otherMixed) {
+ None
+ } else {
+
SymmetricHashJoinStateManager.valueTimestampColumnOrdinal(otherAttributes,
+ stateValueWatermarkColumnOrdinal(otherPredicate,
otherAttributes)).flatMap { ordinal =>
+ MatchingScanWindow(condition.full, inputAttributes,
otherAttributes(ordinal))
+ }
+ }
+ }
+
+ /**
+ * How V4 orders a side's state under the current plan: by the timestamp of
an equality key at
+ * an ordinal, by that of a value column at an ordinal, or by none. The
checkpoint keeps each
+ * stored row under the ordering of the run that stored it.
+ */
+ private def v4StateOrdering(side: JoinSide, predicates:
JoinStateWatermarkPredicates): String = {
+ val (attributes, keys, otherAttributes, otherKeys, predicate) = side match
{
+ case LeftSide => (left.output, leftKeys, right.output, rightKeys,
predicates.left)
+ case RightSide => (right.output, rightKeys, left.output, leftKeys,
predicates.right)
+ }
+ getStateKeyOrdinalForLookup(attributes, keys, otherAttributes, otherKeys,
predicate)
+ .map(ordinal => s"key:$ordinal").getOrElse {
+ SymmetricHashJoinStateManager.valueTimestampColumnOrdinal(attributes,
+ stateValueWatermarkColumnOrdinal(predicate, attributes)).map {
ordinal =>
+ s"value:$ordinal:${attributes(ordinal).dataType.catalogString}"
+ }.getOrElse("none")
+ }
+ }
+
+ // The operator metadata is written while planning the first batch of a run,
before the
+ // eviction watermark and predicates are set, so this derives the predicates
as that batch
+ // would. Which columns they constrain does not depend on the watermark's
value.
+ private lazy val v4StateOrderings: Option[(String, String)] =
+ if (stateFormatVersion >= 4) {
+ val predicates = if (eventTimeWatermarkForEviction.isDefined) {
+ stateWatermarkPredicates
+ } else {
+ getStateWatermarkPredicates(left.output, right.output, leftKeys,
rightKeys,
+ condition.full, Some(0L), None, useFirstEventTimeColumn =
!allowMultipleStatefulOperators)
+ }
+ Some((v4StateOrdering(LeftSide, predicates), v4StateOrdering(RightSide,
predicates)))
+ } else {
+ None
+ }
+
+ /**
+ * Whether each side's V4 state may hold rows stored under another ordering
than the current
+ * plan's, as the operator metadata of an earlier batch records: a run
recorded another
+ * ordering, or recorded such rows. A probe then reads every row of that
side for its key, as
+ * before scan windows. The flag stays for the life of the checkpoint. A
checkpoint without the
+ * record, from an earlier version, counts as ordered by the current plan.
+ */
+ private[sql] lazy val mixedStateOrderings: (Boolean, Boolean) =
+ (v4StateOrderings, previousJoinProperties.flatMap(p =>
+ p.stateOrderings.map(_ -> p.mixedOrderings))) match {
+ case (Some((left, right)), Some(((previousLeft, previousRight),
(leftMixed, rightMixed)))) =>
+ (leftMixed || previousLeft != left, rightMixed || previousRight !=
right)
+ case _ => (false, false)
+ }
+
+ // The join properties recorded at or before the previous batch: by the
first batch of this
+ // run, or by an earlier run when this is the first batch.
+ private lazy val previousJoinProperties:
Option[StreamingJoinOperatorProperties] =
+ stateInfo.filter(info => useVirtualColumnFamilies && info.storeVersion >
0).flatMap { info =>
+ try {
+ OperatorStateMetadataReader.createReader(
+ new Path(info.checkpointLocation, info.operatorId.toString),
+ hadoopConfBcast.value.value, _operatorStateMetadataVersion,
info.storeVersion - 1,
+ createMetadataDir = false).read().collect {
+ case m: OperatorStateMetadataV2 =>
+ StreamingJoinOperatorProperties.fromJson(m.operatorPropertiesJson)
+ }
+ } catch {
+ case NonFatal(e) =>
Review Comment:
**Non-blocking (P2):** This catch treats every failure to read the record as
a checkpoint without one: besides the reader's error for a missing metadata
file, it also swallows I/O errors while listing the offsets or metadata
directory or opening the file, and parse errors. `mixedStateOrderings` then
returns `(false, false)`, the answer meant for properties without orderings,
which `fromJson` already reports without an exception. On a run's first batch,
the planning-time join writes that pair into the run's record (lines 416-417),
so the flag that a reordering restart set is lost for the rest of the
checkpoint's life. Reading the code: with `leftKey = rightKey AND leftTime >=
rightOther`, a first run with a watermark only on `rightTime` stores left rows
at bucket timestamps, and a second run that adds a watermark on `leftTime`
flags the left side. If the third run's first-batch read fails, for example on
a transient listing error, its record clears the flag, and from the next batch
on each right row reads left rows only from its `rightOther` up and skips the
first run's rows, which still match. The validation read in
`IncrementalExecution` tolerates the same failure, but there it only skips a
check.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60379#discussion_r4582134210).
**Recommended change:** Make a failed read of the previous ordering record
fail the batch instead of counting the join's state as ordered by the current
plan. In previousJoinProperties (StreamingSymmetricHashJoinExec.scala:333-349),
treat only StateDataSourceReadOperatorMetadataFailure, which the V2 metadata
reader throws when no metadata file exists at or before the previous batch, as
an absent record, and let every other error propagate, such as an I/O error
while listing or opening the metadata or a file that cannot be parsed. Evaluate
the read only for state format 4, the only format whose windows use it, so that
state format 3 joins gain no new way to fail.
**Why this works:** The read keeps its two legitimate outcomes, a readable
record, with or without orderings, and no metadata file at all, and stops
turning a failure into either of them. A failure while planning a run's first
batch now stops planning before writeStateMetadata
(IncrementalExecution.scala:336-338), so no record with cleared flags is
written, and a failure in doExecute stops the batch before any probe runs;
restarting the query reads the record again. A side that the record flags, or
whose ordering changed, therefore never gets a window because a read failed.
**Compatibility:** A checkpoint without an ordering record, such as one
written by an earlier version, keeps counting as ordered by the current plan,
and a readable record keeps setting and carrying the mixed-ordering flags as it
does now.
**Risks:** A state format 4 query whose join operator metadata is corrupt or
unreadable now stops with the read error instead of running with windows, and
runs again once the file is readable. Removing the join's metadata directory
also lets it run, but the checkpoint then counts as having no record, so a side
flagged earlier gets windows again and can skip rows stored under its earlier
ordering. Restoring the catch rolls the change back. While the record is still
read in every batch, a transient storage error in that read now stops a running
state format 4 query; reading the record only once per run, the fix for the
per-batch metadata read, limits this to planning a run's first batch.
**Constraints:** A checkpoint with no join metadata file at or before the
previous batch, or whose join properties have no orderings, as an earlier
version writes them, must keep counting as ordered by the current plan. State
format 1 to 3 joins must not read the ordering record, so they cannot fail on
it.
**Exclusions:**
- How often the record is read: this change decides only what a failed read
means, and reading the record once per run is a separate fix.
**Verification:**
- **Regression:** After a restart that changes how one side's state is
ordered, make the join's previous operator metadata unreadable, for example by
replacing its file with one that cannot be parsed: the restarted query fails
with the read error and writes no new record for the join, and once the file is
readable again, a probe into the reordered side has no window and new rows
match the rows stored before the restart.
- **Compatibility:** A state format 4 join restarted from a checkpoint whose
join properties have no orderings, as an earlier version writes them, or that
has no join metadata file at all, runs without error and keeps the windows of
the current plan.
- **Compatibility:** A state format 3 join restarted from a checkpoint whose
join operator metadata cannot be parsed runs as it does on the base branch.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -230,6 +237,125 @@ case class StreamingSymmetricHashJoinExec(
private val useVirtualColumnFamilies = stateFormatVersion >= 3
+ // Only the V4 state manager reads these ordinals. They depend only on plan
fields, so
+ // doExecute computes them once on the driver instead of in every task.
+ private lazy val stateKeyOrdinalsForLookup: (Option[Int], Option[Int]) =
+ if (stateFormatVersion >= 4) {
+ (getStateKeyOrdinalForLookup(
+ left.output, leftKeys, right.output, rightKeys,
stateWatermarkPredicates.left),
+ getStateKeyOrdinalForLookup(
+ right.output, rightKeys, left.output, leftKeys,
stateWatermarkPredicates.right))
+ } else {
+ (None, None)
+ }
+
+ /**
+ * The window of the other side's state that a row of `joinSide` reads in
V4, or None to read
+ * every row for the key. V4 orders a side's state by a timestamp, unless
the side has a key
+ * ordinal (see getStateKeyOrdinalForLookup), whose lookups read the key's
exact timestamp.
+ * That timestamp is the column the side's value-eviction predicate
constrains, or its event
+ * time if it has no such predicate. The window bounds that column with the
join condition
+ * evaluated on the row; see [[MatchingScanWindow]]. For rightTime BETWEEN
leftTime AND expiry,
+ * the left side evicts on expiry: a left row reads right rows with
rightTime in
+ * [leftTime, expiry], and a right row reads left rows with expiry at or
above rightTime.
+ */
+ private[sql] def matchingScanWindow(joinSide: JoinSide):
Option[MatchingScanWindow] = {
+ val (inputAttributes, otherAttributes, otherKeyOrdinal, otherPredicate,
otherMixed) =
+ joinSide match {
+ case LeftSide => (left.output, right.output,
stateKeyOrdinalsForLookup._2,
+ stateWatermarkPredicates.right, mixedStateOrderings._2)
Review Comment:
**Nit (P3):** This branch reads `mixedStateOrderings._2`, the right state's
flag that the record stores as `rightMixedOrdering`, but no test sets it:
'matching scans read every stored row after a restart changes a side's
ordering' changes only the left state's ordering and asserts only that
`matchingScanWindow(RightSide)` is empty, and the restart without a change
keeps both windows. So reading `._1` here, deriving the right flag from the
left orderings, or misspelling `rightMixedOrdering` in
`StreamingJoinOperatorProperties.json` or `fromJson` would leave every test
passing, while left rows would skip right rows stored before a restart that
reorders the right state. A mirror of the existing test would catch it: for
example, a join on `leftKey = rightKey AND rightTime >= leftOther` whose second
run adds a watermark on `rightTime`, checking in that run and the next that
`matchingScanWindow(LeftSide)` is empty and that new left rows match right rows
stored before the restart.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60379#discussion_r4582134210).
**Verification:**
- **Regression:** With a restart that changes only the right state's
ordering, a left-row probe has no window into the right state in the restarted
run and in the next run, and new left rows match right rows stored before the
restart; the check fails if left-row probes read the left state's flag, if the
right flag is derived from the left orderings, or if the recorded right flag is
lost.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/join/StreamingSymmetricHashJoinExec.scala:
##########
@@ -230,6 +237,125 @@ case class StreamingSymmetricHashJoinExec(
private val useVirtualColumnFamilies = stateFormatVersion >= 3
+ // Only the V4 state manager reads these ordinals. They depend only on plan
fields, so
+ // doExecute computes them once on the driver instead of in every task.
+ private lazy val stateKeyOrdinalsForLookup: (Option[Int], Option[Int]) =
+ if (stateFormatVersion >= 4) {
+ (getStateKeyOrdinalForLookup(
+ left.output, leftKeys, right.output, rightKeys,
stateWatermarkPredicates.left),
+ getStateKeyOrdinalForLookup(
+ right.output, rightKeys, left.output, leftKeys,
stateWatermarkPredicates.right))
+ } else {
+ (None, None)
+ }
+
+ /**
+ * The window of the other side's state that a row of `joinSide` reads in
V4, or None to read
+ * every row for the key. V4 orders a side's state by a timestamp, unless
the side has a key
+ * ordinal (see getStateKeyOrdinalForLookup), whose lookups read the key's
exact timestamp.
+ * That timestamp is the column the side's value-eviction predicate
constrains, or its event
+ * time if it has no such predicate. The window bounds that column with the
join condition
+ * evaluated on the row; see [[MatchingScanWindow]]. For rightTime BETWEEN
leftTime AND expiry,
+ * the left side evicts on expiry: a left row reads right rows with
rightTime in
+ * [leftTime, expiry], and a right row reads left rows with expiry at or
above rightTime.
+ */
+ private[sql] def matchingScanWindow(joinSide: JoinSide):
Option[MatchingScanWindow] = {
+ val (inputAttributes, otherAttributes, otherKeyOrdinal, otherPredicate,
otherMixed) =
+ joinSide match {
+ case LeftSide => (left.output, right.output,
stateKeyOrdinalsForLookup._2,
+ stateWatermarkPredicates.right, mixedStateOrderings._2)
+ case RightSide => (right.output, left.output,
stateKeyOrdinalsForLookup._1,
+ stateWatermarkPredicates.left, mixedStateOrderings._1)
+ }
+ // Rows that an earlier run stored under another ordering lie outside the
window.
+ if (stateFormatVersion < 4 || otherKeyOrdinal.isDefined || otherMixed) {
+ None
+ } else {
+
SymmetricHashJoinStateManager.valueTimestampColumnOrdinal(otherAttributes,
+ stateValueWatermarkColumnOrdinal(otherPredicate,
otherAttributes)).flatMap { ordinal =>
+ MatchingScanWindow(condition.full, inputAttributes,
otherAttributes(ordinal))
+ }
+ }
+ }
+
+ /**
+ * How V4 orders a side's state under the current plan: by the timestamp of
an equality key at
+ * an ordinal, by that of a value column at an ordinal, or by none. The
checkpoint keeps each
+ * stored row under the ordering of the run that stored it.
+ */
+ private def v4StateOrdering(side: JoinSide, predicates:
JoinStateWatermarkPredicates): String = {
+ val (attributes, keys, otherAttributes, otherKeys, predicate) = side match
{
+ case LeftSide => (left.output, leftKeys, right.output, rightKeys,
predicates.left)
+ case RightSide => (right.output, rightKeys, left.output, leftKeys,
predicates.right)
+ }
+ getStateKeyOrdinalForLookup(attributes, keys, otherAttributes, otherKeys,
predicate)
+ .map(ordinal => s"key:$ordinal").getOrElse {
+ SymmetricHashJoinStateManager.valueTimestampColumnOrdinal(attributes,
+ stateValueWatermarkColumnOrdinal(predicate, attributes)).map {
ordinal =>
+ s"value:$ordinal:${attributes(ordinal).dataType.catalogString}"
+ }.getOrElse("none")
+ }
+ }
+
+ // The operator metadata is written while planning the first batch of a run,
before the
+ // eviction watermark and predicates are set, so this derives the predicates
as that batch
+ // would. Which columns they constrain does not depend on the watermark's
value.
+ private lazy val v4StateOrderings: Option[(String, String)] =
+ if (stateFormatVersion >= 4) {
+ val predicates = if (eventTimeWatermarkForEviction.isDefined) {
+ stateWatermarkPredicates
+ } else {
+ getStateWatermarkPredicates(left.output, right.output, leftKeys,
rightKeys,
+ condition.full, Some(0L), None, useFirstEventTimeColumn =
!allowMultipleStatefulOperators)
+ }
+ Some((v4StateOrdering(LeftSide, predicates), v4StateOrdering(RightSide,
predicates)))
+ } else {
+ None
+ }
+
+ /**
+ * Whether each side's V4 state may hold rows stored under another ordering
than the current
+ * plan's, as the operator metadata of an earlier batch records: a run
recorded another
+ * ordering, or recorded such rows. A probe then reads every row of that
side for its key, as
+ * before scan windows. The flag stays for the life of the checkpoint. A
checkpoint without the
+ * record, from an earlier version, counts as ordered by the current plan.
+ */
+ private[sql] lazy val mixedStateOrderings: (Boolean, Boolean) =
+ (v4StateOrderings, previousJoinProperties.flatMap(p =>
+ p.stateOrderings.map(_ -> p.mixedOrderings))) match {
+ case (Some((left, right)), Some(((previousLeft, previousRight),
(leftMixed, rightMixed)))) =>
+ (leftMixed || previousLeft != left, rightMixed || previousRight !=
right)
+ case _ => (false, false)
+ }
+
+ // The join properties recorded at or before the previous batch: by the
first batch of this
+ // run, or by an earlier run when this is the first batch.
+ private lazy val previousJoinProperties:
Option[StreamingJoinOperatorProperties] =
+ stateInfo.filter(info => useVirtualColumnFamilies && info.storeVersion >
0).flatMap { info =>
Review Comment:
**Non-blocking (P2):** `doExecute` forces `mixedStateOrderings` on every
micro-batch's newly planned join (line 495), and the tuple on lines 324-325
evaluates `previousJoinProperties` before it checks `v4StateOrderings`. This
gate admits state format 3 as well as 4, so every batch after batch 0 of either
format builds an `OperatorStateMetadataV2Reader` on the driver before the
batch's job is submitted. That reader checks and lists the offset log, logs
'Skipping metadata directory creation' at INFO, checks and lists the metadata
directory, and opens and parses the latest file: about six checkpoint
file-system calls per join and batch, which can add tens to hundreds of
milliseconds per batch on object stores. In state format 3 the result is always
discarded. In state format 4, every batch after a run's first re-reads the
record that the first batch wrote, which cannot change within the run, since
only that batch writes it. The base branch's join reads no operator metadata
while runn
ing.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60379#discussion_r4582134210).
**Recommended change:** Stop re-reading the join's operator metadata in
every batch. Read the previous ordering record only when v4StateOrderings is
defined, that is, for state format 4, so state formats 1 to 3 never read it.
For state format 4, keep the flags that planning the run's first batch computes
for the record and hand them to that batch's executed join and to the joins of
the run's later batches, through the per-run planning state that already
carries the state schema broadcast, so that doExecute no longer reads the
checkpoint. A join that receives no flags reads the record as it does now.
**Why this works:** The flags depend only on the previous run's record and
the current plan, and the plan's orderings do not change within a run, so the
value computed while planning the run's first batch, which is also written into
the run's record, is what every later re-read of that record returns. Handing
that value on removes the per-batch existence checks, listings, open and parse
on the driver, and the INFO line, without changing any window.
**Compatibility:** Which side gets a window stays as it is now in every
batch and run: a side whose ordering changed, or that the previous record
flags, gets none, and a restart with the same ordering keeps both windows.
**Risks:** The flags move from a checkpoint read into state handed between
planning steps. A join that receives no flags must read the record as it does
now rather than assume that neither side holds rows of another ordering;
otherwise a missed hand-off would let probes skip stored rows that match.
Rolling the change back is safe: without the hand-off, each batch's join reads
the record as it does now.
**Constraints:** The flags that a batch uses must be the ones computed for
the run's record, from the previous run's record and the current plan. A side
that the previous record flags, or whose ordering changed, must stay without a
window in every batch of the run, the first included.
**Exclusions:**
- What a failed read of the record means: this change decides only how often
the record is read, and making a failed read fail the batch is a separate fix.
**Verification:**
- **Regression:** Over several batches of a state format 3 join and of a
state format 4 join, observe the driver's reads of the join's operator
metadata, for example through the metadata reader's log output: state format 3
adds none to the validation reads of a restarted run's first batch, and state
format 4 reads its previous ordering record once per run, while planning the
first batch.
- **Behavior:** After a restart that changes how one side's state is
ordered, a probe into the reordered side has no window in the restarted run's
first batch and in a later batch of that run, and still has none in the next
run; after a restart with the same ordering, both sides keep their windows in
the first and a later batch.
--
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]