[SPARK-60644][SS] Dedup within watermark incremental cleanup #59762
Review summary
No defects found in this revision. The new tests cover the watermark choice for per-record cleanup and for the completion drain, the per-record removal budget, the expiry boundary, no-data batches, the legacy propagator, rollback and replay, restarts that toggle the factor, and Real-Time Mode, on HDFS and both RocksDB modes. Two design questions for the author follow.
Cross-cutting observations
Separation: The common origin and the verified safety argument are context only. Choosing a separate opt-in for this operator would not shorten eviction for users who opt in, and changing the drain watermark would not decouple the operators sharing the factor. Each question needs its own author decision at a different place in the code, and neither implies a defect or a blocking condition.
Findings
0 total: 0 P0, 0 P1, 0 P2, 0 P3.
No findings.
Decision challenges
Shared cleanup factor now also changes dropDuplicatesWithinWatermark output
spark.sql.streaming.statefulOperator.incrementalCleanupFactor is session-wide, and streaming aggregation and dropDuplicates already read it. For those two operators it is purely a performance setting: their state key contains the event time (or window), so a key removed early can only be matched later by a record the late filter drops anyway. With this PR the same knob also changes which outside-interval records dropDuplicatesWithinWatermark emits.
Concretely, take the sequence in the new test incremental cleanup can readmit a key outside the watermark delay: a@10 and clock@35, then advance@40, then a batch with late-events watermark 25 and eviction watermark 30.
a (expiry 20) is evicted at the end of the advance batch, so a@28 in the last batch is emitted in either arrival order.advance batch drains only to its late-events watermark, so a is still stored when the last batch starts. [a@28, probe@40] then suppresses a@28, while [probe@40, a@28] emits it.This stays within the documented dedup-within-delay contract, but the knob cannot be set per operator. A query that wants incremental cleanup for its aggregation cannot keep batch-end-only behavior for its within-watermark dedup. Also, 4.3.0 shipped this config with the doc promise that dropDuplicatesWithinWatermark always evicts at batch end, and the factor is not pinned in the offset log. So a job that already sets it for aggregation picks up the new behavior on upgrade, with no code change.
Is sharing the knob intended? If so, could the Real-Time Mode guide's "leave the cleanup factor at its default of 0" sentence also say that this turns off incremental cleanup for aggregation and dropDuplicates in the same session? The rewritten config doc already covers the rest. If not, would a separate opt-in for the within-watermark operator be better, so the existing knob keeps its 4.3 meaning? Either way, the late-events-watermark safety this PR adds stays in place.
Late-events-watermark drain keeps one extra batch of expiring state
With a positive factor, every removal in a batch stops at the late-events watermark, including the completion drain and no-data batches. The iterator is opened before any input (statefulOperators.scala 1445-1446) and reused for the drain (1487). Under the default propagator, the late-events watermark is the previous batch's eviction watermark (WatermarkPropagator.scala 306-312). So batch N removes exactly what master removed at the end of batch N-1, and every expiring entry stays one batch longer.
What each side does:
shouldRunAnotherBatch then returns false, so that band stays until new data arrives. The new no-data test pins this: b (expiry 25) survives eviction watermark 30. A later non-late b@31 is then suppressed at factor 1, but emitted at factor 0.The drain does not need the late-events watermark for safety. Once a partition's input is fully processed, the next batch's late-events watermark equals this batch's eviction watermark, which is the same reasoning as the comment at 1710-1713. Would you consider either of these cheaper options? Both keep the guarantee and add no extra scan.
dropDuplicates.Removing the whole band within the same batch would need a full batch-end pass, which is the cost incremental cleanup exists to avoid. If you prefer to keep the current behavior, could the config doc and the Real-Time Mode guide say that a positive factor applies the late-events watermark to every removal in the batch, including the batch-end remainder and no-data batches? Then readers know eviction lags one batch and state is larger than at factor 0.
<!-- SPARK_DEV_REVIEW_CODE {"findings":[],"head_sha":"d0571889d4eb98d8ae0b8d0b39c5675cbac953aa","verdict_sha256":"296137adf7f2b649eb75b0e4cbf6395f2e4e471c66a31c52e259e61b314eb2a9"} -->
@jerrypeng thanks, sorry I didn't know your pr was there and looks solid. One thing to add. In RocksDB (snapshot iterators), a key that is expired at iterator-open time can be refreshed by a non-late record earlier in the same batch. Without re-reading the current value before remove, the stale snapshot entry gets evicted and there could be a later incorrect duplicate.
With #59953 I have a test that fails without the re-read. Could we adopt the re-read and ideally the logical-expiry check here, or see if the shared path already handles it? Maybe we can add an extra test?
@shenavaa
Thanks for calling this out. I agree the re-read is necessary with logical-expiry semantics: an expired-but-physically-present key can be refreshed before the RocksDB snapshot iterator reaches it, so deleting based solely on the snapshot value could remove the replacement.
In https://github.com/apache/spark/pull/59762’s current implementation, we check store.keyExists(key) before cleanup and insert only if that check returns false. An expired entry that is still physically present therefore suppresses the incoming record rather than being refreshed. A replacement can be inserted only after cleanup has removed the old entry, at which point its snapshot entry has already been consumed. That prevents this particular stale-snapshot deletion scenario without a re-read.
If we adopt the logical-expiry check, I agree that current-value revalidation and your regression test should come with it. Independently, an ordered-key RocksDB regression covering removal followed by same-batch reinsertion would be useful coverage for the current approach too. Thanks for adding the concrete test—it helps clarify the invariant each approach relies on.
cloud-fan
jerrypeng
What changes were proposed in this pull request?
Enable incremental state cleanup for
dropDuplicatesWithinWatermarkthrough the existingspark.sql.streaming.statefulOperator.incrementalCleanupFactorconfiguration.k, remove up tokeligible state entries per non-late input record, then drain the remaining eligible entries at batch completion.No new configuration, dependency, or state schema is introduced.
Why are the changes needed?
dropDuplicatesWithinWatermarkcurrently ignores the incremental-cleanup factor and performs all state eviction at batch completion. This leaves it unable to distribute removals across record processing, including during long-running Real-Time Mode batches.Enabling cleanup also requires choosing the correct watermark. The batch-end eviction watermark can be ahead of the watermark used to reject late input. Using that newer watermark during record processing could remove an entry before processing a non-late duplicate that should still be suppressed.
The late-events watermark prevents this: an entry is removed only after any subsequently accepted record with that key would fall outside the guaranteed watermark-delay interval.
The cleanup factor bounds the number of removals per record, not the number of state entries scanned or worst-case processing latency.
Does this PR introduce _any_ user-facing change?
Yes.
Previously,
dropDuplicatesWithinWatermarkalways evicted state at batch completion, even when the incremental-cleanup factor was positive. It now honors that setting.The default remains
0, preserving the existing batch-end-only behavior.With a positive factor:
Checkpoint key/value schemas are unchanged. Enabling and disabling cleanup across restarts does not require a state migration.
How was this patch tested?
Added regression coverage for:
0,1,2, and10.Local validation passed 164 distinct tests:
The two focused RTM cases additionally passed three consecutive runs at the final commit. SQL production/test and catalyst scalastyle checks passed.
Equivalent suite commands:
No performance benchmark was run; this PR makes no quantified throughput or latency claim.
Was this patch authored or co-authored using generative AI tooling?
Generated-by: Codex CLI 0.163.0