This is an automated email from the ASF dual-hosted git repository.

HeartSaVioR pushed a commit to branch branch-4.x
in repository https://gitbox.apache.org/repos/asf/spark.git


The following commit(s) were added to refs/heads/branch-4.x by this push:
     new e0dd0c27be2c [SPARK-60644][SS] Dedup within watermark incremental 
cleanup
e0dd0c27be2c is described below

commit e0dd0c27be2c9d959f15c12da713e20b9d5c7cf4
Author: Boyang Jerry Peng <[email protected]>
AuthorDate: Thu Nov 12 21:48:27 2026 +0900

    [SPARK-60644][SS] Dedup within watermark incremental cleanup
    
    ### What changes were proposed in this pull request?
    
    Enable incremental state cleanup for `dropDuplicatesWithinWatermark` in 
Real-Time Mode (RTM), using the existing 
`spark.sql.streaming.statefulOperator.incrementalCleanupFactor` configuration.
    
    - Pass the execution mode into the operator. In micro-batch mode, keep 
batch-end-only cleanup even when a positive shared factor is configured for 
another operator.
    - Default the shared factor to `2` in RTM only when it is not explicitly 
configured. Honor explicit `0` and positive values; keep the global 
configuration default at `0`.
    - With a positive factor `k` in RTM, remove up to `k` eligible state 
entries per non-late input record, then drain the remaining eligible entries at 
batch completion.
    - Use one eviction iterator and the late-events watermark for all 
incremental cleanup, including the completion-time drain and no-data batches. 
When incremental cleanup is disabled, retain batch-end cleanup using the 
eviction watermark.
    - Reuse the shared deduplication cleanup loop, metrics, and state-store 
commit/abort handling.
    - Document the shared-setting scope, output and state-retention tradeoffs, 
and restart behavior. Add regression coverage for RTM and micro-batch 
compatibility.
    
    No new configuration key, dependency, or checkpoint key/value schema is 
introduced.
    
    ### Why are the changes needed?
    
    `dropDuplicatesWithinWatermark` currently ignores the incremental-cleanup 
factor and performs state eviction at batch completion. Long-running RTM 
batches therefore cannot distribute this operator's removal work across record 
processing.
    
    Incremental cleanup also needs the correct watermark. The batch-end 
eviction watermark can be ahead of the watermark used to reject late input. 
Using that newer watermark during input processing could remove an entry before 
a non-late duplicate that should still be suppressed arrives.
    
    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 removals per record, not the number of state 
entries scanned or worst-case processing latency. This change does not 
introduce a separate batch-end scan with a newer cutoff.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes, in RTM.
    
    #### Micro-batch compatibility
    
    `dropDuplicatesWithinWatermark` continues to clean up only at batch end, 
including when an existing query sets a positive shared factor for aggregation 
or regular `dropDuplicates`. Those other operators keep their existing 
micro-batch behavior.
    
    #### RTM defaults and shared-setting scope
    
    RTM defaults the factor to `2` unless it is explicitly configured. An 
explicit `0` selects batch-end-only cleanup; an explicit positive value is 
honored. The global configuration default remains `0`.
    
    The setting remains shared across the supported operators in the query. 
Setting it to `0` also disables incremental cleanup for aggregation and regular 
`dropDuplicates` that use the same setting; it is not an operator-specific 
opt-out.
    
    With a positive factor for within-watermark deduplication:
    
    - 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.
    - All cleanup uses the late-events watermark, including the batch-end drain 
and empty/all-late-input batches. With the default watermark propagator, that 
watermark can trail the eviction watermark by one batch. Entries whose 
expiration falls between the two watermarks remain longer than with factor `0`, 
which can increase state-store and checkpoint size.
    - RTM can schedule subsequent batches without new input, so retained 
entries can be reclaimed once the cleanup watermark catches up. Idle time alone 
does not advance event-time watermarks or expire all state.
    
    #### Checkpoints and restarts
    
    Checkpoint key/value schemas are unchanged; enabling or disabling cleanup 
does not require a state migration. The factor is not pinned in the 
checkpoint's offset log, so changing it across restarts can change the cleanup 
policy and outside-delay output behavior. Restarting in micro-batch mode 
retains batch-end-only within-watermark cleanup regardless of the shared factor.
    
    ### How was this patch tested?
    
    Regression coverage added or updated includes:
    
    - Micro-batch compatibility with shared factors `0`, `1`, `2`, and `10`, 
including zero incremental removals and unchanged outside-delay output in both 
arrival orders.
    - RTM's default factor and explicit overrides, including explicit `0`.
    - Distinct late-events and eviction watermarks, expiry-boundary equality, 
and the legacy watermark propagator.
    - Per-record removal budgets and completion-time remainder cleanup in RTM.
    - Both arrival orders for the outside-delay RTM case, asserting their 
different expected outputs.
    - Empty and all-late input, including state retained between the two 
watermarks.
    - Checkpoint reopening after deletion and same-key reinsertion, and RocksDB 
coverage.
    - Failure after incremental mutations but before commit, followed by 
checkpoint recovery.
    - Enabling/disabling cleanup and switching between RTM and micro-batch mode 
across checkpoint restarts.
    - Plan canonicalization and RTM execution over pipelined shuffle.
    
    The current source and test assertions were checked during the response 
review. That review did not rerun builds or tests; the previous revision's test 
counts and final-commit pass claims are not presented as validation of this 
head.
    
    Relevant validation commands (not rerun as part of this description update):
    
    ```sh
    build/sbt \
      'sql/testOnly *StreamingDeduplicationWithinWatermarkSuite' \
      'sql/testOnly *StreamingDeduplicationWithinWatermarkRealTimeSuite' \
      'sql/testOnly *StreamingDeduplicationSuite' \
      'sql/testOnly *StreamRealTimeModeDefaultConfsSuite' \
      'sql/testOnly 
org.apache.spark.sql.streaming.StreamRealTimeModeWithManualClockSuite -- -z 
"dedup within watermark"' \
      sql/scalastyle \
      sql/Test/scalastyle \
      catalyst/scalastyle
    ```
    
    The following-empty-RTM-batch catch-up behavior described above is 
supported by scheduler and watermark-propagation source analysis; a dedicated 
end-to-end test of that complete sequence remains a follow-up. No performance 
benchmark was run, and 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
    
    Closes #59762 from jerrypeng/dedup-within-watermark-incremental-cleanup.
    
    Authored-by: Boyang Jerry Peng <[email protected]>
    Signed-off-by: Jungtaek Lim <[email protected]>
    
    (cherry picked from commit b636b18452f4246dde40fabb650144c2e0f58bf2)
    Signed-off-by: Jungtaek Lim <[email protected]>
    
    
    skip-checks: true
---
 docs/streaming/real-time-mode.md                   |  27 +-
 .../org/apache/spark/sql/internal/SQLConf.scala    |  10 +-
 .../operators/stateful/statefulOperators.scala     |  40 ++-
 .../streaming/runtime/IncrementalExecution.scala   |   5 +-
 .../streaming/runtime/StreamExecution.scala        |  11 +-
 .../StreamRealTimeModeDefaultConfsSuite.scala      |  21 ++
 .../sql/streaming/StreamRealTimeModeSuite.scala    |  61 +++-
 ...DeduplicationWithinWatermarkRealTimeSuite.scala | 331 +++++++++++++++++
 ...treamingDeduplicationWithinWatermarkSuite.scala | 390 ++++++++++++++++++---
 9 files changed, 814 insertions(+), 82 deletions(-)

diff --git a/docs/streaming/real-time-mode.md b/docs/streaming/real-time-mode.md
index b4c45ee00f27..0f8daadcdfbe 100644
--- a/docs/streaming/real-time-mode.md
+++ b/docs/streaming/real-time-mode.md
@@ -701,10 +701,29 @@ spark
 
 </div>
 
-Records that pass deduplication are emitted as they are processed, while 
watermark advancement and
-state eviction take effect at Real-time Mode batch boundaries. The trigger 
duration therefore
-determines how often cleanup has an opportunity to remove state after the 
watermark advances past a
-key's expiry.
+Records that pass deduplication are emitted as they are processed. Watermarks 
advance at Real-time
+Mode batch boundaries. Real-time Mode defaults
+`spark.sql.streaming.statefulOperator.incrementalCleanupFactor` to `2` unless 
it is explicitly set.
+A positive value spreads eviction across input-record processing, removing up 
to that many eligible
+state entries per input record, with any remaining eligible state removed at 
batch end. Set it to
+`0` to use batch-end-only cleanup.
+
+For `dropDuplicatesWithinWatermark`, a positive factor uses the late-events 
watermark for all cleanup,
+including the batch-end drain and no-data batches. With the default watermark 
propagator, this
+watermark can trail the batch-end eviction watermark by one batch. Entries 
whose expiration
+timestamps fall between these watermarks remain longer than with factor `0`, 
which can increase
+state-store and checkpoint size. If the stream becomes idle and no further 
batch is scheduled,
+these entries can remain until execution resumes. The trigger duration still 
determines when more
+state becomes eligible for removal.
+
+Incremental cleanup preserves duplicate suppression within the guaranteed 
watermark-delay interval.
+For records with the same key outside that interval, whether the old entry 
still suppresses a record
+can depend on cleanup progress and state-store iteration order. Set the 
cleanup factor to `0` to
+retain the batch-end-only behavior. This setting also controls incremental 
cleanup for streamline
+aggregation and regular `dropDuplicates` in the query. It is not pinned in the 
checkpoint's offset
+log, so a restart can change the cleanup policy without migrating state. In 
micro-batch mode,
+`dropDuplicatesWithinWatermark` always retains batch-end-only cleanup, even 
when a positive shared
+factor is configured for another operator; those other operators keep their 
existing behavior.
 
 ### Streaming aggregation
 
diff --git 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala
index e66632eda226..3459c5290b66 100644
--- a/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala
+++ b/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala
@@ -4173,8 +4173,14 @@ object SQLConf {
         "eviction happens at batch end. When k, up to k eligible records are 
removed per input; " +
         "any still-eligible records left over are removed at batch end. Only 
applies to modes " +
         "that evict (e.g. Append/Update); has no effect in Complete mode, 
which never evicts. " +
-        "Read by the streamline aggregation and streaming deduplication 
(dropDuplicates) " +
-        "operators; dropDuplicatesWithinWatermark always evicts at batch end.")
+        "Read by the streamline aggregation and streaming deduplication 
operators. Real-Time " +
+        "Mode defaults this setting to 2 when it is not explicitly set. For " +
+        "dropDuplicatesWithinWatermark, incremental cleanup only applies in 
Real-Time Mode; " +
+        "micro-batch queries always evict at batch end, even with a positive 
factor. When " +
+        "enabled for this operator, all cleanup uses the late-events 
watermark, including " +
+        "the batch-end drain and no-data batches. This can retain more state 
than a value of 0. " +
+        "Cleanup progress may change which records outside the guaranteed 
watermark-delay " +
+        "interval are emitted.")
       .version("4.3.0")
       .withBindingPolicy(ConfigBindingPolicy.NOT_APPLICABLE)
       .longConf
diff --git 
a/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/statefulOperators.scala
 
b/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/statefulOperators.scala
index 26389bb57477..971cfe4fd572 100644
--- 
a/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/statefulOperators.scala
+++ 
b/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/operators/stateful/statefulOperators.scala
@@ -1659,25 +1659,21 @@ case class StreamingDeduplicateWithinWatermarkExec(
     child: SparkPlan,
     stateInfo: Option[StatefulOperatorStateInfo] = None,
     eventTimeWatermarkForLateEvents: Option[Long] = None,
-    eventTimeWatermarkForEviction: Option[Long] = None)
+    eventTimeWatermarkForEviction: Option[Long] = None,
+    isRealTimeMode: Boolean = false)
   extends BaseStreamingDeduplicateExec {
 
+  // Mid-batch eviction can change output outside the guaranteed 
watermark-delay interval. Keep
+  // existing micro-batch behavior even when the shared factor is set for 
another operator; only
+  // real-time mode trades that behavior for spreading cleanup across its 
long-running batches.
+  override protected val incrementalCleanupFactor: Long =
+    if (isRealTimeMode) 
conf.getConf(SQLConf.STREAMING_STATE_INCREMENTAL_CLEANUP_FACTOR) else 0L
+
   protected val schemaForValueRow: StructType = StructType(
     Array(StructField("expiresAtMicros", LongType, nullable = false)))
 
   protected val extraOptionOnStateStore: Map[String, String] = Map.empty
 
-  // Incremental cleanup is deliberately NOT enabled for 
dropDuplicatesWithinWatermark. Its dedup
-  // key is only the user's columns; the expiry (`expiresAtMicros`) lives in 
the value row and is
-  // decoupled from a record's event time. So two records that share a dedup 
key can have different
-  // event times, and one can be non-late while the other's stored entry has 
already expired.
-  // Evicting that entry mid-batch (as incremental cleanup would) makes a 
later non-late record with
-  // the same key miss the existing entry and be emitted as new -- an output 
that depends on the
-  // cleanup factor and store iteration order. Evicting only at batch end (the 
inherited factor-0
-  // path) keeps the entry visible to every record in the batch, so the output 
is deterministic.
-  // (StreamingDeduplicateExec is immune because its key includes the event 
time: any record sharing
-  // an evictable key is itself late and is dropped by the late-events filter 
first.)
-
   // Below three variables are defined as lazy, as evaluating these variables 
does not work with
   // canonicalized plan. Specifically, attributes in child won't have an event 
time column in
   // the canonicalized plan. These variables are NOT referenced in 
canonicalized plan, hence
@@ -1715,17 +1711,23 @@ case class StreamingDeduplicateWithinWatermarkExec(
     val numRemovedStateRows = longMetric("numRemovedStateRows")
     val numRowsReadDuringEviction = longMetric("numRowsReadDuringEviction")
 
-    // Incremental cleanup is not enabled for this operator (this class does 
not override the base
-    // incrementalCleanupFactor, which defaults to 0 -- see the class-level 
comment for why), so
-    // eviction always runs once at batch end against the eviction watermark.
-    val watermarkForEviction = 
DateTimeUtils.millisToMicros(eventTimeWatermarkForEviction.get)
+    // Incremental cleanup must use the late-events watermark: a non-late 
duplicate can still be
+    // below the newer eviction watermark. Removing its entry too early could 
admit a duplicate
+    // within the watermark-delay interval. At batch end, with incremental 
cleanup disabled, all
+    // input has been processed and the eviction watermark is safe.
+    val incrementalAwareEvictionWatermark = if (doIncrementalCleanup) {
+      eventTimeWatermarkForLateEvents
+    } else {
+      eventTimeWatermarkForEviction
+    }
+    val watermarkForEviction = 
DateTimeUtils.millisToMicros(incrementalAwareEvictionWatermark.get)
 
     // We cannot reuse `EvictionIterator` here because it reads the eviction 
timestamp from the
     // state store key, whereas this operator stores `expiresAtMicros` in the 
value row (the key is
     // only the dedup key columns). Like EvictionIterator, this returns only 
the rows that are
-    // actually evicted, so numRemovedStateRows counts removals rather than 
state rows scanned.
-    // Unlike EvictionIterator, a row is removed in hasNext (via filter); that 
is safe here because
-    // without incremental cleanup the caller always drains the iterator.
+    // actually evicted, so the removal metrics count removals rather than 
state rows scanned.
+    // A row is removed in hasNext (via filter), so callers must check their 
removal budget before
+    // probing hasNext.
     store.iterator().filter { rowPair =>
       numRowsReadDuringEviction += 1
       val expiresAt = rowPair.value.getLong(0)
diff --git 
a/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala
 
b/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala
index 6edf78ac9016..a649a7e7d638 100644
--- 
a/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala
+++ 
b/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/IncrementalExecution.scala
@@ -412,13 +412,14 @@ class IncrementalExecution(
           eventTimeWatermarkForLateEvents = None,
           eventTimeWatermarkForEviction = None)
 
-      case StreamingDeduplicateWithinWatermarkExec(keys, child, None, None, 
None) =>
+      case StreamingDeduplicateWithinWatermarkExec(keys, child, None, None, 
None, _) =>
         StreamingDeduplicateWithinWatermarkExec(
           keys,
           child,
           Some(nextStatefulOperationStateInfo()),
           eventTimeWatermarkForLateEvents = None,
-          eventTimeWatermarkForEviction = None)
+          eventTimeWatermarkForEviction = None,
+          isRealTimeMode = isRealTimeMode)
 
       case m: FlatMapGroupsWithStateExec =>
         // We set this to true only for the first batch of the streaming query.
diff --git 
a/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamExecution.scala
 
b/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamExecution.scala
index 019d29232627..6139d33135ae 100644
--- 
a/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamExecution.scala
+++ 
b/sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamExecution.scala
@@ -489,9 +489,7 @@ abstract class StreamExecution(
    *
    * Every default applied here is logged, so those changes are recoverable 
from the driver log.
    *
-   * Deliberately not set, though Databricks Runtime does default them for 
Real-Time Mode:
-   *  - The incremental state-cleanup factor: that mechanism does not exist in 
OSS yet.
-   *  - The Python/Pandas UDF latency knobs: those configs do not exist in OSS.
+   * The Python/Pandas UDF latency knobs defaulted by Databricks Runtime do 
not exist in OSS.
    */
   private def setSparkSessionConfigsForRealTimeMode(sparkSessionForStream: 
SparkSession): Unit = {
     val conf = sparkSessionForStream.conf
@@ -532,6 +530,13 @@ abstract class StreamExecution(
       conf.set(changelogKey, "true")
     }
 
+    // Spread eviction across the long-running batch to reduce cleanup latency 
at batch boundaries.
+    val incrementalCleanupConf = 
SQLConf.STREAMING_STATE_INCREMENTAL_CLEANUP_FACTOR
+    if (!conf.contains(incrementalCleanupConf.key)) {
+      logInfo(log"Setting incremental cleanup factor to 2 for real-time mode")
+      conf.set(incrementalCleanupConf, 2L)
+    }
+
     // SOFT DEFAULT. `repartition(n)` uses RoundRobinPartitioning, and by 
default (SPARK-23207)
     // Spark inserts a local sort before a round-robin shuffle so the 
row-to-partition assignment is
     // deterministic -- otherwise a retried task could emit rows in a 
different order and lose data.
diff --git 
a/sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamRealTimeModeDefaultConfsSuite.scala
 
b/sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamRealTimeModeDefaultConfsSuite.scala
index 65fb2c09a53b..794952fbf009 100644
--- 
a/sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamRealTimeModeDefaultConfsSuite.scala
+++ 
b/sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamRealTimeModeDefaultConfsSuite.scala
@@ -62,6 +62,27 @@ class StreamRealTimeModeDefaultConfsSuite extends 
StreamRealTimeModeSuiteBase {
     observed
   }
 
+  test("Real-Time Mode defaults incremental cleanup to 2 only in the query 
session") {
+    val key = SQLConf.STREAMING_STATE_INCREMENTAL_CLEANUP_FACTOR.key
+    val original = spark.conf.getOption(key)
+    val explicitlySet = spark.conf.contains(key)
+    val observed = runRealTimeQueryAndReadConfs(Seq(key))
+
+    assert(observed(key).contains("2"))
+    assert(spark.conf.getOption(key) === original)
+    assert(spark.conf.contains(key) === explicitlySet)
+  }
+
+  gridTest("Real-Time Mode honors an explicit incremental cleanup 
factor")(Seq(0L, 1L, 5L)) {
+    factor =>
+      val key = SQLConf.STREAMING_STATE_INCREMENTAL_CLEANUP_FACTOR.key
+      withSQLConf(key -> factor.toString) {
+        val observed = runRealTimeQueryAndReadConfs(Seq(key))
+        assert(observed(key).contains(factor.toString))
+        assert(spark.conf.get(key) === factor.toString)
+      }
+  }
+
   test("a Real-Time Mode query defaults to checkpoint format v2 with the 
RocksDB state store") {
     val keys = Seq(
       SQLConf.STATE_STORE_CHECKPOINT_FORMAT_VERSION.key,
diff --git 
a/sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamRealTimeModeSuite.scala
 
b/sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamRealTimeModeSuite.scala
index e8f2c96090f0..20bf264d1950 100644
--- 
a/sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamRealTimeModeSuite.scala
+++ 
b/sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamRealTimeModeSuite.scala
@@ -602,7 +602,7 @@ class StreamRealTimeModeWithManualClockSuite extends 
StreamRealTimeModeManualClo
     }
   }
 
-  test("pipelined shuffle: dedup within watermark runs in Real-Time Mode") {
+  test("pipelined shuffle: dedup within watermark supports batch-end-only 
cleanup") {
     val inputData = LowLatencyMemoryStream.singlePartition[(String, Int)]
     val result = inputData.toDF()
       .withColumn("eventTime", timestamp_seconds($"_2"))
@@ -615,7 +615,8 @@ class StreamRealTimeModeWithManualClockSuite extends 
StreamRealTimeModeManualClo
       // watermark to 20 seconds after that batch completes.
       AddData(inputData,
         ("expired", 1), ("dup", 15), ("dup", 16), ("high", 30)),
-      StartStream(),
+      StartStream(additionalConfs = Map(
+        SQLConf.STREAMING_STATE_INCREMENTAL_CLEANUP_FACTOR.key -> "0")),
       CheckAnswerWithTimeout(60000, "expired", "dup", "high"),
       Execute { q =>
         val plan = q.lastExecution.executedPlan
@@ -648,6 +649,62 @@ class StreamRealTimeModeWithManualClockSuite extends 
StreamRealTimeModeManualClo
     )
   }
 
+  test("pipelined shuffle: dedup within watermark supports incremental 
cleanup") {
+    withSQLConf(
+      SQLConf.STREAMING_STATE_INCREMENTAL_CLEANUP_FACTOR.key -> "1",
+      SQLConf.STATE_STORE_PROVIDER_CLASS.key -> 
classOf[RocksDBStateStoreProvider].getName,
+      SQLConf.SHUFFLE_PARTITIONS.key -> "1") {
+      val inputData = LowLatencyMemoryStream.singlePartition[(String, Int)]
+      val result = inputData.toDF()
+        .withColumn("eventTime", timestamp_seconds($"_2"))
+        .withWatermark("eventTime", "10 seconds")
+        .dropDuplicatesWithinWatermark("_1")
+        .select($"_1")
+
+      testStream(result, OutputMode.Update, Map.empty, new 
ContinuousMemorySink())(
+        AddData(inputData,
+          ("expired", 1), ("expired2", 2), ("expired3", 3), ("a", 15), 
("clock", 30)),
+        StartStream(),
+        CheckAnswerWithTimeout(60000, "expired", "expired2", "expired3", "a", 
"clock"),
+        advanceRealTimeClock,
+        WaitUntilBatchProcessed(0),
+
+        AddData(inputData, ("advance", 40)),
+        CheckAnswerWithTimeout(60000, "expired", "expired2", "expired3", "a", 
"clock", "advance"),
+        advanceRealTimeClock,
+        WaitUntilBatchProcessed(1),
+        Execute { q =>
+          // Cleanup uses the late-events watermark (0), not the eviction 
watermark (20).
+          val operator = q.lastProgress.stateOperators.head
+          assert(operator.numRowsTotal === 6)
+          assert(operator.numRowsRemoved === 0)
+        },
+
+        // At the 20-second late-events watermark, three entries expire but 
"a" (expiry 25)
+        // must stay: its non-late duplicate at 24 is within 10 seconds of its 
first event.
+        // Two surviving inputs remove two entries incrementally; completion 
must remove the last.
+        // The emitted "probe" comes last so seeing it confirms the whole 
input was consumed.
+        AddData(inputData, ("a", 24), ("a", 20), ("probe", 40)),
+        CheckAnswerWithTimeout(
+          60000, "expired", "expired2", "expired3", "a", "clock", "advance", 
"probe"),
+        advanceRealTimeClock,
+        WaitUntilBatchProcessed(2),
+        CheckAnswerWithTimeout(
+          60000, "expired", "expired2", "expired3", "a", "clock", "advance", 
"probe"),
+        Execute { q =>
+          assertAllExchangesPipelined(q)
+          val operator = q.lastProgress.stateOperators.head
+          assert(operator.numRowsTotal === 4)
+          assert(operator.numRowsUpdated === 1)
+          assert(operator.numRowsDroppedByWatermark === 1)
+          assert(operator.numRowsRemoved === 3)
+          
assert(operator.customMetrics.get("numRowsIncrementallyRemoved").longValue() 
=== 2)
+        },
+        StopStream
+      )
+    }
+  }
+
   test("pipelined shuffle: multi-key dedup runs in Real-Time Mode over a 
pipelined shuffle") {
     // dropDuplicates on more than one column: the hash-partitioning is by the 
composite key.
     // Confirms the pipelined path is not specific to a single dedup column.
diff --git 
a/sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingDeduplicationWithinWatermarkRealTimeSuite.scala
 
b/sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingDeduplicationWithinWatermarkRealTimeSuite.scala
new file mode 100644
index 000000000000..28426c2f0656
--- /dev/null
+++ 
b/sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingDeduplicationWithinWatermarkRealTimeSuite.scala
@@ -0,0 +1,331 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.streaming
+
+import org.apache.spark.SparkException
+import org.apache.spark.sql.{DataFrame, Dataset}
+import 
org.apache.spark.sql.execution.streaming.operators.stateful.StreamingDeduplicateWithinWatermarkExec
+import org.apache.spark.sql.execution.streaming.sources.{ContinuousMemorySink, 
LowLatencyMemoryStream}
+import org.apache.spark.sql.execution.streaming.state.RocksDBStateStoreProvider
+import org.apache.spark.sql.functions.{timestamp_seconds, udf}
+import org.apache.spark.sql.internal.SQLConf
+
+object StreamingDeduplicationWithinWatermarkRealTimeSuite {
+  @volatile var failAfterCleanup = false
+  @volatile var lateRowRead = false
+}
+
+class StreamingDeduplicationWithinWatermarkRealTimeSuite
+  extends StreamRealTimeModeManualClockSuiteBase {
+
+  import testImplicits._
+
+  private val factorKey = 
SQLConf.STREAMING_STATE_INCREMENTAL_CLEANUP_FACTOR.key
+
+  private def deduplicate(input: Dataset[(String, Int)]): DataFrame = {
+    input.toDF()
+      .withColumn("eventTime", timestamp_seconds($"_2"))
+      .withWatermark("eventTime", "10 seconds")
+      .dropDuplicatesWithinWatermark("_1")
+      .select($"_1")
+  }
+
+  private def checkRemovalMetrics(total: Long, removed: Long, incremental: 
Long): AssertOnQuery = {
+    Execute { q =>
+      val operator = q.lastProgress.stateOperators.head
+      assert(operator.numRowsTotal === total)
+      assert(operator.numRowsRemoved === removed)
+      
assert(operator.customMetrics.get("numRowsIncrementallyRemoved").longValue() 
=== incremental)
+      
assert(operator.customMetrics.get("numRowsReadDuringEviction").longValue() >= 
removed)
+    }
+  }
+
+  private def checkExecutionMode(realTimeMode: Boolean): AssertOnQuery = {
+    Execute { q =>
+      val operators = q.lastExecution.executedPlan.collect {
+        case d: StreamingDeduplicateWithinWatermarkExec => d
+      }
+      assert(operators.nonEmpty && operators.forall(_.isRealTimeMode == 
realTimeMode))
+    }
+  }
+
+  gridTest("incremental cleanup drains remaining expired state with default 
and explicit factors")(
+      Seq(None, Some(1L), Some(2L), Some(10L))) { factor =>
+    withSQLConf((Seq(SQLConf.SHUFFLE_PARTITIONS.key -> "1") ++
+        factor.map(value => factorKey -> value.toString)): _*) {
+      val inputData = LowLatencyMemoryStream.singlePartition[(String, Int)]
+      val result = deduplicate(inputData.toDS())
+
+      testStream(result, OutputMode.Update, Map.empty, new 
ContinuousMemorySink())(
+        AddData(inputData, ("a", 1), ("b", 10), ("c", 21), ("d", 30), ("e", 
42)),
+        StartStream(),
+        CheckAnswerWithTimeout(60000, "a", "b", "c", "d", "e"),
+        advanceRealTimeClock,
+        WaitUntilBatchProcessed(0),
+
+        AddData(inputData, ("g", 51)),
+        CheckAnswerWithTimeout(60000, "a", "b", "c", "d", "e", "g"),
+        advanceRealTimeClock,
+        WaitUntilBatchProcessed(1),
+        checkRemovalMetrics(total = 6, removed = 0, incremental = 0),
+
+        // Three entries expire at the late-events watermark of 32. A single 
input removes up
+        // to the factor incrementally; completion drains the rest of the same 
iterator.
+        AddData(inputData, ("h", 51)),
+        CheckAnswerWithTimeout(60000, "a", "b", "c", "d", "e", "g", "h"),
+        advanceRealTimeClock,
+        WaitUntilBatchProcessed(2),
+        checkRemovalMetrics(total = 4, removed = 3, incremental = 
factor.getOrElse(2L).min(3L)),
+        checkExecutionMode(realTimeMode = true),
+        Execute { q =>
+          assert(q.sparkSessionForStream.conf.get(factorKey) === 
factor.getOrElse(2L).toString)
+        },
+        StopStream
+      )
+    }
+  }
+
+  gridTest("completion drains at the late-events watermark without surviving 
input")(
+      Seq(false, true)) { onlyLateInput =>
+    withSQLConf(factorKey -> "1", SQLConf.SHUFFLE_PARTITIONS.key -> "1") {
+      val inputData = LowLatencyMemoryStream.singlePartition[(String, Int)]
+      StreamingDeduplicationWithinWatermarkRealTimeSuite.lateRowRead = false
+      val result = deduplicate(inputData.toDS().map { row =>
+        if (row._1 == "late") {
+          StreamingDeduplicationWithinWatermarkRealTimeSuite.lateRowRead = true
+        }
+        row
+      })
+      val lastInput = if (onlyLateInput) Seq("late" -> 20) else 
Seq.empty[(String, Int)]
+
+      try {
+        testStream(result, OutputMode.Update, Map.empty, new 
ContinuousMemorySink())(
+          AddData(inputData, ("a", 10), ("b", 15), ("clock", 30)),
+          StartStream(),
+          CheckAnswerWithTimeout(60000, "a", "b", "clock"),
+          advanceRealTimeClock,
+          WaitUntilBatchProcessed(0),
+          AddData(inputData, ("advance", 40)),
+          CheckAnswerWithTimeout(60000, "a", "b", "clock", "advance"),
+          advanceRealTimeClock,
+          WaitUntilBatchProcessed(1),
+          checkRemovalMetrics(total = 4, removed = 0, incremental = 0),
+
+          AddData(inputData, lastInput: _*),
+          Execute { q =>
+            eventually {
+              assert(q.lastExecution.currentBatchId === 2)
+            }
+            waitForTasksToStart(2)
+            // A task-start event does not prove the reader consumed the late 
row before its
+            // deadline. Acknowledge that read without adding a surviving 
sentinel record.
+            if (onlyLateInput) {
+              eventually {
+                
assert(StreamingDeduplicationWithinWatermarkRealTimeSuite.lateRowRead)
+              }
+            }
+          },
+          advanceRealTimeClock,
+          WaitUntilBatchProcessed(2),
+          // At late watermark 20, only "a" (expiry 20) is eligible. "b" 
(expiry 25) survives,
+          // even though the newer batch-end eviction watermark is 30.
+          checkRemovalMetrics(total = 3, removed = 1, incremental = 0),
+          Execute { q =>
+            assert(q.lastProgress.numInputRows === (if (onlyLateInput) 1L else 
0L))
+            
assert(q.lastProgress.stateOperators.head.numRowsDroppedByWatermark ===
+              (if (onlyLateInput) 1L else 0L))
+          },
+          CheckAnswerWithTimeout(60000, "a", "b", "clock", "advance"),
+          StopStream
+        )
+      } finally {
+        StreamingDeduplicationWithinWatermarkRealTimeSuite.lateRowRead = false
+      }
+    }
+  }
+
+  gridTest("incremental cleanup can readmit a key outside the watermark 
delay")(
+      Seq(false, true)) { duplicateFirst =>
+    withSQLConf(factorKey -> "1", SQLConf.SHUFFLE_PARTITIONS.key -> "1") {
+      val inputData = LowLatencyMemoryStream.singlePartition[(String, Int)]
+      val result = deduplicate(inputData.toDS())
+      val rows = if (duplicateFirst) Seq("a" -> 28, "probe" -> 40)
+        else Seq("probe" -> 40, "a" -> 28)
+      val expected = Seq("a", "clock", "advance", "probe") ++
+        (if (duplicateFirst) Seq.empty else Seq("a"))
+
+      testStream(result, OutputMode.Update, Map.empty, new 
ContinuousMemorySink())(
+        AddData(inputData, ("a", 10), ("clock", 35)),
+        StartStream(),
+        CheckAnswerWithTimeout(60000, "a", "clock"),
+        advanceRealTimeClock,
+        WaitUntilBatchProcessed(0),
+        AddData(inputData, ("advance", 40)),
+        CheckAnswerWithTimeout(60000, "a", "clock", "advance"),
+        advanceRealTimeClock,
+        WaitUntilBatchProcessed(1),
+
+        // The lookup precedes cleanup. If "a" arrives first, it is suppressed 
and its old
+        // entry removed; otherwise cleanup on "probe" removes it before the 
next lookup.
+        // The 18-second timestamp spread is outside the guaranteed 10-second 
interval.
+        AddData(inputData, rows: _*),
+        CheckAnswerWithTimeout(60000, expected: _*),
+        advanceRealTimeClock,
+        WaitUntilBatchProcessed(2),
+        checkRemovalMetrics(total = if (duplicateFirst) 3 else 4, removed = 1, 
incremental = 1),
+        StopStream
+      )
+    }
+  }
+
+  test("cleanup can be enabled and disabled across checkpoint restarts") {
+    withSQLConf(factorKey -> "0", SQLConf.SHUFFLE_PARTITIONS.key -> "1") {
+      withTempDir { checkpoint =>
+        val inputData = LowLatencyMemoryStream.singlePartition[(String, Int)]
+        val result = deduplicate(inputData.toDS())
+
+        testStream(result, OutputMode.Update, Map.empty, new 
ContinuousMemorySink())(
+          AddData(inputData, ("a", 15), ("clock", 30)),
+          StartStream(checkpointLocation = checkpoint.getAbsolutePath),
+          CheckAnswerWithTimeout(60000, "a", "clock"),
+          advanceRealTimeClock,
+          WaitUntilBatchProcessed(0),
+          AddData(inputData, ("advance", 40)),
+          CheckAnswerWithTimeout(60000, "a", "clock", "advance"),
+          advanceRealTimeClock,
+          WaitUntilBatchProcessed(1),
+          StopStream
+        )
+
+        testStream(result, OutputMode.Update, Map.empty, new 
ContinuousMemorySink())(
+          StartStream(checkpointLocation = checkpoint.getAbsolutePath,
+            additionalConfs = Map(factorKey -> "1")),
+          AddData(inputData, ("probe", 40)),
+          CheckAnswerWithTimeout(60000, "probe"),
+          advanceRealTimeClock,
+          WaitUntilBatchProcessed(2),
+          checkRemovalMetrics(total = 4, removed = 0, incremental = 0),
+          StopStream
+        )
+
+        testStream(result, OutputMode.Update, Map.empty, new 
ContinuousMemorySink())(
+          StartStream(checkpointLocation = checkpoint.getAbsolutePath),
+          AddData(inputData, ("tick", 50)),
+          CheckAnswerWithTimeout(60000, "tick"),
+          advanceRealTimeClock,
+          WaitUntilBatchProcessed(3),
+          checkRemovalMetrics(total = 4, removed = 1, incremental = 0),
+          StopStream
+        )
+      }
+    }
+  }
+
+  test("cleanup follows the trigger when restarting the same checkpoint in MBM 
and RTM") {
+    withSQLConf(
+        factorKey -> "1",
+        SQLConf.SHUFFLE_PARTITIONS.key -> "1",
+        SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> "false",
+        SQLConf.STATE_STORE_CHECKPOINT_FORMAT_VERSION.key -> "2",
+        SQLConf.STATE_STORE_PROVIDER_CLASS.key -> 
classOf[RocksDBStateStoreProvider].getName) {
+      val inputData = LowLatencyMemoryStream.singlePartition[(String, Int)]
+      val result = deduplicate(inputData.toDS())
+
+      testStream(result, OutputMode.Update, Map.empty, new 
ContinuousMemorySink())(
+        AddData(inputData, ("a", 1), ("b", 15), ("clock", 30)),
+        StartStream(Trigger.ProcessingTime(0)),
+        CheckAnswer("a", "b", "clock"),
+        checkExecutionMode(realTimeMode = false),
+        checkRemovalMetrics(total = 3, removed = 0, incremental = 0),
+        StopStream,
+
+        AddData(inputData, ("advance", 40)),
+        StartStream(defaultTrigger),
+        CheckAnswerWithTimeout(60000, "a", "b", "clock", "advance"),
+        advanceRealTimeClock,
+        WaitUntilBatchProcessed(1),
+        AddData(inputData, ("g", 40)),
+        CheckAnswerWithTimeout(60000, "a", "b", "clock", "advance", "g"),
+        advanceRealTimeClock,
+        WaitUntilBatchProcessed(2),
+        checkExecutionMode(realTimeMode = true),
+        // The late-events watermark is 20, so "a" (expiry 11) is removed but 
"b" survives.
+        checkRemovalMetrics(total = 4, removed = 1, incremental = 1),
+        StopStream,
+
+        AddData(inputData, ("tick", 50)),
+        StartStream(Trigger.ProcessingTime(0)),
+        CheckAnswer("a", "b", "clock", "advance", "g", "tick"),
+        checkExecutionMode(realTimeMode = false),
+        // MBM removes "b" (expiry 25) at its eviction watermark of 30 after 
consuming input.
+        checkRemovalMetrics(total = 4, removed = 1, incremental = 0),
+        StopStream
+      )
+    }
+  }
+
+  test("an uncommitted batch rolls back incremental cleanup before checkpoint 
recovery") {
+    withSQLConf(factorKey -> "1", SQLConf.SHUFFLE_PARTITIONS.key -> "1") {
+      withTempDir { checkpoint =>
+        val inputData = LowLatencyMemoryStream.singlePartition[(String, Int)]
+        val failUDF = udf { key: String =>
+          if (key == "probe" &&
+              
StreamingDeduplicationWithinWatermarkRealTimeSuite.failAfterCleanup) {
+            throw new IllegalStateException("injected failure after 
incremental cleanup")
+          }
+          key
+        }
+        val result = 
deduplicate(inputData.toDS()).select(failUDF($"_1").as("key"))
+
+        try {
+          testStream(result, OutputMode.Update, Map.empty, new 
ContinuousMemorySink())(
+            AddData(inputData, ("expired", 1), ("a", 15), ("clock", 30)),
+            StartStream(checkpointLocation = checkpoint.getAbsolutePath),
+            CheckAnswerWithTimeout(60000, "expired", "a", "clock"),
+            advanceRealTimeClock,
+            WaitUntilBatchProcessed(0),
+            AddData(inputData, ("advance", 40)),
+            CheckAnswerWithTimeout(60000, "expired", "a", "clock", "advance"),
+            advanceRealTimeClock,
+            WaitUntilBatchProcessed(1),
+            Execute { _ =>
+              
StreamingDeduplicationWithinWatermarkRealTimeSuite.failAfterCleanup = true
+            },
+            AddData(inputData, ("probe", 40), ("a", 24)),
+            ExpectFailure[SparkException] { error =>
+              assert(error.getMessage.contains("injected failure after 
incremental cleanup"))
+            }
+          )
+
+          StreamingDeduplicationWithinWatermarkRealTimeSuite.failAfterCleanup 
= false
+          testStream(result, OutputMode.Update, Map.empty, new 
ContinuousMemorySink())(
+            StartStream(checkpointLocation = checkpoint.getAbsolutePath),
+            AddData(inputData, ("recovery", 50)),
+            CheckAnswerWithTimeout(60000, "probe", "recovery"),
+            advanceRealTimeClock,
+            WaitUntilBatchProcessed(2),
+            checkRemovalMetrics(total = 5, removed = 1, incremental = 1),
+            StopStream
+          )
+        } finally {
+          StreamingDeduplicationWithinWatermarkRealTimeSuite.failAfterCleanup 
= false
+        }
+      }
+    }
+  }
+}
diff --git 
a/sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingDeduplicationWithinWatermarkSuite.scala
 
b/sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingDeduplicationWithinWatermarkSuite.scala
index 8a9766c7e875..c73c885d3629 100644
--- 
a/sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingDeduplicationWithinWatermarkSuite.scala
+++ 
b/sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingDeduplicationWithinWatermarkSuite.scala
@@ -17,15 +17,21 @@
 
 package org.apache.spark.sql.streaming
 
-import org.apache.spark.sql.{AnalysisException, Dataset, SaveMode}
+import org.apache.spark.SparkException
+import org.apache.spark.sql.{AnalysisException, DataFrame, Dataset, SaveMode}
 import org.apache.spark.sql.catalyst.streaming.InternalOutputModes.Append
-import 
org.apache.spark.sql.execution.streaming.operators.stateful.StatefulOperatorsUtils
+import 
org.apache.spark.sql.execution.streaming.operators.stateful.{StatefulOperatorsUtils,
 StreamingDeduplicateWithinWatermarkExec}
 import org.apache.spark.sql.execution.streaming.runtime.MemoryStream
 import org.apache.spark.sql.functions.timestamp_seconds
 import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.streaming.util.StreamManualClock
 import org.apache.spark.sql.types.{LongType, StringType, StructType}
 import org.apache.spark.tags.SlowSQLTest
 
+object StreamingDeduplicationWithinWatermarkSuite {
+  @volatile var failBeforeCommit = false
+}
+
 @SlowSQLTest
 class StreamingDeduplicationWithinWatermarkSuite extends StateStoreMetricsTest
   with StreamingDeduplicationSuiteBase {
@@ -165,46 +171,323 @@ class StreamingDeduplicationWithinWatermarkSuite extends 
StateStoreMetricsTest
     )
   }
 
-  test("incremental cleanup factor does not change 
dropDuplicatesWithinWatermark output") {
-    // dropDuplicatesWithinWatermark deliberately does not participate in 
incremental cleanup
-    // (its dedup key excludes the event time, so mid-batch eviction of a 
shared key could change
-    // the output). Setting a non-zero incrementalCleanupFactor must therefore 
leave the output and
-    // per-batch state counts identical to the default -- this is the same 
sequence as
-    // "deduplicate with subset of columns which event time column is not in 
subset".
-    withSQLConf(SQLConf.STREAMING_STATE_INCREMENTAL_CLEANUP_FACTOR.key -> 
"10") {
-      val inputData = MemoryStream[(String, Int)]
-      val result = inputData.toDS()
-        .withColumn("eventTime", timestamp_seconds($"_2"))
-        .withWatermark("eventTime", "2 seconds")
-        .dropDuplicatesWithinWatermark("_1")
-        .select($"_1", $"eventTime".cast("long").as[Long])
+  private def deduplicateWithinWatermark(input: MemoryStream[(String, Int)]): 
DataFrame = {
+    input.toDS()
+      .withColumn("eventTime", timestamp_seconds($"_2"))
+      .withWatermark("eventTime", "10 seconds")
+      .dropDuplicatesWithinWatermark("_1")
+      .select($"_1", $"eventTime".cast("long").as[Long])
+  }
+
+  private def assertCleanupMetrics(
+      removed: Long,
+      incremental: Long,
+      scanned: Option[Long] = None): AssertOnQuery = {
+    AssertOnQuery(s"Check cleanup metrics: removed=$removed, 
incremental=$incremental") { q =>
+      val operator = q.lastProgress.stateOperators.head
+      assert(operator.numRowsRemoved === removed)
+      
assert(operator.customMetrics.get("numRowsIncrementallyRemoved").longValue() 
=== incremental)
+      val numScanned = 
operator.customMetrics.get("numRowsReadDuringEviction").longValue()
+      assert(numScanned >= removed)
+      scanned.foreach(expected => assert(numScanned === expected))
+      true
+    }
+  }
+
+  gridTest("micro-batch cleanup ignores the shared factor and protects 
within-window duplicates")(
+      Seq(0L, 1L, 2L, 10L)) { factor =>
+    withSQLConf(
+      SQLConf.STREAMING_STATE_INCREMENTAL_CLEANUP_FACTOR.key -> 
factor.toString,
+      SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> "false",
+      SQLConf.SHUFFLE_PARTITIONS.key -> "1") {
+      val inputData = MemoryStream[(String, Int)](1)
+      val result = deduplicateWithinWatermark(inputData)
 
       testStream(result, Append)(
-        AddData(inputData, "a" -> 17),
-        CheckNewAnswer("a" -> 17),
-        assertNumStateRows(total = 1, updated = 1),
+        AddData(inputData, "a" -> 15, "clock" -> 30),
+        CheckNewAnswer("a" -> 15, "clock" -> 30),
+        assertNumStateRows(total = 2, updated = 2),
 
-        AddData(inputData, "a" -> 16),
-        CheckNewAnswer(),
-        assertNumStateRows(total = 1, updated = 0),
+        AddData(inputData, "advance" -> 40),
+        CheckNewAnswer("advance" -> 40),
+        assertNumStateRows(total = 3, updated = 1),
+
+        // Late input is filtered at 20, but batch-end eviction can use 30. 
"a" expires at 25;
+        // evicting it incrementally at 30 would let the non-late duplicate at 
24 through.
+        AddData(inputData, "probe" -> 40, "a" -> 24, "a" -> 20),
+        CheckNewAnswer("probe" -> 40),
+        assertNumStateRows(total = 3, updated = 1, droppedByWatermark = 1),
+        assertCleanupMetrics(removed = 1, incremental = 0),
+        Execute { q =>
+          val operators = q.lastExecution.executedPlan.collect {
+            case d: StreamingDeduplicateWithinWatermarkExec => d
+          }
+          assert(operators.nonEmpty && operators.forall(!_.isRealTimeMode))
+          assert(q.sparkSessionForStream.conf.get(
+            SQLConf.STREAMING_STATE_INCREMENTAL_CLEANUP_FACTOR.key) === 
factor.toString)
+        }
+      )
+    }
+  }
+
+  gridTest("micro-batch cleanup retains batch-end eviction after checkpoint 
restart")(
+      Seq(1L, 2L, 10L)) { factor =>
+    withSQLConf(
+      SQLConf.STREAMING_STATE_INCREMENTAL_CLEANUP_FACTOR.key -> 
factor.toString,
+      SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> "false",
+      SQLConf.SHUFFLE_PARTITIONS.key -> "1") {
+      val inputData = MemoryStream[(String, Int)](1)
+      val result = deduplicateWithinWatermark(inputData)
 
-        AddData(inputData, "a" -> 13),
+      testStream(result, Append)(
+        AddData(inputData, "a" -> 1, "b" -> 10, "c" -> 21, "d" -> 30, "e" -> 
42),
+        CheckNewAnswer("a" -> 1, "b" -> 10, "c" -> 21, "d" -> 30, "e" -> 42),
+        assertNumStateRows(total = 5, updated = 5),
+
+        AddData(inputData, "g" -> 51),
+        CheckNewAnswer("g" -> 51),
+        assertNumStateRows(total = 3, updated = 1),
+        assertCleanupMetrics(removed = 3, incremental = 0),
+        StopStream,
+        StartStream(),
+
+        // The restored eviction watermark is 41. "d" (expiry 40) is removed 
at batch end,
+        // regardless of the positive shared cleanup factor.
+        AddData(inputData, "h" -> 51),
+        CheckNewAnswer("h" -> 51),
+        assertNumStateRows(total = 3, updated = 1),
+        assertCleanupMetrics(removed = 1, incremental = 0),
+        StopStream,
+        StartStream(),
+
+        // A removed key can be admitted again, but its next within-window 
duplicate is dropped.
+        AddData(inputData, "a" -> 52, "a" -> 53),
+        CheckNewAnswer("a" -> 52),
+        assertNumStateRows(total = 4, updated = 1),
+        assertCleanupMetrics(removed = 0, incremental = 0)
+      )
+    }
+  }
+
+  test("micro-batch cleanup uses the eviction watermark in a no-data batch") {
+    withSQLConf(
+      SQLConf.STREAMING_STATE_INCREMENTAL_CLEANUP_FACTOR.key -> "1",
+      SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> "true",
+      SQLConf.SHUFFLE_PARTITIONS.key -> "1") {
+      val inputData = MemoryStream[(String, Int)](1)
+      val result = deduplicateWithinWatermark(inputData)
+      val clock = new StreamManualClock
+
+      testStream(result, Append)(
+        AddData(inputData, "a" -> 10, "b" -> 15, "clock" -> 30),
+        StartStream(Trigger.ProcessingTime("1 second"), clock),
+        CheckNewAnswer("a" -> 10, "b" -> 15, "clock" -> 30),
+        WaitUntilBatchProcessed(0),
+        assertNumStateRows(total = 3, updated = 3),
+
+        AddData(inputData, "advance" -> 40),
+        AdvanceManualClock(1000L),
+        WaitUntilBatchProcessed(1),
+        CheckNewAnswer("advance" -> 40),
+        assertNumStateRows(total = 3, updated = 1),
+        assertCleanupMetrics(removed = 1, incremental = 0),
+
+        // The empty batch has late watermark 20 and eviction watermark 30. 
"a" was already
+        // removed at 20; "b" (expiry 25) is now removed using the newer 
eviction watermark.
+        AdvanceManualClock(1000L),
+        WaitUntilBatchProcessed(2),
         CheckNewAnswer(),
-        assertNumStateRows(total = 1, updated = 0, droppedByWatermark = 1),
+        Execute { q =>
+          assert(q.lastProgress.batchId === 2)
+          assert(q.lastProgress.numInputRows === 0)
+        },
+        assertNumStateRows(total = 2, updated = 0),
+        assertCleanupMetrics(removed = 1, incremental = 0, scanned = Some(3L))
+      )
+    }
+  }
+
+  test("micro-batch cleanup ignores a positive factor with the legacy 
watermark propagator") {
+    withSQLConf(
+      SQLConf.STREAMING_STATE_INCREMENTAL_CLEANUP_FACTOR.key -> "1",
+      SQLConf.STATEFUL_OPERATOR_ALLOW_MULTIPLE.key -> "false",
+      SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> "false",
+      SQLConf.SHUFFLE_PARTITIONS.key -> "1") {
+      val inputData = MemoryStream[(String, Int)](1)
+      val result = deduplicateWithinWatermark(inputData)
 
-        AddData(inputData, "b" -> 22, "c" -> 21),
-        CheckNewAnswer("b" -> 22, "c" -> 21),
+      testStream(result, Append)(
+        AddData(inputData, "a" -> 10, "clock" -> 30),
+        CheckNewAnswer("a" -> 10, "clock" -> 30),
         assertNumStateRows(total = 2, updated = 2),
 
-        // "a" -> 21 is emitted as new because the earlier "a" state expired 
and was evicted at the
-        // previous batch end -- unchanged from the factor-0 path.
-        AddData(inputData, "a" -> 21),
-        CheckNewAnswer("a" -> 21),
+        // Both watermark thresholds are 20 with the legacy propagator, so "a" 
can be evicted.
+        AddData(inputData, "advance" -> 40),
+        CheckNewAnswer("advance" -> 40),
+        assertNumStateRows(total = 2, updated = 1),
+        assertCleanupMetrics(removed = 1, incremental = 0),
+
+        AddData(inputData, "a" -> 31, "a" -> 32),
+        CheckNewAnswer("a" -> 31),
         assertNumStateRows(total = 3, updated = 1),
+        assertCleanupMetrics(removed = 0, incremental = 0)
+      )
+    }
+  }
 
-        AddData(inputData, "d" -> 25),
-        CheckNewAnswer("d" -> 25),
-        assertNumStateRows(total = 2, updated = 1)
+  test("micro-batch cleanup with a positive shared factor rolls back an 
uncommitted batch") {
+    withSQLConf(
+      SQLConf.STREAMING_STATE_INCREMENTAL_CLEANUP_FACTOR.key -> "1",
+      SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> "false",
+      SQLConf.SHUFFLE_PARTITIONS.key -> "1") {
+      val inputData = MemoryStream[(String, Int)](1)
+      val result = deduplicateWithinWatermark(inputData).as[(String, 
Long)].map { row =>
+        // Fail before batch-end eviction and commit to test replay with a 
positive shared factor.
+        if (row._1 == "probe" && 
StreamingDeduplicationWithinWatermarkSuite.failBeforeCommit) {
+          sys.error("injected failure before commit")
+        }
+        row
+      }
+
+      try {
+        testStream(result, Append)(
+          AddData(inputData, "expired" -> 1, "a" -> 15, "clock" -> 30),
+          CheckNewAnswer("expired" -> 1, "a" -> 15, "clock" -> 30),
+          assertNumStateRows(total = 3, updated = 3),
+          AddData(inputData, "advance" -> 40),
+          CheckNewAnswer("advance" -> 40),
+          assertNumStateRows(total = 3, updated = 1),
+
+          // "expired" was removed at batch end. "a" must survive until every 
non-late duplicate
+          // in the replayed batch is processed, then be removed at the 
eviction watermark of 30.
+          Execute { _ => 
StreamingDeduplicationWithinWatermarkSuite.failBeforeCommit = true },
+          AddData(inputData, "probe" -> 40, "a" -> 24),
+          ExpectFailure[SparkException] { error =>
+            assert(error.getMessage.contains("injected failure before commit"))
+          },
+          Execute { _ => 
StreamingDeduplicationWithinWatermarkSuite.failBeforeCommit = false },
+          StartStream(),
+          CheckNewAnswer("probe" -> 40),
+          assertNumStateRows(total = 3, updated = 1),
+          assertCleanupMetrics(removed = 1, incremental = 0)
+        )
+      } finally {
+        StreamingDeduplicationWithinWatermarkSuite.failBeforeCommit = false
+      }
+    }
+  }
+
+  gridTest("micro-batch cleanup expires entries at the eviction watermark 
boundary")(
+      Seq(false, true)) { onlyLateInput =>
+    withSQLConf(
+      SQLConf.STREAMING_STATE_INCREMENTAL_CLEANUP_FACTOR.key -> "1",
+      SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> "false",
+      SQLConf.SHUFFLE_PARTITIONS.key -> "1") {
+      val inputData = MemoryStream[(String, Int)](1)
+      val result = deduplicateWithinWatermark(inputData)
+      val lastInput = if (onlyLateInput) "a" -> 20 else "probe" -> 40
+      val lastAnswer = if (onlyLateInput) CheckNewAnswer() else 
CheckNewAnswer("probe" -> 40)
+
+      testStream(result, Append)(
+        AddData(inputData, "a" -> 10, "clock" -> 30),
+        CheckNewAnswer("a" -> 10, "clock" -> 30),
+        assertNumStateRows(total = 2, updated = 2),
+        AddData(inputData, "advance" -> 40),
+        CheckNewAnswer("advance" -> 40),
+        assertNumStateRows(total = 2, updated = 1),
+        assertCleanupMetrics(removed = 1, incremental = 0),
+
+        // "a" was removed at the eviction watermark of 20. The next batch 
must not count it
+        // again, whether its input is all late or contains a new key.
+        AddData(inputData, lastInput),
+        lastAnswer,
+        assertNumStateRows(
+          total = if (onlyLateInput) 2 else 3,
+          updated = if (onlyLateInput) 0 else 1,
+          droppedByWatermark = if (onlyLateInput) 1 else 0),
+        assertCleanupMetrics(
+          removed = 0,
+          incremental = 0,
+          scanned = if (onlyLateInput) Some(2L) else None)
+      )
+    }
+  }
+
+  test("micro-batch cleanup keeps its policy when the shared factor changes 
across restarts") {
+    val factorKey = SQLConf.STREAMING_STATE_INCREMENTAL_CLEANUP_FACTOR.key
+    withSQLConf(
+      factorKey -> "0",
+      SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> "false",
+      SQLConf.SHUFFLE_PARTITIONS.key -> "1") {
+      val inputData = MemoryStream[(String, Int)](1)
+      val result = deduplicateWithinWatermark(inputData)
+
+      testStream(result, Append)(
+        AddData(inputData, "a" -> 15, "clock" -> 30),
+        CheckNewAnswer("a" -> 15, "clock" -> 30),
+        assertNumStateRows(total = 2, updated = 2),
+        AddData(inputData, "advance" -> 40),
+        CheckNewAnswer("advance" -> 40),
+        assertNumStateRows(total = 3, updated = 1),
+        StopStream,
+
+        // Setting a positive factor must not change this operator's 
micro-batch policy.
+        // "a" (expiry 25) is removed at the eviction watermark of 30, at 
batch end.
+        StartStream(additionalConfs = Map(factorKey -> "1")),
+        AddData(inputData, "probe" -> 40),
+        CheckNewAnswer("probe" -> 40),
+        assertNumStateRows(total = 3, updated = 1),
+        assertCleanupMetrics(removed = 1, incremental = 0),
+        StopStream,
+
+        // Returning the factor to 0 reads the same checkpoint without a state 
migration.
+        StartStream(additionalConfs = Map(factorKey -> "0")),
+        AddData(inputData, "tick" -> 50),
+        CheckNewAnswer("tick" -> 50),
+        assertNumStateRows(total = 4, updated = 1),
+        assertCleanupMetrics(removed = 0, incremental = 0)
+      )
+    }
+  }
+
+  gridTest("micro-batch output outside the watermark delay does not depend on 
cleanup order")(
+      Seq(false, true)) { duplicateFirst =>
+    withSQLConf(
+      SQLConf.STREAMING_STATE_INCREMENTAL_CLEANUP_FACTOR.key -> "1",
+      SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key -> "false",
+      SQLConf.SHUFFLE_PARTITIONS.key -> "1") {
+      val inputData = MemoryStream[(String, Int)](1)
+      val result = deduplicateWithinWatermark(inputData)
+      val rows = if (duplicateFirst) {
+        Seq("a" -> 28, "probe" -> 40)
+      } else {
+        Seq("probe" -> 40, "a" -> 28)
+      }
+      val expected = rows
+
+      testStream(result, Append)(
+        AddData(inputData, "a" -> 10, "clock" -> 35),
+        CheckNewAnswer("a" -> 10, "clock" -> 35),
+        assertNumStateRows(total = 2, updated = 2),
+        AddData(inputData, "advance" -> 40),
+        CheckNewAnswer("advance" -> 40),
+        assertNumStateRows(total = 2, updated = 1),
+        assertCleanupMetrics(removed = 1, incremental = 0),
+
+        // The previous batch removed "a" at its eviction watermark of 25. 
Either input order
+        // admits the new "a", even though the shared cleanup factor is 
positive.
+        AddData(inputData, rows: _*),
+        CheckNewAnswer(expected.head, expected.tail: _*),
+        assertNumStateRows(total = 4, updated = 2),
+        assertCleanupMetrics(removed = 0, incremental = 0),
+        StopStream,
+        StartStream(),
+
+        // Reopening preserves the replacement entry in either input order.
+        AddData(inputData, "a" -> 31, "a" -> 32),
+        CheckNewAnswer(),
+        assertNumStateRows(total = 4, updated = 0),
+        assertCleanupMetrics(removed = 0, incremental = 0)
       )
     }
   }
@@ -248,24 +531,27 @@ class StreamingDeduplicationWithinWatermarkSuite extends 
StateStoreMetricsTest
     }
   }
 
-  test("SPARK-46676: canonicalization of 
StreamingDeduplicateWithinWatermarkExec should work") {
-    withTempDir { checkpoint =>
-      val dedupeInputData = MemoryStream[(String, Int)]
-      val dedupe = dedupeInputData.toDS()
-        .withColumn("eventTime", timestamp_seconds($"_2"))
-        .withWatermark("eventTime", "10 second")
-        .dropDuplicatesWithinWatermark("_1")
-        .select($"_1", $"eventTime".cast("long").as[Long])
-
-      testStream(dedupe, Append)(
-        StartStream(checkpointLocation = checkpoint.getCanonicalPath),
-        AddData(dedupeInputData, "a" -> 1),
-        CheckNewAnswer("a" -> 1),
-        Execute { q =>
-          // This threw out error before SPARK-46676.
-          q.lastExecution.executedPlan.canonicalized
-        }
-      )
+  gridTest("SPARK-46676: canonicalization of 
StreamingDeduplicateWithinWatermarkExec should work")(
+      Seq(0L, 1L)) { factor =>
+    withSQLConf(SQLConf.STREAMING_STATE_INCREMENTAL_CLEANUP_FACTOR.key -> 
factor.toString) {
+      withTempDir { checkpoint =>
+        val dedupeInputData = MemoryStream[(String, Int)]
+        val dedupe = dedupeInputData.toDS()
+          .withColumn("eventTime", timestamp_seconds($"_2"))
+          .withWatermark("eventTime", "10 second")
+          .dropDuplicatesWithinWatermark("_1")
+          .select($"_1", $"eventTime".cast("long").as[Long])
+
+        testStream(dedupe, Append)(
+          StartStream(checkpointLocation = checkpoint.getCanonicalPath),
+          AddData(dedupeInputData, "a" -> 1),
+          CheckNewAnswer("a" -> 1),
+          Execute { q =>
+            // This threw out error before SPARK-46676.
+            q.lastExecution.executedPlan.canonicalized
+          }
+        )
+      }
     }
   }
 
@@ -303,3 +589,7 @@ class StreamingDeduplicationWithinWatermarkSuite extends 
StateStoreMetricsTest
     )
   }
 }
+
+@SlowSQLTest
+class RocksDBStateStoreStreamingDeduplicationWithinWatermarkSuite
+  extends StreamingDeduplicationWithinWatermarkSuite with RocksDBStateStoreTest


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to