← Back to Pull requests

[SPARK-60644][SS] Dedup within watermark incremental cleanup #59762

Open
jerrypeng opened this pull request with 491 lines diff across 5 files
View on GitHub
jerrypeng jerrypeng commented on Oct 23, 2026 22:50 UTC
Author

What changes were proposed in this pull request?

Enable incremental state cleanup for dropDuplicatesWithinWatermark through the existing spark.sql.streaming.statefulOperator.incrementalCleanupFactor configuration.

  • With a positive factor k, remove up to k eligible state entries per non-late input record, then drain the remaining eligible entries at batch completion.

  • Use the late-events watermark for both incremental cleanup and the completion-time drain. Keep the existing eviction watermark when incremental cleanup is disabled.

  • Reuse the shared deduplication cleanup loop, iterator, metrics, and state-store commit/abort handling.

  • Update the configuration and Real-Time Mode documentation to explain the behavior and compatibility implications.

  • Add coverage for watermark safety, removal budgets, checkpoint recovery, failure/replay, and Real-Time Mode execution.
  • No new configuration, dependency, or state schema is introduced.

    Why are the changes needed?

    dropDuplicatesWithinWatermark currently 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, dropDuplicatesWithinWatermark always 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:

  • Duplicate suppression within the documented watermark-delay interval remains guaranteed.

  • Same-key records outside that interval may be emitted or suppressed depending on cleanup progress and state-store iteration order. Exact output equivalence with batch-end-only cleanup is not guaranteed.

  • Cleanup uses the late-events watermark, which can trail the batch-end eviction watermark by one batch, so some state can be retained longer.
  • 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:

  • Distinct late-events and eviction watermarks.

  • Cleanup factors 0, 1, 2, and 10.

  • Per-record removal budgets and completion-time remainder cleanup.

  • Expiry-boundary equality, all-late input, and no-data batches.

  • Checkpoint reopening after deletion and same-key reinsertion.

  • Failure after incremental mutations but before commit, followed by checkpoint replay.

  • Enabling and disabling cleanup across checkpoint restarts.

  • Legacy watermark propagation and plan canonicalization.

  • Real-Time Mode execution over pipelined shuffle.
  • Local validation passed 164 distinct tests:

  • 66 within-watermark cases across HDFS and RocksDB snapshot/changelog modes.

  • 96 existing regular-deduplication regression cases.

  • Two focused Real-Time Mode cases.
  • 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:

    build/sbt \
      'sql/testOnly *StreamingDeduplicationWithinWatermarkSuite' \
      'sql/testOnly *StreamingDeduplicationSuite' \
      'sql/testOnly org.apache.spark.sql.streaming.StreamRealTimeModeWithManualClockSuite -- -z "dedup within watermark"' \
      sql/scalastyle \
      sql/Test/scalastyle \
      catalyst/scalastyle
    

    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

    Diff: 491 lines (+418 / -73) across 5 files Reviewer: cloud-fan Review duration: 18315m
    All Vouch review confidence checks passed
    Residual risk 0.06 = Change Risk (0.46) × (1 − Review Confidence (0.88)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.46 · 491 lines diff across 5 files
    0.46
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.86 · 2 substantive comment(s)
    0.86
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    87%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.371
    Real PR Conversation Timeline
    4 items
    cloud-fan cloud-fan commented on Oct 28, 2026 23:24 UTC
    Reviewer

    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

  • Both open questions come from enabling dropDuplicatesWithinWatermark through the incremental-cleanup design that dropDuplicates and streaming aggregation already use: one session-wide factor and a single eviction pass bounded by the late-events watermark. The review found the core safety argument sound for every factor value and both watermark propagators, so a positive factor never admits a duplicate within the watermark delay. What remains is the trade-offs: this is the only operator for which the shared factor changes which records are emitted, and under the default propagator a positive factor delays eviction by one batch, which also leaves expired state behind after the final no-data batch on an idle stream.
  • 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.

  • In master (and at factor 0), 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.

  • At factor 1, the 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:

  • Master (the factor is ignored for this operator): every batch, no-data batches included, evicts up to the current eviction watermark at batch end.

  • This PR at factor > 0: removal work is spread across records, but committed state carries one extra batch band of expiring keys. With roughly uniform high-NDV arrival, the retained span grows from about 2D+B to about 2D+2B, where D is the delay and B the batch duration. That is about 1.2x for the guide's 10-minute delay with 5-minute Real-Time Mode batches, and about 1.9x for a 10-second delay. RocksDB memory, SST, and checkpoint size grow with it. Total removal work is unchanged, only shifted.

  • On an idle stream, the final no-data batch drains only to the late-events watermark, and 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.

  • When a partition admits no non-late input (no-data batches, all-late or empty partitions), drain with the eviction watermark, for example by creating the incremental iterator lazily on the first admitted row. This removes the idle-stream residual, and because the loop is shared it would also apply to dropDuplicates.

  • Evaluate the not-yet-scanned remainder of the drain against the eviction watermark. How much this helps depends on the workload; it does nothing when the iterator was already exhausted during record processing.
  • 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"} -->

    shenavaa shenavaa commented on Oct 30, 2026 22:09 UTC
    Contributor

    @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?

    jerrypeng jerrypeng commented on Oct 30, 2026 22:52 UTC
    Author

    @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.

    Reviewers
    Assignees
    jerrypeng jerrypeng
    Labels
    risk: low confidence: 88.0% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 45.9% (MEDIUM) · Higher = larger blast radius
    45.9%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 88.0% · Lower = rushed or shallow review
    88.0%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 5.5% · Safe to merge
    5.5%
    Repository