siying commented on PR #60068:
URL: https://github.com/apache/spark/pull/60068#issuecomment-6883601440
Code review on `cd678880ec7`:
Pivoting to a checkpoint-pinned version
(`spark.sql.streaming.join.eventTimeColumnRetentionVersion`) instead of a
post-hoc state projection is much cleaner and avoids fragile
logical-to-physical attribute rewriting. Pinning legacy checkpoints to version
`0` and propagating the setting into `StreamingV2ScanPushDown.startupConf` look
solid.
Here are the issues found in this pass:
---
### 1. [P0] `useEventTimeIndex` in `SymmetricHashJoinStateManagerV4` alters
primary-store timestamp keys and breaks compatible query restarts
**Locations:**
- `StreamingSymmetricHashJoinExec.scala` (lines 702–706)
- `SymmetricHashJoinStateManager.scala` (lines 266–302, 439–446, 560–565)
In `SymmetricHashJoinStateManagerV4`, `hasEventTime` does not only control
whether `tsWithKey` is populated — via `eventTimeColIdxOpt.filter(_ =>
hasEventTime)` and `joinKeyOrdinalForWatermark.filter(_ => hasEventTime)`, it
also controls the 8-byte `[timestamp]` suffix written into keys of the
**primary** `keyWithTsToValues` column family (`[key][timestamp] -> [(value,
matched), ...]`).
When `useRetainedEventTimeColumn` is `true` and a join side currently has
`stateWatermarkPredicate.isEmpty`, passing `useEventTimeIndex = Some(false)`
forces `hasEventTime = false` even though the event-time column is present in
`inputValueAttributes` and persisted in the state schema:
1. **Run 1:** A user runs `left.join(right, "key").select("key")` under V4
(`version = 1`), or the `SPARK-56406` shape (`left` has a watermark, `right`
does not yet define `.withWatermark`, `leftTime BETWEEN rightTime - 5s AND
rightTime + 5s`). Because `stateWatermarkPredicate` is `None`, buffered rows
are written to `keyWithTsToValues` with **random bucket timestamps in
`0..1023`** (`random.nextInt(1024)` microseconds), and `tsWithKey` is left
empty.
2. **Run 2 (compatible query restart):** The user adds
`.withWatermark("rightTime", ...)` on `right` or adds a time-interval bound `&&
leftTime BETWEEN rightTime - interval 5 seconds AND rightTime + interval 5
seconds` and restarts from the checkpoint. Because `(key, leftTime)` and `(key,
rightTime)` are already in the persisted state schema,
**`StateSchemaCompatibilityChecker` passes without error**.
3. **Silent data loss & state leak in Run 2:**
- `stateWatermarkPredicate` becomes
`Some(JoinStateValueWatermarkPredicate(...))`, flipping `isV4TimeIntervalJoin =
true` (`StreamingSymmetricHashJoinExec.scala:735`).
- Probes call `keyWithTsToValues.getValuesInRange(key, minTs, maxTs)` in
the real microsecond domain and **silently miss all Run 1 rows stored under
random buckets `0..1023`**.
- `evictByTimestamp` / `evictAndReturnByTimestamp` scans `tsWithKey`,
which has no entries for Run 1 rows — **permanently leaking pre-restart state**
and, for outer joins, **never emitting unmatched NULL-padded rows** for Run 1
records.
- Downgrading the `SPARK-56406` query (`new -> old`, where state schemas
match because `leftTime` is referenced in the join condition) hits the same
mismatch because old Spark sets `hasEventTime = true` whenever
`eventTimeColIdxOpt.isDefined`.
- Minor asymmetry: `getJoinedRowsAndRemoveMatched`
(`SymmetricHashJoinStateManager.scala:563`) still calls `tsWithKey.remove(key,
ts)` unconditionally when `!hasEventTime`, writing unnecessary RocksDB delete
tombstones for `LeftSemi` joins.
**Suggestion:** Drop the `useEventTimeIndex` override for V4 in this PR
(keeping `hasEventTime = eventTimeColIdxOpt.isDefined ||
joinKeyOrdinalForWatermark.isDefined`), or if skipping `tsWithKey` is pursued
under SPARK-56536, persist the index/key-timestamp mode in
`OperatorStateMetadataV2` (`StreamingJoinOperatorProperties`) so incompatible
restarts fail fast instead of silently corrupting probes/eviction.
---
### 2. [P1] `StreamMetadata` unconditionally overwrites `OffsetSeqMetadata`
and can wedge checkpoints after an aborted startup + rollback (`new -> old ->
new`)
**Locations:**
- `MicroBatchExecution.scala` (lines 208–233)
- `StreamingQueryCheckpointMetadata.scala` (lines 76–81)
- `StreamMetadata.scala` (lines 43–50)
1. **Overwrites `OffsetSeqMetadata` unconditionally:** `StreamMetadata`'s
Scaladoc states that `joinEventTimeColumnRetentionVersion` is used *"when the
latest offset does not contain the setting, including before the first offset
is written."* However, `metadata.conf.updated(key, retentionVersion.toString)`
overwrites `key` even when `metadata.conf` already contains `key`, and
`logicalPlan` (lines 230–232) sets `streamConf` solely from `streamMetadata`
instead of checking `initialLatestOffsetSeq` first. If `<checkpoint>/metadata`
lacks the field (`None`) while `offsets/N` recorded `"1"`, this silently flips
the query from `"1"` to `"0"`.
2. **Pre-batch-0 failure + rollback (`new -> old -> new`):**
`StreamExecution` initializes `checkpointMetadata.streamMetadata` eagerly in
its constructor (`StreamExecution.scala:172`), writing `<checkpoint>/metadata`
with `"joinEventTimeColumnRetentionVersion": 1` before `logicalPlan`, source
initialization, or Batch 0 execute. If startup fails before Batch 0 runs and
the user rolls back to Spark 4.3 on the same checkpoint path, Spark 4.3 ignores
the unknown field in `metadata`, sees empty `offsets/`/`commits/`/`state/`, and
commits batches `0..N` with the **legacy pruned state schema (`version = 0`)**
and `offsets/0..N` without `key` — while `<checkpoint>/metadata` still retains
`"joinEventTimeColumnRetentionVersion": 1`. On a subsequent upgrade back to
Spark 4.4, injecting `"1"` from `StreamMetadata` fails with
`STATE_STORE_INCOMPATIBLE_SCHEMA` and overrides even an explicit session-level
`spark.sql.streaming.join.eventTimeColumnRetentionVersion=0`.
**Suggestion:** Never overwrite `key` when `metadata.conf.contains(key)` is
already `true`. When `latestOffsets` lacks `key` and
`streamMetadata.joinEventTimeColumnRetentionVersion` is `Some(1)`, distinguish
the `strippedByOldBinary` case (where an old binary appended an uncommitted
`offsets/(k+1)` on top of a checkpoint whose last committed offset `offsets/k`
recorded `"1"`) from a checkpoint whose committed batches
(`commitLog.getLatest()`) were written by an old binary without `key` (which
has version-`0` state on disk and must default to `"0"`).
---
### 3. [P1] Logical vs. physical join count divergence after `ColumnPruning`
**Locations:**
- `Optimizer.scala` (lines 1520–1522)
- `IncrementalExecution.scala` (lines 725–732)
*(Already noted in the inline thread on `IncrementalExecution.scala` for
twice-referenced materialized CTEs via `ReplaceCTERefWithRepartition`.)* Adding
one related case: `PushDownJoinThroughUnion` (`Optimizer.scala:263`, when
`spark.sql.optimizer.pushDownJoinThroughUnion.enabled=true`) also runs after
the `Operator Optimization` `ColumnPruning` batch and can duplicate a join
across union branches. Recording the retention decision on the logical `Join`
(and forwarding it in `StreamingJoinStrategy` into
`StreamingSymmetricHashJoinExec`) handles both cases and avoids the extra
`plan.transform` pass right before `StateOpIdRule` in `IncrementalExecution`.
---
### 4. [P2] Unconditional `useRetainedEventTimeColumn = true` under version
`1` diverges from `UnsupportedOperationChecker` for outer/semi joins
**Locations:**
- `StreamingSymmetricHashJoinHelper.scala` (lines 193–202, 276–301)
- `UnsupportedOperationChecker.scala` (lines 708–735)
- `StreamingJoinSuite.scala` (lines 340–346, 1665–1696)
`UnsupportedOperationChecker.checkForStreamStreamJoinWatermark` validates
`LeftOuter`, `RightOuter`, `FullOuter`, and `LeftSemi` joins by calling
`StreamingJoinHelper.getStateValueWatermark(join.left.outputSet,
join.right.outputSet, ...)` across **all** input attributes. Under version `1`,
`useRetainedEventTimeColumn` is `true` for every single stream-stream join —
including unpruned `SELECT *` queries or when `ColumnPruning` is excluded.
Consequently, a `left_outer` join on `leftKey = rightKey AND leftJoinTime >
rightEventTime` (with watermark on `leftEventTime`, as in
`StreamingJoinSuite.scala:1665`) passes analysis, yet at runtime
`StreamingSymmetricHashJoinHelper` restricts
`attributesToFindStateWatermarkFor` to `AttributeSet(oneSideEventTime.toSeq)`
and yields `stateWatermarkPredicates.left = None`. Because
`StreamingSymmetricHashJoinExec` only emits unmatched `(leftRow, null)` rows
via `leftSideJoiner.removeAndReturnOldState()`, unmatched outer rows buffer
indefinitely without ever being emitted or rejected at analysis time.
Consider aligning `UnsupportedOperationChecker` under version `1` (or
scoping/documenting this behavior explicitly), and adding `(1, false, false,
true)` (`version = 1` with `excludeColumnPruning = true`) to the matrix in
`StreamingJoinSuite`.
---
### 5. [Low / Housekeeping] PR description, test names, and `EXPLAIN` output
1. **Stale PR description:** The GitHub PR description still describes the
earlier schema-preserving `Join`-annotation /
`*StreamingJoinColumnPruningSuite` design rather than the checkpoint-pinned
`eventTimeColumnRetentionVersion` implementation in `cd678880ec7`.
2. **Leftover `"POC"` wording in `ColumnPruningSuite.scala`:** Lines 593
(`"SPARK-60850: ambiguous event-time inputs are outside the retention POC"`)
and 608 (`"SPARK-60850: window-valued event time is outside the retention
POC"`).
3. **`EXPLAIN` output (`StreamingSymmetricHashJoinExec.scala:151`):** Adding
`useRetainedEventTimeColumn: Boolean = false` to the
`StreamingSymmetricHashJoinExec` case class without overriding `stringArgs`
appends `, false` / `, true` to `StreamingSymmetricHashJoin` in `EXPLAIN` plans
(compare `Deduplicate.stringArgs` in `basicLogicalOperators.scala:2467`).
---
<!-- GITHUB_MCP_FOOTER: This attribution is automatically appended by GitHub
MCP. -->
_This comment was generated with [GitHub MCP](http://go/mcps)._
--
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]