You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@kafka.apache.org by bb...@apache.org on 2026/09/08 17:27:02 UTC

(kafka) branch 4.3 updated (c18b27fd2c3 -> 4bbc64b3247)

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

bbejeck pushed a change to branch 4.3
in repository https://gitbox.apache.org/repos/asf/kafka.git


    from c18b27fd2c3 KAFKA-20393: Fix stickyNode using stale IP when broker address changes (#21983)
     new a61e8a9b927 KAFKA-13499: Avoid restoring outdated records (#22115)
     new fb7279ad34a KAFKA-20875: Headers window store adapters must expose the retention they wrap (#23037)
     new b3add398354 KAFKA-20876: Windowed restore optimisation gives up when `endOffset-1` is a transaction control record (#23086)
     new 4bbc64b3247 KAFKA-20940: Windowed changelog restore optimization is skipped whenever a checkpointed offset exists (#23285)

The 4 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 checkstyle/suppressions.xml                        |    2 +-
 .../processor/internals/ProcessorStateManager.java |   10 +
 .../processor/internals/StoreChangelogReader.java  |  384 ++++++-
 ...stractDualSchemaRocksDBSegmentedBytesStore.java |    7 +-
 .../AbstractRocksDBSegmentedBytesStore.java        |    7 +-
 .../state/internals/InMemorySessionStore.java      |    7 +-
 .../state/internals/InMemoryWindowStore.java       |    7 +-
 .../PlainToHeadersWindowStoreAdapter.java          |   13 +-
 .../internals/SessionToHeadersStoreAdapter.java    |    9 +-
 .../TimestampedToHeadersWindowStoreAdapter.java    |   13 +-
 .../WindowToTimestampedWindowByteStoreAdapter.java |    9 +-
 ...ValueIterator.java => WithRetentionPeriod.java} |   23 +-
 .../internals/StoreChangelogReaderTest.java        | 1173 ++++++++++++++++++++
 .../PlainToHeadersWindowStoreAdapterTest.java      |    8 +
 .../SessionToHeadersStoreAdapterTest.java          |   17 +
 ...TimestampedToHeadersWindowStoreAdapterTest.java |    8 +
 .../TimestampedWindowStoreBuilderTest.java         |   27 +
 .../state/internals/WithRetentionPeriodTest.java   |   88 ++
 18 files changed, 1776 insertions(+), 36 deletions(-)
 copy streams/src/main/java/org/apache/kafka/streams/state/internals/{ManagedKeyValueIterator.java => WithRetentionPeriod.java} (53%)
 create mode 100644 streams/src/test/java/org/apache/kafka/streams/state/internals/WithRetentionPeriodTest.java


(kafka) 04/04: KAFKA-20940: Windowed changelog restore optimization is skipped whenever a checkpointed offset exists (#23285)

Posted by bb...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

bbejeck pushed a commit to branch 4.3
in repository https://gitbox.apache.org/repos/asf/kafka.git

commit 4bbc64b3247c98c695894e884cbe1ead08a81546
Author: Alan Lau <72...@users.noreply.github.com>
AuthorDate: Mon Aug 31 09:55:15 2026 -0400

    KAFKA-20940: Windowed changelog restore optimization is skipped whenever a checkpointed offset exists (#23285)
    
    Jira: https://issues.apache.org/jira/browse/KAFKA-20940
    
    The windowed changelog restore optimization added in KAFKA-13499, which
    seeks past already-expired records instead of restoring them, only ran
    for partitions with no checkpointed offset; whenever a checkpoint
    existed the reader sought straight to it and restored every record after
    it, replaying a prefix of data that retention had already expired. This
    extends the optimization to checkpointed active windowed changelogs
    whose checkpoint is far enough behind the end offset to be worth it,
    running them through the same probe but floored at the checkpoint so
    restoration never rewinds past records that have already been applied.
    When the probe cannot place a partition, or the checkpoint sits below
    the log start or the log is empty, restore falls back to the checkpoint
    rather than the beginning and leaves the existing truncation and
    corruption handling unchanged.
    
    Reviewers: Bill Bejeck <bb...@apache.org>
---
 checkstyle/suppressions.xml                        |   2 +-
 .../processor/internals/StoreChangelogReader.java  | 140 ++++++-
 .../internals/StoreChangelogReaderTest.java        | 463 ++++++++++++++++++++-
 3 files changed, 576 insertions(+), 29 deletions(-)

diff --git a/checkstyle/suppressions.xml b/checkstyle/suppressions.xml
index f34ccd6c2d3..d26c0a7901e 100644
--- a/checkstyle/suppressions.xml
+++ b/checkstyle/suppressions.xml
@@ -214,7 +214,7 @@
               files="(KStreamKStreamJoinTest|KTableKTableForeignKeyJoinIntegrationTest|RocksDBGenericOptionsToDbOptionsColumnFamilyOptionsAdapterTest|RelationalSmokeTest|MockProcessorContextStateStoreTest|IQv2StoreIntegrationTest|StreamsConfigTest).java"/>
 
     <suppress checks="JavaNCSS"
-              files="(KStreamKStreamJoinTest|StreamTaskTest|StreamThreadTest|TaskManagerTest|TopologyTestDriverTest).java"/>
+              files="(KStreamKStreamJoinTest|StoreChangelogReaderTest|StreamTaskTest|StreamThreadTest|TaskManagerTest|TopologyTestDriverTest).java"/>
 
     <suppress checks="NPathComplexity"
               files="(KStreamKStreamJoinTest|KTableKTableForeignKeyJoinIntegrationTest|RelationalSmokeTest|MockProcessorContextStateStoreTest|TopologyTestDriverTest|IQv2StoreIntegrationTest).java"/>
diff --git a/streams/src/main/java/org/apache/kafka/streams/processor/internals/StoreChangelogReader.java b/streams/src/main/java/org/apache/kafka/streams/processor/internals/StoreChangelogReader.java
index 3c82dcc7259..6972758b9d5 100644
--- a/streams/src/main/java/org/apache/kafka/streams/processor/internals/StoreChangelogReader.java
+++ b/streams/src/main/java/org/apache/kafka/streams/processor/internals/StoreChangelogReader.java
@@ -228,6 +228,12 @@ public class StoreChangelogReader implements ChangelogReader {
     // probe that is working is never suppressed.
     private static final Duration PROBE_RETRY_BACKOFF = Duration.ofSeconds(60);
 
+    // Smallest stored-offset gap worth a probe: below it, replaying the gap costs about what the probe
+    // spends, and the probe pauses every restoring partition while it runs. Tied to the widest probe
+    // window so the relationship survives retuning.
+    // The 8x is a conservative margin over the probe's cost as measured in load testing.
+    private static final long PROBE_MIN_OFFSET_GAP = 8 * PROBE_WINDOWS[PROBE_WINDOWS.length - 1];
+
     private ChangelogReaderState state;
 
     // deliberately outlives unregister: a changelog that is corrupted and re-registered in a loop
@@ -764,7 +770,12 @@ public class StoreChangelogReader implements ChangelogReader {
                                            final long numRecords,
                                            final Long lastRestoredOffset, // this is not a "position" so we need to correct it below
                                            final long restoredToOffset) {
-        final long restoredFromOffset = lastRestoredOffset == null ? changelogMetadata.restoreStartOffset : lastRestoredOffset + 1;
+        // clamp to the position restoration started from: after skipping past a stored offset, the first
+        // batch's lastRestoredOffset is the stored offset, which is behind restoreStartOffset; measuring
+        // from the stored offset would decrement the remaining-records metric by the whole skipped gap
+        final long restoredFromOffset = lastRestoredOffset == null
+            ? changelogMetadata.restoreStartOffset
+            : Math.max(changelogMetadata.restoreStartOffset, lastRestoredOffset + 1);
         final long numOffsets = Math.max(restoredToOffset - restoredFromOffset, 0L);
         task.recordRestoration(time, numRecords, numOffsets, false);
     }
@@ -1025,9 +1036,11 @@ public class StoreChangelogReader implements ChangelogReader {
 
     private void prepareChangelogs(final Map<TaskId, Task> tasks,
                                    final Set<ChangelogMetadata> newPartitionsToRestore) {
-        // separate those who do not have the current offset loaded from checkpoint
+        // separate those who do not have the current offset loaded from the store
         final Set<TopicPartition> newSeekToBeginningPartitions = new HashSet<>();
         final Map<TopicPartition, Long> newWindowedPartitionsRetention = new HashMap<>();
+        // for a partition with a stored offset routed through the probe, the stored offset + 1 it may never seek below
+        final Map<TopicPartition, Long> newPartitionsFloor = new HashMap<>();
 
         for (final ChangelogMetadata changelogMetadata : newPartitionsToRestore) {
             final StateStoreMetadata storeMetadata = changelogMetadata.storeMetadata;
@@ -1036,13 +1049,23 @@ public class StoreChangelogReader implements ChangelogReader {
             final Long endOffset = changelogs.get(partition).restoreEndOffset;
 
             if (currentOffset != null) {
-                // the current offset is the offset of the last record, so we should set the position
-                // as that offset + 1 as the "next" record to fetch; seek is not a blocking call so
-                // there's nothing to capture
-                restoreConsumer.seek(partition, currentOffset + 1);
+                // the current offset is the offset of the last record, so the "next" record to fetch is
+                // that offset + 1; it is also the floor the probe may never seek below, since doing so
+                // would re-apply applied records and rewind the stored offset
+                final long floor = currentOffset + 1;
+                if (shouldProbePastStoredOffset(changelogMetadata, partition, floor, endOffset)) {
+                    newWindowedPartitionsRetention.put(partition, storeMetadata.retentionPeriod());
+                    newPartitionsFloor.put(partition, floor);
+
+                    log.debug("Start restoring windowed changelog partition {} by probing to skip expired data " +
+                        "past stored offset {} to end offset {}.", partition, currentOffset, recordEndOffset(endOffset));
+                } else {
+                    // seek is not a blocking call so there's nothing to capture
+                    restoreConsumer.seek(partition, floor);
 
-                log.debug("Start restoring changelog partition {} from current offset {} to end offset {}.",
-                    partition, currentOffset, recordEndOffset(endOffset));
+                    log.debug("Start restoring changelog partition {} from current offset {} to end offset {}.",
+                        partition, currentOffset, recordEndOffset(endOffset));
+                }
             } else {
                 final long retentionPeriod = storeMetadata.retentionPeriod();
                 if (retentionPeriod > 0 && retentionPeriod != Long.MAX_VALUE) {
@@ -1067,7 +1090,7 @@ public class StoreChangelogReader implements ChangelogReader {
             }
         }
 
-        seekNewPartitions(newWindowedPartitionsRetention, newSeekToBeginningPartitions);
+        seekNewPartitions(newWindowedPartitionsRetention, newSeekToBeginningPartitions, newPartitionsFloor);
 
         for (final ChangelogMetadata changelogMetadata : newPartitionsToRestore) {
             final StateStoreMetadata storeMetadata = changelogMetadata.storeMetadata;
@@ -1111,13 +1134,40 @@ public class StoreChangelogReader implements ChangelogReader {
         }
     }
 
+    /**
+     * Whether an active windowed changelog with a stored offset should probe to skip expired data instead
+     * of replaying from that offset; the guards below exclude standbys, stores without usable
+     * retention, backed-off partitions, and gaps too small to be worth a probe.
+     */
+    private boolean shouldProbePastStoredOffset(final ChangelogMetadata changelogMetadata,
+                                                final TopicPartition partition,
+                                                final long floor,
+                                                final Long endOffset) {
+        if (changelogMetadata.stateManager.taskType() != TaskType.ACTIVE) {
+            return false;
+        }
+        final long retentionPeriod = changelogMetadata.storeMetadata.retentionPeriod();
+        if (retentionPeriod <= 0 || retentionPeriod == Long.MAX_VALUE) {
+            return false;
+        }
+        if (!probeIsDue(partition)) {
+            return false;
+        }
+        return endOffset != null && endOffset - floor >= PROBE_MIN_OFFSET_GAP;
+    }
+
     private void seekNewPartitions(final Map<TopicPartition, Long> windowedPartitionsRetention,
-                                    final Set<TopicPartition> seekToBeginningPartitions) {
+                                    final Set<TopicPartition> seekToBeginningPartitions,
+                                    final Map<TopicPartition, Long> newPartitionsFloor) {
         // Seek non-windowed partitions to beginning.
         if (!seekToBeginningPartitions.isEmpty()) {
             restoreConsumer.seekToBeginning(seekToBeginningPartitions);
         }
 
+        // Partitions with a stored offset routed through the probe that fall back are sent to their floor
+        // (stored offset + 1), never to the beginning; collected here and seeked at the end.
+        final Set<TopicPartition> floorFallbackPartitions = new HashSet<>();
+
         // Try to optimize windowed partitions by seeking past expired data.
         if (!windowedPartitionsRetention.isEmpty()) {
             final Set<TopicPartition> allAssigned = restoreConsumer.assignment();
@@ -1132,6 +1182,24 @@ public class StoreChangelogReader implements ChangelogReader {
                 final Map<TopicPartition, Long> beginningOffsets =
                     restoreConsumer.beginningOffsets(windowedPartitionsRetention.keySet());
 
+                // A stored offset below the log start (truncated head) or on an empty/shrunk log cannot be
+                // certified by the skip. Seek it to its floor, pause it, and drop it from the probe, so
+                // the next restore poll -- not the probe's -- takes the InvalidOffsetException ->
+                // TaskCorrupted wipe path a plain seek(stored offset + 1) would; probe from scratch afterward.
+                final Set<TopicPartition> demotedToFloor = new HashSet<>();
+                for (final TopicPartition partition : windowedPartitionsRetention.keySet()) {
+                    final Long floor = newPartitionsFloor.get(partition);
+                    final Long endOffset = endOffsets.get(partition);
+                    if (floor != null &&
+                        (floor < beginningOffsets.getOrDefault(partition, 0L) || endOffset == null || endOffset <= 0)) {
+                        restoreConsumer.seek(partition, floor);
+                        restoreConsumer.pause(Collections.singleton(partition));
+                        demotedToFloor.add(partition);
+                    }
+                }
+                windowedPartitionsRetention.keySet().removeAll(demotedToFloor);
+
+                // partitions with no stored offset on an empty/unreadable log seek to the beginning
                 for (final TopicPartition partition : windowedPartitionsRetention.keySet()) {
                     final Long endOffset = endOffsets.get(partition);
                     if (endOffset == null || endOffset <= 0) {
@@ -1147,19 +1215,22 @@ public class StoreChangelogReader implements ChangelogReader {
                 final Set<TopicPartition> unresolved = new HashSet<>(windowedPartitionsRetention.keySet());
                 runBackwardProbe(unresolved, latestTimestamps, beginningOffsets, endOffsets);
 
-                seekByRetention(latestTimestamps, windowedPartitionsRetention, seekToBeginningPartitions);
+                seekByRetention(latestTimestamps, windowedPartitionsRetention, seekToBeginningPartitions,
+                    newPartitionsFloor, floorFallbackPartitions);
             } catch (final TimeoutException e) {
                 log.debug("Could not seek by timestamp for changelog partitions {}, falling back to seek-to-beginning",
                     windowedPartitionsRetention.keySet(), e);
-                seekToBeginningPartitions.addAll(windowedPartitionsRetention.keySet());
+                addProbeFallback(windowedPartitionsRetention.keySet(), newPartitionsFloor,
+                    seekToBeginningPartitions, floorFallbackPartitions);
             } catch (final KafkaException e) {
                 log.warn("Failed to seek by timestamp for changelog partitions {}, falling back to seek-to-beginning",
                     windowedPartitionsRetention.keySet(), e);
-                seekToBeginningPartitions.addAll(windowedPartitionsRetention.keySet());
+                addProbeFallback(windowedPartitionsRetention.keySet(), newPartitionsFloor,
+                    seekToBeginningPartitions, floorFallbackPartitions);
             } finally {
                 // in the finally, not after the probe: a lookup that times out leaves through a
                 // catch, and a probe that fails that way must arm the backoff like any other
-                recordProbeOutcomes(windowedPartitionsRetention, seekToBeginningPartitions);
+                recordProbeOutcomes(windowedPartitionsRetention, seekToBeginningPartitions, floorFallbackPartitions);
                 restoreConsumer.pause(allAssigned);
                 final Set<TopicPartition> toResume = new HashSet<>(allAssigned);
                 toResume.removeAll(previouslyPaused);
@@ -1174,6 +1245,24 @@ public class StoreChangelogReader implements ChangelogReader {
         if (!seekToBeginningPartitions.isEmpty()) {
             restoreConsumer.seekToBeginning(seekToBeginningPartitions);
         }
+        // Partitions with a stored offset that fell back seek to their floor, never to the beginning.
+        for (final TopicPartition partition : floorFallbackPartitions) {
+            restoreConsumer.seek(partition, newPartitionsFloor.get(partition));
+        }
+    }
+
+    /** A partition the probe could not place goes to its floor if it has a stored offset, else to the beginning. */
+    private static void addProbeFallback(final Collection<TopicPartition> partitions,
+                                         final Map<TopicPartition, Long> newPartitionsFloor,
+                                         final Set<TopicPartition> seekToBeginningPartitions,
+                                         final Set<TopicPartition> floorFallbackPartitions) {
+        for (final TopicPartition partition : partitions) {
+            if (newPartitionsFloor.containsKey(partition)) {
+                floorFallbackPartitions.add(partition);
+            } else {
+                seekToBeginningPartitions.add(partition);
+            }
+        }
     }
 
     /**
@@ -1265,7 +1354,9 @@ public class StoreChangelogReader implements ChangelogReader {
 
     private void seekByRetention(final Map<TopicPartition, Long> latestTimestamps,
                                  final Map<TopicPartition, Long> windowedPartitionsRetention,
-                                 final Set<TopicPartition> seekToBeginningPartitions) {
+                                 final Set<TopicPartition> seekToBeginningPartitions,
+                                 final Map<TopicPartition, Long> newPartitionsFloor,
+                                 final Set<TopicPartition> floorFallbackPartitions) {
         final Map<TopicPartition, Long> seekTimestamps = new HashMap<>();
         for (final Map.Entry<TopicPartition, Long> entry : windowedPartitionsRetention.entrySet()) {
             final TopicPartition partition = entry.getKey();
@@ -1280,18 +1371,24 @@ public class StoreChangelogReader implements ChangelogReader {
                     continue;
                 }
             }
-            log.debug("Start restoring changelog partition {} from the beginning.", partition);
-            seekToBeginningPartitions.add(partition);
+            log.debug("Start restoring changelog partition {} from its fallback position.", partition);
+            addProbeFallback(Collections.singleton(partition), newPartitionsFloor, seekToBeginningPartitions, floorFallbackPartitions);
         }
 
         if (!seekTimestamps.isEmpty()) {
             final Map<TopicPartition, OffsetAndTimestamp> offsetsByTimestamp =
                 restoreConsumer.offsetsForTimes(seekTimestamps);
             offsetsByTimestamp.forEach((partition, offsetAndTimestamp) -> {
-                if (offsetAndTimestamp != null) {
+                final Long floor = newPartitionsFloor.get(partition);
+                if (offsetAndTimestamp != null && (floor == null || offsetAndTimestamp.offset() > floor)) {
+                    // a genuine skip past expired data; floor is null with no stored offset, so any
+                    // resolved offset is honoured as before
                     restoreConsumer.seek(partition, offsetAndTimestamp.offset());
                 } else {
-                    seekToBeginningPartitions.add(partition);
+                    // no benefit: offsetsForTimes could not resolve, or resolved at or below the
+                    // stored-offset floor so the probe would skip nothing. Fall back to the floor (or the
+                    // beginning) and arm the backoff so a re-registration does not re-pay for the probe.
+                    addProbeFallback(Collections.singleton(partition), newPartitionsFloor, seekToBeginningPartitions, floorFallbackPartitions);
                 }
             });
         }
@@ -1299,9 +1396,10 @@ public class StoreChangelogReader implements ChangelogReader {
 
     /** Arms the backoff for partitions the probe could not place, and clears it for those it did. */
     private void recordProbeOutcomes(final Map<TopicPartition, Long> windowedPartitionsRetention,
-                                     final Set<TopicPartition> seekToBeginningPartitions) {
+                                     final Set<TopicPartition> seekToBeginningPartitions,
+                                     final Set<TopicPartition> floorFallbackPartitions) {
         for (final TopicPartition partition : windowedPartitionsRetention.keySet()) {
-            if (seekToBeginningPartitions.contains(partition)) {
+            if (seekToBeginningPartitions.contains(partition) || floorFallbackPartitions.contains(partition)) {
                 probeFailedAtMs.put(partition, time.milliseconds());
             } else {
                 probeFailedAtMs.remove(partition);
diff --git a/streams/src/test/java/org/apache/kafka/streams/processor/internals/StoreChangelogReaderTest.java b/streams/src/test/java/org/apache/kafka/streams/processor/internals/StoreChangelogReaderTest.java
index e68a2302d0d..14f61f11f46 100644
--- a/streams/src/test/java/org/apache/kafka/streams/processor/internals/StoreChangelogReaderTest.java
+++ b/streams/src/test/java/org/apache/kafka/streams/processor/internals/StoreChangelogReaderTest.java
@@ -40,6 +40,7 @@ import org.apache.kafka.common.utils.LogContext;
 import org.apache.kafka.common.utils.MockTime;
 import org.apache.kafka.streams.StreamsConfig;
 import org.apache.kafka.streams.errors.StreamsException;
+import org.apache.kafka.streams.errors.TaskCorruptedException;
 import org.apache.kafka.streams.processor.StandbyUpdateListener.SuspendReason;
 import org.apache.kafka.streams.processor.StateStore;
 import org.apache.kafka.streams.processor.TaskId;
@@ -66,6 +67,7 @@ import java.util.Collection;
 import java.util.Collections;
 import java.util.HashMap;
 import java.util.HashSet;
+import java.util.List;
 import java.util.Map;
 import java.util.Optional;
 import java.util.Properties;
@@ -98,6 +100,7 @@ import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyBoolean;
 import static org.mockito.ArgumentMatchers.anyLong;
 import static org.mockito.Mockito.atLeastOnce;
+import static org.mockito.Mockito.doAnswer;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.times;
@@ -1583,7 +1586,7 @@ public class StoreChangelogReaderTest {
             final StateStore store = mock(StateStore.class);
             when(meta.changelogPartition()).thenReturn(tps[i]);
             when(meta.store()).thenReturn(store);
-            when(meta.offset()).thenReturn(null, 0L);   // no checkpoint, then a value once restoring
+            when(meta.offset()).thenReturn(null, 0L);   // no stored offset, then a value once restoring
             when(meta.retentionPeriod()).thenReturn(shortRetentionMs);
             when(store.name()).thenReturn(storeName);
             when(manager.storeMetadata(tps[i])).thenReturn(meta);
@@ -1672,7 +1675,7 @@ public class StoreChangelogReaderTest {
             final StateStore store = mock(StateStore.class);
             when(meta.changelogPartition()).thenReturn(tps[i]);
             when(meta.store()).thenReturn(store);
-            when(meta.offset()).thenReturn(null, 0L);   // no checkpoint, then a value once restoring
+            when(meta.offset()).thenReturn(null, 0L);   // no stored offset, then a value once restoring
             when(meta.retentionPeriod()).thenReturn(shortRetentionMs);
             when(store.name()).thenReturn(storeName);
             when(manager.storeMetadata(tps[i])).thenReturn(meta);
@@ -1761,7 +1764,7 @@ public class StoreChangelogReaderTest {
             final StateStore store = mock(StateStore.class);
             when(meta.changelogPartition()).thenReturn(tps[i]);
             when(meta.store()).thenReturn(store);
-            when(meta.offset()).thenReturn(null, 0L);   // no checkpoint, then a value once restoring
+            when(meta.offset()).thenReturn(null, 0L);   // no stored offset, then a value once restoring
             when(meta.retentionPeriod()).thenReturn(shortRetentionMs);
             when(store.name()).thenReturn(storeName);
             when(manager.storeMetadata(tps[i])).thenReturn(meta);
@@ -1856,7 +1859,7 @@ public class StoreChangelogReaderTest {
             final StateStore store = mock(StateStore.class);
             when(meta.changelogPartition()).thenReturn(tps[i]);
             when(meta.store()).thenReturn(store);
-            when(meta.offset()).thenReturn(null, 0L);   // no checkpoint, then a value once restoring
+            when(meta.offset()).thenReturn(null, 0L);   // no stored offset, then a value once restoring
             when(meta.retentionPeriod()).thenReturn(shortRetentionMs);
             when(store.name()).thenReturn(storeName);
             when(manager.storeMetadata(tps[i])).thenReturn(meta);
@@ -2083,7 +2086,7 @@ public class StoreChangelogReaderTest {
         final StateStore store = mock(StateStore.class);
         when(meta.changelogPartition()).thenReturn(tp);
         when(meta.store()).thenReturn(store);
-        when(meta.offset()).thenReturn(null, 0L);   // no checkpoint, then a value once restoring
+        when(meta.offset()).thenReturn(null, 0L);   // no stored offset, then a value once restoring
         when(meta.retentionPeriod()).thenReturn(retentionMs);
         when(store.name()).thenReturn(storeName);
         when(manager.storeMetadata(tp)).thenReturn(meta);
@@ -2099,7 +2102,7 @@ public class StoreChangelogReaderTest {
     }
 
     @Test
-    public void shouldSeekByTimestampForWindowedStoreWithoutCheckpoint() {
+    public void shouldSeekByTimestampForWindowedStoreWithoutStoredOffset() {
         final long retentionMs = Duration.ofHours(2).toMillis();
         final long offsetForTimestamp = 42L;
         final long latestRecordTimestamp = 10_000_000L;
@@ -2198,7 +2201,7 @@ public class StoreChangelogReaderTest {
     }
 
     @Test
-    public void shouldSeekToBeginningForNonWindowedStoreWithoutCheckpoint() {
+    public void shouldSeekToBeginningForNonWindowedStoreWithoutStoredOffset() {
         final StateStoreMetadata kvStoreMetadata = mock(StateStoreMetadata.class);
         final ProcessorStateManager kvStateManager = mock(ProcessorStateManager.class);
         final StateStore kvStore = mock(StateStore.class);
@@ -2225,6 +2228,452 @@ public class StoreChangelogReaderTest {
         assertEquals(0L, consumer.position(tp), "Non-windowed store should seek to beginning, not by timestamp");
     }
 
+    private ProcessorStateManager windowedActiveManager(final StateStoreMetadata meta,
+                                                        final TopicPartition partition,
+                                                        final TaskId taskId,
+                                                        final long retentionMs) {
+        final ProcessorStateManager manager = mock(ProcessorStateManager.class);
+        final StateStore windowStore = mock(StateStore.class);
+        when(meta.changelogPartition()).thenReturn(partition);
+        when(meta.store()).thenReturn(windowStore);
+        when(meta.retentionPeriod()).thenReturn(retentionMs);
+        when(windowStore.name()).thenReturn(storeName);
+        when(manager.storeMetadata(partition)).thenReturn(meta);
+        when(manager.taskType()).thenReturn(ACTIVE);
+        when(manager.taskId()).thenReturn(taskId);
+        return manager;
+    }
+
+    private static ConsumerRecord<byte[], byte[]> changelogRecord(final TopicPartition partition,
+                                                                  final long offset,
+                                                                  final long timestamp) {
+        return new ConsumerRecord<>(partition.topic(), partition.partition(), offset, timestamp,
+            TimestampType.CREATE_TIME, 0, 0, new byte[0], new byte[0], new RecordHeaders(), Optional.empty());
+    }
+
+    /**
+     * With a stored offset far behind a large changelog, the reader used to replay the whole gap. It
+     * should instead probe for observed stream time and skip data the store discards on restore,
+     * just as it does when restoring from scratch.
+     */
+    @Test
+    public void shouldSeekPastStoredOffsetByTimestampWhenGapIsLarge() {
+        final long retentionMs = Duration.ofHours(2).toMillis();
+        final long storedOffset = 100L;
+        final long endOffset = 100_000L;          // gap far exceeds PROBE_MIN_OFFSET_GAP
+        final long offsetForTimestamp = 50_000L;  // well past the stored offset
+
+        final MockConsumer<byte[], byte[]> timestampConsumer = new MockConsumer<>(AutoOffsetResetStrategy.EARLIEST.name()) {
+            @Override
+            public synchronized Map<TopicPartition, OffsetAndTimestamp> offsetsForTimes(final Map<TopicPartition, Long> timestampsToSearch) {
+                final Map<TopicPartition, OffsetAndTimestamp> result = new HashMap<>();
+                timestampsToSearch.forEach((key, value) -> result.put(key, new OffsetAndTimestamp(offsetForTimestamp, value)));
+                return result;
+            }
+        };
+        timestampConsumer.updateBeginningOffsets(Collections.singletonMap(tp, 0L));
+        timestampConsumer.updateEndOffsets(Collections.singletonMap(tp, endOffset));
+        adminClient.updateEndOffsets(Collections.singletonMap(tp, endOffset));
+        timestampConsumer.schedulePollTask(() -> timestampConsumer.addRecord(changelogRecord(tp, endOffset - 1, 10_000_000L)));
+
+        final TaskId taskId = new TaskId(0, 0);
+        final StateStoreMetadata meta = mock(StateStoreMetadata.class);
+        when(meta.offset()).thenReturn(storedOffset);
+        final ProcessorStateManager manager = windowedActiveManager(meta, tp, taskId, retentionMs);
+
+        final StoreChangelogReader reader =
+            new StoreChangelogReader(time, config, logContext, adminClient, timestampConsumer, callback, standbyListener);
+        reader.register(tp, manager);
+        reader.restore(Collections.singletonMap(taskId, mock(Task.class)));
+
+        assertEquals(offsetForTimestamp, timestampConsumer.position(tp),
+            "a stored offset far behind a large changelog should skip expired data, not replay from the stored offset");
+        assertEquals(offsetForTimestamp, callback.restoreStartOffset,
+            "restoration should be reported as starting at the skipped-to offset");
+    }
+
+    /**
+     * After skipping past a stored offset, the first restored batch begins at the skip target, not at
+     * the stored offset. Measuring the batch from the stored offset would decrement the remaining-records
+     * metric by the whole skipped gap and drive it negative.
+     */
+    @Test
+    public void shouldNotDecrementRemainingRecordsBelowZeroWhenSkippingPastStoredOffset() {
+        final long retentionMs = Duration.ofHours(2).toMillis();
+        final long storedOffset = 100L;
+        final long endOffset = 100_000L;
+        final long offsetForTimestamp = 50_000L;
+        final long batchRecordOffset = 60_000L;
+
+        final MockConsumer<byte[], byte[]> timestampConsumer = new MockConsumer<>(AutoOffsetResetStrategy.EARLIEST.name()) {
+            @Override
+            public synchronized Map<TopicPartition, OffsetAndTimestamp> offsetsForTimes(final Map<TopicPartition, Long> timestampsToSearch) {
+                final Map<TopicPartition, OffsetAndTimestamp> result = new HashMap<>();
+                timestampsToSearch.forEach((key, value) -> result.put(key, new OffsetAndTimestamp(offsetForTimestamp, value)));
+                return result;
+            }
+        };
+        timestampConsumer.updateBeginningOffsets(Collections.singletonMap(tp, 0L));
+        timestampConsumer.updateEndOffsets(Collections.singletonMap(tp, endOffset));
+        adminClient.updateEndOffsets(Collections.singletonMap(tp, endOffset));
+        // the probe consumes the record at the head; the batch record sits below the probe position
+        // and is only returned by the main poll after the skip
+        timestampConsumer.schedulePollTask(() -> {
+            timestampConsumer.addRecord(changelogRecord(tp, endOffset - 1, 10_000_000L));
+            timestampConsumer.addRecord(changelogRecord(tp, batchRecordOffset, 10_000_000L));
+        });
+
+        // storeMetadata.offset() advances as records are restored, mirroring ProcessorStateManager.restore
+        final long[] storeOffset = {storedOffset};
+        final TaskId taskId = new TaskId(0, 0);
+        final StateStoreMetadata meta = mock(StateStoreMetadata.class);
+        when(meta.offset()).thenAnswer(invocation -> storeOffset[0]);
+        final ProcessorStateManager manager = windowedActiveManager(meta, tp, taskId, retentionMs);
+        doAnswer(invocation -> {
+            final List<ConsumerRecord<byte[], byte[]>> restored = invocation.getArgument(1);
+            if (!restored.isEmpty()) {
+                storeOffset[0] = restored.get(restored.size() - 1).offset();
+            }
+            return null;
+        }).when(manager).restore(any(), any(), any());
+
+        final Task task = mock(Task.class);
+        final StoreChangelogReader reader =
+            new StoreChangelogReader(time, config, logContext, adminClient, timestampConsumer, callback, standbyListener);
+        reader.register(tp, manager);
+        reader.restore(Collections.singletonMap(taskId, task));
+
+        final ArgumentCaptor<Long> numOffsets = ArgumentCaptor.forClass(Long.class);
+        final ArgumentCaptor<Boolean> initRemaining = ArgumentCaptor.forClass(Boolean.class);
+        verify(task, atLeastOnce()).recordRestoration(any(), anyLong(), numOffsets.capture(), initRemaining.capture());
+
+        long initialized = 0L;
+        long decremented = 0L;
+        for (int i = 0; i < initRemaining.getAllValues().size(); i++) {
+            if (initRemaining.getAllValues().get(i)) {
+                initialized += numOffsets.getAllValues().get(i);
+            } else {
+                decremented += numOffsets.getAllValues().get(i);
+            }
+        }
+        assertEquals(offsetForTimestamp, callback.restoreStartOffset,
+            "restoration should be reported as starting at the skipped-to offset");
+        assertTrue(decremented <= initialized,
+            "remaining-records was initialised to " + initialized + " but decremented by " + decremented
+                + "; measuring the first batch from the stored offset instead of the skip target drives it negative");
+    }
+
+    /**
+     * When little of the gap is expired, offsetsForTimes returns an offset at or before the
+     * stored offset. Seeking there would re-apply already-applied records and rewind the stored offset, so
+     * the seek must be floored at the stored offset.
+     */
+    @Test
+    public void shouldNotSeekBelowStoredOffsetWhenTimestampOffsetIsBehindIt() {
+        final long retentionMs = Duration.ofHours(2).toMillis();
+        final long storedOffset = 100L;
+        final long endOffset = 100_000L;
+        final long offsetForTimestamp = 90L;   // behind the stored offset: almost all of the gap is live
+
+        final Map<TopicPartition, Long> probed = new HashMap<>();
+        final MockConsumer<byte[], byte[]> timestampConsumer = new MockConsumer<>(AutoOffsetResetStrategy.EARLIEST.name()) {
+            @Override
+            public synchronized Map<TopicPartition, OffsetAndTimestamp> offsetsForTimes(final Map<TopicPartition, Long> timestampsToSearch) {
+                probed.putAll(timestampsToSearch);
+                final Map<TopicPartition, OffsetAndTimestamp> result = new HashMap<>();
+                timestampsToSearch.forEach((key, value) -> result.put(key, new OffsetAndTimestamp(offsetForTimestamp, value)));
+                return result;
+            }
+        };
+        timestampConsumer.updateBeginningOffsets(Collections.singletonMap(tp, 0L));
+        timestampConsumer.updateEndOffsets(Collections.singletonMap(tp, endOffset));
+        adminClient.updateEndOffsets(Collections.singletonMap(tp, endOffset));
+        timestampConsumer.schedulePollTask(() -> timestampConsumer.addRecord(changelogRecord(tp, endOffset - 1, 10_000_000L)));
+
+        final TaskId taskId = new TaskId(0, 0);
+        final StateStoreMetadata meta = mock(StateStoreMetadata.class);
+        when(meta.offset()).thenReturn(storedOffset);
+        final ProcessorStateManager manager = windowedActiveManager(meta, tp, taskId, retentionMs);
+
+        final StoreChangelogReader reader =
+            new StoreChangelogReader(time, config, logContext, adminClient, timestampConsumer, callback, standbyListener);
+        reader.register(tp, manager);
+        reader.restore(Collections.singletonMap(taskId, mock(Task.class)));
+
+        assertTrue(probed.containsKey(tp), "a large gap should route the stored-offset partition through the probe");
+        assertEquals(storedOffset + 1, timestampConsumer.position(tp),
+            "when offsetsForTimes lands at or before the stored offset, restoration must resume at the stored offset, never rewind below it");
+    }
+
+    /**
+     * A probe that resolves at or below the stored offset skipped nothing, so it must arm the backoff
+     * just like a probe that never answered: an immediate re-registration should replay from the
+     * stored offset without probing again, rather than re-paying for a probe that cannot help.
+     */
+    @Test
+    public void shouldBackOffWhenTimestampOffsetClampsToStoredOffset() {
+        final long retentionMs = Duration.ofHours(2).toMillis();
+        final long storedOffset = 100L;
+        final long endOffset = 100_000L;
+        final long offsetForTimestamp = 90L;   // at or below the stored offset: nothing in the gap expired
+        final int[] probeRounds = {0};
+
+        final MockConsumer<byte[], byte[]> probeConsumer = new MockConsumer<>(AutoOffsetResetStrategy.EARLIEST.name()) {
+            @Override
+            public synchronized Map<TopicPartition, OffsetAndTimestamp> offsetsForTimes(final Map<TopicPartition, Long> timestampsToSearch) {
+                probeRounds[0]++;
+                final Map<TopicPartition, OffsetAndTimestamp> result = new HashMap<>();
+                timestampsToSearch.forEach((key, value) -> result.put(key, new OffsetAndTimestamp(offsetForTimestamp, value)));
+                return result;
+            }
+        };
+        probeConsumer.updateBeginningOffsets(Collections.singletonMap(tp, 0L));
+        probeConsumer.updateEndOffsets(Collections.singletonMap(tp, endOffset));
+        adminClient.updateEndOffsets(Collections.singletonMap(tp, endOffset));
+        // the probe resolves a stream time from the head record, then offsetsForTimes clamps to the stored offset
+        probeConsumer.schedulePollTask(() -> probeConsumer.addRecord(changelogRecord(tp, endOffset - 1, 10_000_000L)));
+
+        final StoreChangelogReader reader =
+            new StoreChangelogReader(time, config, logContext, adminClient, probeConsumer, callback, standbyListener);
+        final TaskId taskId = new TaskId(0, 0);
+
+        final StateStoreMetadata meta = mock(StateStoreMetadata.class);
+        when(meta.offset()).thenReturn(storedOffset);
+        reader.register(tp, windowedActiveManager(meta, tp, taskId, retentionMs));
+        reader.restore(Collections.singletonMap(taskId, mock(Task.class)));
+
+        assertEquals(storedOffset + 1, probeConsumer.position(tp),
+            "a probe that clamps to the stored offset must resume there, not rewind below it");
+        assertEquals(1, probeRounds[0], "the first registration probes once");
+
+        reader.unregister(Collections.singleton(tp));
+
+        final StateStoreMetadata meta2 = mock(StateStoreMetadata.class);
+        when(meta2.offset()).thenReturn(storedOffset);
+        reader.register(tp, windowedActiveManager(meta2, tp, taskId, retentionMs));
+        reader.restore(Collections.singletonMap(taskId, mock(Task.class)));
+
+        assertEquals(1, probeRounds[0],
+            "a probe that skipped nothing must arm the backoff, so re-registering immediately replays from the stored offset without probing");
+        assertEquals(storedOffset + 1, probeConsumer.position(tp), "the backed-off registration replays from the stored offset");
+    }
+
+    /**
+     * A small stored offset gap is not worth a probe: replaying it costs about what the probe spends,
+     * and the probe pauses every restoring partition while it runs. Common restores should pay no
+     * new RPCs.
+     */
+    @Test
+    public void shouldNotProbeWhenStoredOffsetGapIsSmall() {
+        final long retentionMs = Duration.ofHours(2).toMillis();
+        final long storedOffset = 100L;
+        final long endOffset = 200L;   // gap far below PROBE_MIN_OFFSET_GAP
+
+        final MockConsumer<byte[], byte[]> noProbeConsumer = new MockConsumer<>(AutoOffsetResetStrategy.EARLIEST.name()) {
+            @Override
+            public synchronized Map<TopicPartition, Long> endOffsets(final Collection<TopicPartition> partitions) {
+                throw new AssertionError("a small stored offset gap must not trigger a probe");
+            }
+
+            @Override
+            public synchronized Map<TopicPartition, Long> beginningOffsets(final Collection<TopicPartition> partitions) {
+                throw new AssertionError("a small stored offset gap must not trigger a probe");
+            }
+
+            @Override
+            public synchronized Map<TopicPartition, OffsetAndTimestamp> offsetsForTimes(final Map<TopicPartition, Long> timestampsToSearch) {
+                throw new AssertionError("a small stored offset gap must not trigger a probe");
+            }
+        };
+        adminClient.updateEndOffsets(Collections.singletonMap(tp, endOffset));
+
+        final TaskId taskId = new TaskId(0, 0);
+        final StateStoreMetadata meta = mock(StateStoreMetadata.class);
+        when(meta.offset()).thenReturn(storedOffset);
+        final ProcessorStateManager manager = windowedActiveManager(meta, tp, taskId, retentionMs);
+
+        final StoreChangelogReader reader =
+            new StoreChangelogReader(time, config, logContext, adminClient, noProbeConsumer, callback, standbyListener);
+        reader.register(tp, manager);
+        reader.restore(Collections.singletonMap(taskId, mock(Task.class)));
+
+        assertEquals(storedOffset + 1, noProbeConsumer.position(tp), "a small gap should replay from the stored offset, cheaply");
+    }
+
+    /**
+     * A probe that never answers must send a stored-offset partition back to its stored offset, not to
+     * the beginning, and arm the backoff so a re-registration loop does not probe on every iteration.
+     */
+    @Test
+    public void shouldFallBackToStoredOffsetAndBackOffWhenProbeNeverAnswers() {
+        final long retentionMs = Duration.ofHours(2).toMillis();
+        final long storedOffset = 100L;
+        final long endOffset = 100_000L;
+        final int[] probeRounds = {0};
+
+        final MockConsumer<byte[], byte[]> probeConsumer = new MockConsumer<>(AutoOffsetResetStrategy.EARLIEST.name()) {
+            @Override
+            public synchronized Map<TopicPartition, Long> beginningOffsets(final Collection<TopicPartition> partitions) {
+                probeRounds[0]++;      // only the probe looks these up
+                return super.beginningOffsets(partitions);
+            }
+        };
+        probeConsumer.updateBeginningOffsets(Collections.singletonMap(tp, 0L));
+        probeConsumer.updateEndOffsets(Collections.singletonMap(tp, endOffset));
+        adminClient.updateEndOffsets(Collections.singletonMap(tp, endOffset));
+        // no records are scheduled, so the probe never answers and must fall back
+
+        final StoreChangelogReader reader =
+            new StoreChangelogReader(time, config, logContext, adminClient, probeConsumer, callback, standbyListener);
+        final TaskId taskId = new TaskId(0, 0);
+
+        final StateStoreMetadata meta = mock(StateStoreMetadata.class);
+        when(meta.offset()).thenReturn(storedOffset);
+        reader.register(tp, windowedActiveManager(meta, tp, taskId, retentionMs));
+        reader.restore(Collections.singletonMap(taskId, mock(Task.class)));
+
+        assertEquals(storedOffset + 1, probeConsumer.position(tp),
+            "a probe that never answers must fall back to the stored offset, not the beginning");
+        assertEquals(1, probeRounds[0], "the first registration probes once");
+
+        reader.unregister(Collections.singleton(tp));
+
+        final StateStoreMetadata meta2 = mock(StateStoreMetadata.class);
+        when(meta2.offset()).thenReturn(storedOffset);
+        reader.register(tp, windowedActiveManager(meta2, tp, taskId, retentionMs));
+        reader.restore(Collections.singletonMap(taskId, mock(Task.class)));
+
+        assertEquals(1, probeRounds[0],
+            "the probe just fell back, so re-registering immediately must replay from the stored offset without probing");
+        assertEquals(storedOffset + 1, probeConsumer.position(tp), "the backed-off registration replays from the stored offset");
+    }
+
+    /**
+     * When a probe falls back for a mixed set, each partition must land on its own safe position: a
+     * partition with no stored offset at the beginning, a stored-offset one at its stored offset.
+     */
+    @Test
+    public void shouldFallBackNoStoredOffsetToBeginningAndStoredOffsetToItsFloor() {
+        final long retentionMs = Duration.ofHours(2).toMillis();
+        final long storedOffset = 100L;
+        final long endOffset = 100_000L;
+
+        final MockConsumer<byte[], byte[]> probeConsumer = new MockConsumer<>(AutoOffsetResetStrategy.EARLIEST.name());
+        final Map<TopicPartition, Long> begins = new HashMap<>();
+        begins.put(tp, 0L);
+        begins.put(tp1, 0L);
+        final Map<TopicPartition, Long> ends = new HashMap<>();
+        ends.put(tp, endOffset);
+        ends.put(tp1, endOffset);
+        probeConsumer.updateBeginningOffsets(begins);
+        probeConsumer.updateEndOffsets(ends);
+        adminClient.updateEndOffsets(Collections.singletonMap(tp, endOffset));
+        adminClient.updateEndOffsets(Collections.singletonMap(tp1, endOffset));
+        // no records are scheduled, so both probes fall back
+
+        final TaskId taskId0 = new TaskId(0, 0);
+        final TaskId taskId1 = new TaskId(0, 1);
+        final StateStoreMetadata meta0 = mock(StateStoreMetadata.class);
+        when(meta0.offset()).thenReturn(null);
+        final StateStoreMetadata meta1 = mock(StateStoreMetadata.class);
+        when(meta1.offset()).thenReturn(storedOffset);
+
+        final StoreChangelogReader reader =
+            new StoreChangelogReader(time, config, logContext, adminClient, probeConsumer, callback, standbyListener);
+        reader.register(tp, windowedActiveManager(meta0, tp, taskId0, retentionMs));
+        reader.register(tp1, windowedActiveManager(meta1, tp1, taskId1, retentionMs));
+
+        final Map<TaskId, Task> tasks = new HashMap<>();
+        tasks.put(taskId0, mock(Task.class));
+        tasks.put(taskId1, mock(Task.class));
+        reader.restore(tasks);
+
+        assertEquals(0L, probeConsumer.position(tp), "the partition with no stored offset falls back to the beginning");
+        assertEquals(storedOffset + 1, probeConsumer.position(tp1),
+            "the stored-offset partition falls back to its stored offset, not the beginning");
+    }
+
+    /**
+     * A stored offset below the current log start means records in (stored offset, logStart) were deleted
+     * before they could be verified. The skip cannot certify them, so the partition takes the
+     * deterministic InvalidOffsetException -> TaskCorruptedException wipe path, exactly as a plain
+     * seek to the stored offset would.
+     */
+    @Test
+    public void shouldMarkTaskCorruptedWhenStoredOffsetIsBelowTheLogStart() {
+        final long retentionMs = Duration.ofHours(2).toMillis();
+        final long storedOffset = 100L;
+        final long logStart = 5_000L;   // (stored offset, logStart) has been truncated
+        final long endOffset = 100_000L;
+
+        final MockConsumer<byte[], byte[]> probeConsumer = new MockConsumer<>(AutoOffsetResetStrategy.EARLIEST.name());
+        probeConsumer.updateBeginningOffsets(Collections.singletonMap(tp, logStart));
+        probeConsumer.updateEndOffsets(Collections.singletonMap(tp, endOffset));
+        adminClient.updateEndOffsets(Collections.singletonMap(tp, endOffset));
+        // a record must be queued so the out-of-range position is discovered on the next poll
+        probeConsumer.schedulePollTask(() -> probeConsumer.addRecord(changelogRecord(tp, logStart, 10_000_000L)));
+
+        final TaskId taskId = new TaskId(0, 0);
+        final StateStoreMetadata meta = mock(StateStoreMetadata.class);
+        when(meta.offset()).thenReturn(storedOffset);
+        final ProcessorStateManager manager = windowedActiveManager(meta, tp, taskId, retentionMs);
+
+        final StoreChangelogReader reader =
+            new StoreChangelogReader(time, config, logContext, adminClient, probeConsumer, callback, standbyListener);
+        reader.register(tp, manager);
+
+        assertThrows(TaskCorruptedException.class,
+            () -> reader.restore(Collections.singletonMap(taskId, mock(Task.class))),
+            "a stored offset below the log start cannot be verified and must trigger the wipe path");
+    }
+
+    /**
+     * The skip optimisation is active-only: a standby with a stored offset replays its gap and is never
+     * probed.
+     */
+    @Test
+    public void shouldNotProbeStandbyWithStoredOffset() {
+        final long storedOffset = 100L;
+
+        final MockConsumer<byte[], byte[]> noProbeConsumer = new MockConsumer<>(AutoOffsetResetStrategy.EARLIEST.name()) {
+            @Override
+            public synchronized Map<TopicPartition, Long> endOffsets(final Collection<TopicPartition> partitions) {
+                throw new AssertionError("standbys must not probe");
+            }
+
+            @Override
+            public synchronized Map<TopicPartition, Long> beginningOffsets(final Collection<TopicPartition> partitions) {
+                throw new AssertionError("standbys must not probe");
+            }
+
+            @Override
+            public synchronized Map<TopicPartition, OffsetAndTimestamp> offsetsForTimes(final Map<TopicPartition, Long> timestampsToSearch) {
+                throw new AssertionError("standbys must not probe");
+            }
+        };
+
+        final TaskId taskId = new TaskId(0, 0);
+        final StateStoreMetadata meta = mock(StateStoreMetadata.class);
+        final ProcessorStateManager manager = mock(ProcessorStateManager.class);
+        final StateStore windowStore = mock(StateStore.class);
+        when(meta.changelogPartition()).thenReturn(tp);
+        when(meta.store()).thenReturn(windowStore);
+        when(meta.offset()).thenReturn(storedOffset);
+        when(windowStore.name()).thenReturn(storeName);
+        when(manager.storeMetadata(tp)).thenReturn(meta);
+        when(manager.taskType()).thenReturn(STANDBY);
+        when(manager.taskId()).thenReturn(taskId);
+        when(manager.changelogAsSource(tp)).thenReturn(false);
+
+        final StoreChangelogReader reader =
+            new StoreChangelogReader(time, config, logContext, adminClient, noProbeConsumer, callback, standbyListener);
+        reader.register(tp, manager);
+        reader.restore(Collections.singletonMap(taskId, mock(Task.class)));
+
+        assertEquals(storedOffset + 1, noProbeConsumer.position(tp),
+            "a standby replays its stored offset gap; the skip optimisation is active-only");
+    }
+
     private void assignPartition(final long messages,
                                  final TopicPartition topicPartition) {
         consumer.updatePartitions(


(kafka) 03/04: KAFKA-20876: Windowed restore optimisation gives up when `endOffset-1` is a transaction control record (#23086)

Posted by bb...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

bbejeck pushed a commit to branch 4.3
in repository https://gitbox.apache.org/repos/asf/kafka.git

commit b3add3983546158bd2eeaaf2fa62e8f1b68edb89
Author: Alan Lau <72...@users.noreply.github.com>
AuthorDate: Thu Aug 13 16:11:06 2026 -0400

    KAFKA-20876: Windowed restore optimisation gives up when `endOffset-1` is a transaction control record (#23086)
    
    Jira: https://issues.apache.org/jira/browse/KAFKA-20876
    
    When restoring a windowed store with no checkpoint,
    `StoreChangelogReader` seeks to `latestTimestamp - retentionPeriod`
    rather than log-start, since data older than the retention is discarded
    on write. It learns `latestTimestamp` by seeking to `endOffset - 1` and
    polling once in `seekNewPartitions`; an empty poll falls back to
    `seekToBeginning`.
    
    The probe now reads a window back from the end rather than a single
    offset, widens it when that window holds no record, and keeps polling a
    window for as long as it is still resolving partitions.
    
    Reviewers: Bill Bejeck <bb...@apache.org>
---
 .../processor/internals/StoreChangelogReader.java  | 168 +++++-
 .../internals/StoreChangelogReaderTest.java        | 592 +++++++++++++++++++++
 2 files changed, 748 insertions(+), 12 deletions(-)

diff --git a/streams/src/main/java/org/apache/kafka/streams/processor/internals/StoreChangelogReader.java b/streams/src/main/java/org/apache/kafka/streams/processor/internals/StoreChangelogReader.java
index e634aae279b..3c82dcc7259 100644
--- a/streams/src/main/java/org/apache/kafka/streams/processor/internals/StoreChangelogReader.java
+++ b/streams/src/main/java/org/apache/kafka/streams/processor/internals/StoreChangelogReader.java
@@ -55,6 +55,7 @@ import java.util.Collection;
 import java.util.Collections;
 import java.util.HashMap;
 import java.util.HashSet;
+import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 import java.util.OptionalLong;
@@ -205,8 +206,34 @@ public class StoreChangelogReader implements ChangelogReader {
 
     private static final long DEFAULT_OFFSET_UPDATE_MS = Duration.ofMinutes(5L).toMillis();
 
+    // Windows the probe reads back from each partition's end. Not 1: under EOS the last offset is
+    // usually a transaction control record, never delivered to a consumer, so probing there is a
+    // guaranteed empty poll.
+    private static final long[] PROBE_WINDOWS = {128L, 512L, 2048L};
+
+    // One empty poll proves nothing: poll() returns as soon as any fetch lands, so a partition can
+    // come back empty because another was served first.
+    private static final int PROBE_IDLE_POLLS = 3;
+
+    // Floor on the waiting a window is owed before it may be called empty: polls that return
+    // immediately have not waited on a fetch, and the floor has to cover a widening, whose re-seek
+    // discards the in-flight fetch and queues behind it -- one fetch in flight per broker.
+    private static final int PROBE_MIN_WAIT_POLLS = 10;
+
+    // Ceiling per window, so polls that return without waiting cannot spin the probe.
+    private static final int PROBE_MAX_POLLS = 30;
+
+    // How long a partition whose probe fell back is left alone, so a task corrupted, wiped and
+    // re-registered in a loop cannot probe on every iteration. Only a failed probe arms it, so a
+    // probe that is working is never suppressed.
+    private static final Duration PROBE_RETRY_BACKOFF = Duration.ofSeconds(60);
+
     private ChangelogReaderState state;
 
+    // deliberately outlives unregister: a changelog that is corrupted and re-registered in a loop
+    // must not forget that probing it has just failed
+    private final Map<TopicPartition, Long> probeFailedAtMs = new HashMap<>();
+
     private final Time time;
     private final Logger log;
     private final Duration pollTime;
@@ -1019,7 +1046,13 @@ public class StoreChangelogReader implements ChangelogReader {
             } else {
                 final long retentionPeriod = storeMetadata.retentionPeriod();
                 if (retentionPeriod > 0 && retentionPeriod != Long.MAX_VALUE) {
-                    newWindowedPartitionsRetention.put(partition, retentionPeriod);
+                    if (probeIsDue(partition)) {
+                        newWindowedPartitionsRetention.put(partition, retentionPeriod);
+                    } else {
+                        log.debug("Start restoring changelog partition {} from the beginning offset to end offset {} " +
+                            "since its last attempt to seek past expired data failed.", partition, recordEndOffset(endOffset));
+                        newSeekToBeginningPartitions.add(partition);
+                    }
                 } else {
                     final StateStore store = storeMetadata.store();
                     if (store instanceof WindowStore || store instanceof SessionStore) {
@@ -1096,21 +1129,25 @@ public class StoreChangelogReader implements ChangelogReader {
 
                 final Map<TopicPartition, Long> endOffsets =
                     restoreConsumer.endOffsets(windowedPartitionsRetention.keySet());
+                final Map<TopicPartition, Long> beginningOffsets =
+                    restoreConsumer.beginningOffsets(windowedPartitionsRetention.keySet());
 
                 for (final TopicPartition partition : windowedPartitionsRetention.keySet()) {
                     final Long endOffset = endOffsets.get(partition);
-                    if (endOffset != null && endOffset > 0) {
-                        restoreConsumer.seek(partition, endOffset - 1);
-                    } else {
+                    if (endOffset == null || endOffset <= 0) {
                         restoreConsumer.seekToBeginning(Collections.singleton(partition));
                         seekToBeginningPartitions.add(partition);
                     }
                 }
                 windowedPartitionsRetention.keySet().removeAll(seekToBeginningPartitions);
 
-                final ConsumerRecords<byte[], byte[]> polledRecords = restoreConsumer.poll(pollTime);
+                // probe back from the head for the newest data record: under EOS endOffset-1 is
+                // usually a control record, and the optimisation would degrade to seekToBeginning
+                final Map<TopicPartition, Long> latestTimestamps = new HashMap<>();
+                final Set<TopicPartition> unresolved = new HashSet<>(windowedPartitionsRetention.keySet());
+                runBackwardProbe(unresolved, latestTimestamps, beginningOffsets, endOffsets);
 
-                seekByRetentionFromPolledRecords(polledRecords, windowedPartitionsRetention, seekToBeginningPartitions);
+                seekByRetention(latestTimestamps, windowedPartitionsRetention, seekToBeginningPartitions);
             } catch (final TimeoutException e) {
                 log.debug("Could not seek by timestamp for changelog partitions {}, falling back to seek-to-beginning",
                     windowedPartitionsRetention.keySet(), e);
@@ -1120,6 +1157,9 @@ public class StoreChangelogReader implements ChangelogReader {
                     windowedPartitionsRetention.keySet(), e);
                 seekToBeginningPartitions.addAll(windowedPartitionsRetention.keySet());
             } finally {
+                // in the finally, not after the probe: a lookup that times out leaves through a
+                // catch, and a probe that fails that way must arm the backoff like any other
+                recordProbeOutcomes(windowedPartitionsRetention, seekToBeginningPartitions);
                 restoreConsumer.pause(allAssigned);
                 final Set<TopicPartition> toResume = new HashSet<>(allAssigned);
                 toResume.removeAll(previouslyPaused);
@@ -1136,16 +1176,102 @@ public class StoreChangelogReader implements ChangelogReader {
         }
     }
 
-    private void seekByRetentionFromPolledRecords(final ConsumerRecords<byte[], byte[]> polledRecords,
-                                                   final Map<TopicPartition, Long> windowedPartitionsRetention,
-                                                   final Set<TopicPartition> seekToBeginningPartitions) {
+    /**
+     * Reads back from each partition's end for the newest timestamp, to drive the retention-based
+     * seek. A window that cannot answer is widened; what the widest cannot answer for goes to log start.
+     */
+    private void runBackwardProbe(final Set<TopicPartition> unresolved,
+                                  final Map<TopicPartition, Long> latestTimestamps,
+                                  final Map<TopicPartition, Long> beginningOffsets,
+                                  final Map<TopicPartition, Long> endOffsets) {
+        long previousBack = 0L;
+        for (final long back : PROBE_WINDOWS) {
+            if (unresolved.isEmpty()) {
+                return;
+            }
+            seekProbePositions(unresolved, back, previousBack, beginningOffsets, endOffsets);
+            pollProbeWindow(unresolved, latestTimestamps);
+            previousBack = back;
+        }
+    }
+
+    /** Seeks each unresolved partition back by {@code back} offsets from its end. */
+    private void seekProbePositions(final Set<TopicPartition> unresolved,
+                                    final long back,
+                                    final long previousBack,
+                                    final Map<TopicPartition, Long> beginningOffsets,
+                                    final Map<TopicPartition, Long> endOffsets) {
+        // poll() updates fetch positions for the whole assignment and the restore consumer has
+        // auto.offset.reset=none, so every partition needs a position before the first poll
+        for (final TopicPartition partition : unresolved) {
+            final long begin = beginningOffsets.getOrDefault(partition, 0L);
+            final long end = endOffsets.get(partition);
+            final long target = Math.max(begin, end - back);
+            // a partition whose narrower window already reached log start has nothing further to
+            // show; re-seeking it would only discard the fetch that is about to answer
+            if (previousBack > 0L && target == Math.max(begin, end - previousBack)) {
+                continue;
+            }
+            restoreConsumer.seek(partition, target);
+        }
+    }
+
+    /** Polls the current window until it stops answering and has been given its dues. */
+    private void pollProbeWindow(final Set<TopicPartition> unresolved,
+                                 final Map<TopicPartition, Long> latestTimestamps) {
+        // a poll returns at most max.poll.records across all partitions, so one window can take
+        // several polls to reach them all; a fixed count abandons partitions still being served
+        final long startNs = time.nanoseconds();
+        final long minWaitNs = pollTime.toNanos() * PROBE_MIN_WAIT_POLLS;
+        int idlePolls = 0;
+        int polls = 0;
+        while (!unresolved.isEmpty() && polls < PROBE_MAX_POLLS
+            && (idlePolls < PROBE_IDLE_POLLS || time.nanoseconds() - startNs < minWaitNs)) {
+            final int remaining = unresolved.size();
+            collectProbed(restoreConsumer.poll(pollTime), unresolved, latestTimestamps);
+            polls++;
+            idlePolls = unresolved.size() < remaining ? 0 : idlePolls + 1;
+        }
+    }
+
+    /**
+     * Resolves any partition the poll answered for, taking the newest timestamp in the window: it
+     * estimates observed stream time, and a timestamp the log holds cannot overshoot it.
+     */
+    private void collectProbed(final ConsumerRecords<byte[], byte[]> probed,
+                               final Set<TopicPartition> unresolved,
+                               final Map<TopicPartition, Long> latestTimestamps) {
+        final Set<TopicPartition> resolved = new HashSet<>();
+        final Iterator<TopicPartition> iterator = unresolved.iterator();
+        while (iterator.hasNext()) {
+            final TopicPartition partition = iterator.next();
+            final List<ConsumerRecord<byte[], byte[]>> records = probed.records(partition);
+            if (records.isEmpty()) {
+                continue;
+            }
+            long latest = Long.MIN_VALUE;
+            for (final ConsumerRecord<byte[], byte[]> record : records) {
+                latest = Math.max(latest, record.timestamp());
+            }
+            latestTimestamps.put(partition, latest);
+            resolved.add(partition);
+            iterator.remove();
+        }
+        if (!resolved.isEmpty()) {
+            // stop resolved partitions competing for the next poll's max.poll.records budget
+            restoreConsumer.pause(resolved);
+        }
+    }
+
+    private void seekByRetention(final Map<TopicPartition, Long> latestTimestamps,
+                                 final Map<TopicPartition, Long> windowedPartitionsRetention,
+                                 final Set<TopicPartition> seekToBeginningPartitions) {
         final Map<TopicPartition, Long> seekTimestamps = new HashMap<>();
         for (final Map.Entry<TopicPartition, Long> entry : windowedPartitionsRetention.entrySet()) {
             final TopicPartition partition = entry.getKey();
             final long retentionPeriod = entry.getValue();
-            final List<ConsumerRecord<byte[], byte[]>> records = polledRecords.records(partition);
-            if (!records.isEmpty()) {
-                final long latestTimestamp = records.get(0).timestamp();
+            final Long latestTimestamp = latestTimestamps.get(partition);
+            if (latestTimestamp != null) {
                 final long seekTimestamp = latestTimestamp - retentionPeriod;
                 if (seekTimestamp > 0) {
                     seekTimestamps.put(partition, seekTimestamp);
@@ -1171,6 +1297,24 @@ public class StoreChangelogReader implements ChangelogReader {
         }
     }
 
+    /** Arms the backoff for partitions the probe could not place, and clears it for those it did. */
+    private void recordProbeOutcomes(final Map<TopicPartition, Long> windowedPartitionsRetention,
+                                     final Set<TopicPartition> seekToBeginningPartitions) {
+        for (final TopicPartition partition : windowedPartitionsRetention.keySet()) {
+            if (seekToBeginningPartitions.contains(partition)) {
+                probeFailedAtMs.put(partition, time.milliseconds());
+            } else {
+                probeFailedAtMs.remove(partition);
+            }
+        }
+    }
+
+    /** A partition whose probe just fell back is left alone until the backoff expires. */
+    private boolean probeIsDue(final TopicPartition partition) {
+        final Long failedAt = probeFailedAtMs.get(partition);
+        return failedAt == null || time.milliseconds() - failedAt >= PROBE_RETRY_BACKOFF.toMillis();
+    }
+
     @Override
     public void unregister(final Collection<TopicPartition> revokedChangelogs) {
         unregister(revokedChangelogs, StandbyUpdateListener.SuspendReason.MIGRATED);
diff --git a/streams/src/test/java/org/apache/kafka/streams/processor/internals/StoreChangelogReaderTest.java b/streams/src/test/java/org/apache/kafka/streams/processor/internals/StoreChangelogReaderTest.java
index d3a38ea8cb4..e68a2302d0d 100644
--- a/streams/src/test/java/org/apache/kafka/streams/processor/internals/StoreChangelogReaderTest.java
+++ b/streams/src/test/java/org/apache/kafka/streams/processor/internals/StoreChangelogReaderTest.java
@@ -62,8 +62,10 @@ import org.mockito.junit.jupiter.MockitoSettings;
 import org.mockito.quality.Strictness;
 
 import java.time.Duration;
+import java.util.Collection;
 import java.util.Collections;
 import java.util.HashMap;
+import java.util.HashSet;
 import java.util.Map;
 import java.util.Optional;
 import java.util.Properties;
@@ -1506,6 +1508,596 @@ public class StoreChangelogReaderTest {
         }
     }
 
+    /**
+     * The first poll after assignment returns nothing and every record arrives from the next poll
+     * on. An empty poll only means the fetch has not landed, so giving up on it sends partitions
+     * to a log-start seek with no margin against retention.
+     */
+    @Test
+    public void shouldRetryProbePollBeforeFallingBackToLogStart() {
+        final long shortRetentionMs = Duration.ofSeconds(3).toMillis();
+        final long beginOffset = 900_000L;
+        final long logEndOffset = 1_000_000L;
+        final long seekTarget = 999_000L;
+        final int numPartitions = 12;      // more than one poll can plausibly serve at once
+
+        final TopicPartition[] tps = new TopicPartition[numPartitions];
+        final Map<TopicPartition, Long> begins = new HashMap<>();
+        final Map<TopicPartition, Long> ends = new HashMap<>();
+        for (int i = 0; i < numPartitions; i++) {
+            tps[i] = new TopicPartition(tp.topic(), i);
+            begins.put(tps[i], beginOffset);
+            ends.put(tps[i], logEndOffset);
+        }
+
+        // a position after restore reflects records since consumed, not where it was seeked, so
+        // seekToBeginning is the only unambiguous signal that the optimisation was abandoned
+        final Set<TopicPartition> seekedToBeginning = new HashSet<>();
+        final MockConsumer<byte[], byte[]> probeConsumer =
+            new MockConsumer<>(AutoOffsetResetStrategy.EARLIEST.name()) {
+                @Override
+                public synchronized Map<TopicPartition, OffsetAndTimestamp> offsetsForTimes(
+                        final Map<TopicPartition, Long> timestampsToSearch) {
+                    final Map<TopicPartition, OffsetAndTimestamp> result = new HashMap<>();
+                    timestampsToSearch.forEach((k, v) ->
+                        result.put(k, new OffsetAndTimestamp(seekTarget, v)));
+                    return result;
+                }
+
+                @Override
+                public synchronized void seekToBeginning(final Collection<TopicPartition> partitions) {
+                    seekedToBeginning.addAll(partitions);
+                    super.seekToBeginning(partitions);
+                }
+            };
+        probeConsumer.updateBeginningOffsets(begins);
+        probeConsumer.updateEndOffsets(ends);
+        adminClient.updateEndOffsets(ends);
+
+        // records can only be added once assigned, and earlier polls happen before that; the first
+        // poll after assignment delivers nothing, standing in for a fetch that has not landed
+        final int[] assignedPolls = {0};
+        for (int round = 0; round < numPartitions * 4; round++) {
+            probeConsumer.schedulePollTask(() -> {
+                if (!probeConsumer.assignment().contains(tps[0])) {
+                    return;
+                }
+                if (++assignedPolls[0] <= 1) {
+                    return;
+                }
+                for (final TopicPartition partition : tps) {
+                    probeConsumer.addRecord(new ConsumerRecord<>(
+                        partition.topic(), partition.partition(), logEndOffset - 1,
+                        10_000_000L, TimestampType.CREATE_TIME,
+                        0, 0, new byte[0], new byte[0], new RecordHeaders(), Optional.empty()));
+                }
+            });
+        }
+
+        final StoreChangelogReader probeReader = new StoreChangelogReader(
+            time, config, logContext, adminClient, probeConsumer, callback, standbyListener);
+
+        for (int i = 0; i < numPartitions; i++) {
+            final StateStoreMetadata meta = mock(StateStoreMetadata.class);
+            final ProcessorStateManager manager = mock(ProcessorStateManager.class);
+            final StateStore store = mock(StateStore.class);
+            when(meta.changelogPartition()).thenReturn(tps[i]);
+            when(meta.store()).thenReturn(store);
+            when(meta.offset()).thenReturn(null, 0L);   // no checkpoint, then a value once restoring
+            when(meta.retentionPeriod()).thenReturn(shortRetentionMs);
+            when(store.name()).thenReturn(storeName);
+            when(manager.storeMetadata(tps[i])).thenReturn(meta);
+            when(manager.taskType()).thenReturn(ACTIVE);
+            when(manager.taskId()).thenReturn(new TaskId(0, i));
+            probeReader.register(tps[i], manager);
+        }
+
+        final Map<TaskId, Task> probeTasks = new HashMap<>();
+        for (int i = 0; i < numPartitions; i++) {
+            probeTasks.put(new TaskId(0, i), mock(Task.class));
+        }
+        probeReader.restore(probeTasks);
+
+        assertEquals(Collections.emptySet(), seekedToBeginning,
+            "every partition has a 3s retention against a 100k-record log, so the optimisation "
+                + "should apply to all of them; these were abandoned on one empty poll");
+    }
+
+    /**
+     * One partition is answered per poll, so resolving all of them takes more polls than any fixed
+     * budget in the old design allowed. A budget that stops while partitions are still being served
+     * sends them to a log-start restore with no margin against retention.
+     */
+    @Test
+    public void shouldKeepPollingWhileTheWindowIsStillResolvingPartitions() {
+        final long shortRetentionMs = Duration.ofSeconds(3).toMillis();
+        final long beginOffset = 900_000L;
+        final long logEndOffset = 1_000_000L;
+        final long seekTarget = 999_000L;
+        final int numPartitions = 20;      // more polls than any fixed budget in the old design
+
+        final TopicPartition[] tps = new TopicPartition[numPartitions];
+        final Map<TopicPartition, Long> begins = new HashMap<>();
+        final Map<TopicPartition, Long> ends = new HashMap<>();
+        for (int i = 0; i < numPartitions; i++) {
+            tps[i] = new TopicPartition(tp.topic(), i);
+            begins.put(tps[i], beginOffset);
+            ends.put(tps[i], logEndOffset);
+        }
+
+        final Set<TopicPartition> seekedToBeginning = new HashSet<>();
+        final MockConsumer<byte[], byte[]> probeConsumer =
+            new MockConsumer<>(AutoOffsetResetStrategy.EARLIEST.name()) {
+                @Override
+                public synchronized Map<TopicPartition, OffsetAndTimestamp> offsetsForTimes(
+                        final Map<TopicPartition, Long> timestampsToSearch) {
+                    final Map<TopicPartition, OffsetAndTimestamp> result = new HashMap<>();
+                    timestampsToSearch.forEach((k, v) ->
+                        result.put(k, new OffsetAndTimestamp(seekTarget, v)));
+                    return result;
+                }
+
+                @Override
+                public synchronized void seekToBeginning(final Collection<TopicPartition> partitions) {
+                    seekedToBeginning.addAll(partitions);
+                    super.seekToBeginning(partitions);
+                }
+            };
+        probeConsumer.updateBeginningOffsets(begins);
+        probeConsumer.updateEndOffsets(ends);
+        adminClient.updateEndOffsets(ends);
+
+        // one partition per poll: the shape a shared max.poll.records budget produces when each
+        // window is large enough to fill a poll on its own
+        final int[] answered = {0};
+        for (int round = 0; round < numPartitions * 4; round++) {
+            probeConsumer.schedulePollTask(() -> {
+                if (!probeConsumer.assignment().contains(tps[0]) || answered[0] >= numPartitions) {
+                    return;
+                }
+                final TopicPartition partition = tps[answered[0]++];
+                probeConsumer.addRecord(new ConsumerRecord<>(
+                    partition.topic(), partition.partition(), logEndOffset - 1,
+                    10_000_000L, TimestampType.CREATE_TIME,
+                    0, 0, new byte[0], new byte[0], new RecordHeaders(), Optional.empty()));
+            });
+        }
+
+        final StoreChangelogReader probeReader = new StoreChangelogReader(
+            time, config, logContext, adminClient, probeConsumer, callback, standbyListener);
+
+        for (int i = 0; i < numPartitions; i++) {
+            final StateStoreMetadata meta = mock(StateStoreMetadata.class);
+            final ProcessorStateManager manager = mock(ProcessorStateManager.class);
+            final StateStore store = mock(StateStore.class);
+            when(meta.changelogPartition()).thenReturn(tps[i]);
+            when(meta.store()).thenReturn(store);
+            when(meta.offset()).thenReturn(null, 0L);   // no checkpoint, then a value once restoring
+            when(meta.retentionPeriod()).thenReturn(shortRetentionMs);
+            when(store.name()).thenReturn(storeName);
+            when(manager.storeMetadata(tps[i])).thenReturn(meta);
+            when(manager.taskType()).thenReturn(ACTIVE);
+            when(manager.taskId()).thenReturn(new TaskId(0, i));
+            probeReader.register(tps[i], manager);
+        }
+
+        final Map<TaskId, Task> probeTasks = new HashMap<>();
+        for (int i = 0; i < numPartitions; i++) {
+            probeTasks.put(new TaskId(0, i), mock(Task.class));
+        }
+        probeReader.restore(probeTasks);
+
+        assertEquals(Collections.emptySet(), seekedToBeginning,
+            "every partition answered the probe, just not all in the same poll; these were "
+                + "abandoned by a budget that stopped while they were still being served");
+    }
+
+    /**
+     * A poll that returns without waiting has given no fetch a chance to land, so a run of them is
+     * no more evidence than none. Here ten polls deliver nothing while the clock does not move,
+     * which must not be read as an empty window.
+     */
+    @Test
+    public void shouldNotGiveUpOnPollsThatHaveNotWaited() {
+        final long shortRetentionMs = Duration.ofSeconds(3).toMillis();
+        final long beginOffset = 900_000L;
+        final long logEndOffset = 1_000_000L;
+        final long seekTarget = 999_000L;
+        final int numPartitions = 6;
+        final int silentPolls = 10;        // well past PROBE_IDLE_POLLS, with time standing still
+
+        final TopicPartition[] tps = new TopicPartition[numPartitions];
+        final Map<TopicPartition, Long> begins = new HashMap<>();
+        final Map<TopicPartition, Long> ends = new HashMap<>();
+        for (int i = 0; i < numPartitions; i++) {
+            tps[i] = new TopicPartition(tp.topic(), i);
+            begins.put(tps[i], beginOffset);
+            ends.put(tps[i], logEndOffset);
+        }
+
+        final Set<TopicPartition> seekedToBeginning = new HashSet<>();
+        final MockConsumer<byte[], byte[]> probeConsumer =
+            new MockConsumer<>(AutoOffsetResetStrategy.EARLIEST.name()) {
+                @Override
+                public synchronized Map<TopicPartition, OffsetAndTimestamp> offsetsForTimes(
+                        final Map<TopicPartition, Long> timestampsToSearch) {
+                    final Map<TopicPartition, OffsetAndTimestamp> result = new HashMap<>();
+                    timestampsToSearch.forEach((k, v) ->
+                        result.put(k, new OffsetAndTimestamp(seekTarget, v)));
+                    return result;
+                }
+
+                @Override
+                public synchronized void seekToBeginning(final Collection<TopicPartition> partitions) {
+                    seekedToBeginning.addAll(partitions);
+                    super.seekToBeginning(partitions);
+                }
+            };
+        probeConsumer.updateBeginningOffsets(begins);
+        probeConsumer.updateEndOffsets(ends);
+        adminClient.updateEndOffsets(ends);
+
+        final int[] answered = {0};
+        for (int round = 0; round < 60; round++) {
+            probeConsumer.schedulePollTask(() -> {
+                if (!probeConsumer.assignment().contains(tps[0]) || ++answered[0] <= silentPolls) {
+                    return;
+                }
+                for (final TopicPartition partition : tps) {
+                    probeConsumer.addRecord(new ConsumerRecord<>(
+                        partition.topic(), partition.partition(), logEndOffset - 1,
+                        10_000_000L, TimestampType.CREATE_TIME,
+                        0, 0, new byte[0], new byte[0], new RecordHeaders(), Optional.empty()));
+                }
+            });
+        }
+
+        final StoreChangelogReader probeReader = new StoreChangelogReader(
+            time, config, logContext, adminClient, probeConsumer, callback, standbyListener);
+
+        for (int i = 0; i < numPartitions; i++) {
+            final StateStoreMetadata meta = mock(StateStoreMetadata.class);
+            final ProcessorStateManager manager = mock(ProcessorStateManager.class);
+            final StateStore store = mock(StateStore.class);
+            when(meta.changelogPartition()).thenReturn(tps[i]);
+            when(meta.store()).thenReturn(store);
+            when(meta.offset()).thenReturn(null, 0L);   // no checkpoint, then a value once restoring
+            when(meta.retentionPeriod()).thenReturn(shortRetentionMs);
+            when(store.name()).thenReturn(storeName);
+            when(manager.storeMetadata(tps[i])).thenReturn(meta);
+            when(manager.taskType()).thenReturn(ACTIVE);
+            when(manager.taskId()).thenReturn(new TaskId(0, i));
+            probeReader.register(tps[i], manager);
+        }
+
+        final Map<TaskId, Task> probeTasks = new HashMap<>();
+        for (int i = 0; i < numPartitions; i++) {
+            probeTasks.put(new TaskId(0, i), mock(Task.class));
+        }
+        probeReader.restore(probeTasks);
+
+        assertEquals(Collections.emptySet(), seekedToBeginning,
+            "no time passed while those polls came back empty, so none of them waited on a fetch; "
+                + "abandoning the window on that basis sends partitions to a log-start restore");
+    }
+
+    /**
+     * After a producer fence the restore consumer answers nothing for a while. Here twelve polls
+     * each block a full poll timeout and return empty before the window finally answers, which is
+     * shorter than the slowest probes measured on a soak, so none of it may be called an empty
+     * window.
+     */
+    @Test
+    public void shouldWaitOutAnUnreadyConsumerBeforeAbandoningTheWindow() {
+        final long shortRetentionMs = Duration.ofSeconds(3).toMillis();
+        final long beginOffset = 900_000L;
+        final long logEndOffset = 1_000_000L;
+        final long seekTarget = 999_000L;
+        final int numPartitions = 6;
+        final int unreadyPolls = 12;       // 1.2s at the default poll.ms, all of it fruitless
+
+        final TopicPartition[] tps = new TopicPartition[numPartitions];
+        final Map<TopicPartition, Long> begins = new HashMap<>();
+        final Map<TopicPartition, Long> ends = new HashMap<>();
+        for (int i = 0; i < numPartitions; i++) {
+            tps[i] = new TopicPartition(tp.topic(), i);
+            begins.put(tps[i], beginOffset);
+            ends.put(tps[i], logEndOffset);
+        }
+
+        final Set<TopicPartition> seekedToBeginning = new HashSet<>();
+        final MockConsumer<byte[], byte[]> probeConsumer =
+            new MockConsumer<>(AutoOffsetResetStrategy.EARLIEST.name()) {
+                @Override
+                public synchronized Map<TopicPartition, OffsetAndTimestamp> offsetsForTimes(
+                        final Map<TopicPartition, Long> timestampsToSearch) {
+                    final Map<TopicPartition, OffsetAndTimestamp> result = new HashMap<>();
+                    timestampsToSearch.forEach((k, v) ->
+                        result.put(k, new OffsetAndTimestamp(seekTarget, v)));
+                    return result;
+                }
+
+                @Override
+                public synchronized void seekToBeginning(final Collection<TopicPartition> partitions) {
+                    seekedToBeginning.addAll(partitions);
+                    super.seekToBeginning(partitions);
+                }
+            };
+        probeConsumer.updateBeginningOffsets(begins);
+        probeConsumer.updateEndOffsets(ends);
+        adminClient.updateEndOffsets(ends);
+
+        final long pollMs = config.getLong(StreamsConfig.POLL_MS_CONFIG);
+        final int[] answered = {0};
+        for (int round = 0; round < 60; round++) {
+            probeConsumer.schedulePollTask(() -> {
+                if (!probeConsumer.assignment().contains(tps[0])) {
+                    return;
+                }
+                if (++answered[0] <= unreadyPolls) {
+                    time.sleep(pollMs);      // the poll blocked its full timeout and found nothing
+                    return;
+                }
+                for (final TopicPartition partition : tps) {
+                    probeConsumer.addRecord(new ConsumerRecord<>(
+                        partition.topic(), partition.partition(), logEndOffset - 1,
+                        10_000_000L, TimestampType.CREATE_TIME,
+                        0, 0, new byte[0], new byte[0], new RecordHeaders(), Optional.empty()));
+                }
+            });
+        }
+
+        final StoreChangelogReader probeReader = new StoreChangelogReader(
+            time, config, logContext, adminClient, probeConsumer, callback, standbyListener);
+
+        for (int i = 0; i < numPartitions; i++) {
+            final StateStoreMetadata meta = mock(StateStoreMetadata.class);
+            final ProcessorStateManager manager = mock(ProcessorStateManager.class);
+            final StateStore store = mock(StateStore.class);
+            when(meta.changelogPartition()).thenReturn(tps[i]);
+            when(meta.store()).thenReturn(store);
+            when(meta.offset()).thenReturn(null, 0L);   // no checkpoint, then a value once restoring
+            when(meta.retentionPeriod()).thenReturn(shortRetentionMs);
+            when(store.name()).thenReturn(storeName);
+            when(manager.storeMetadata(tps[i])).thenReturn(meta);
+            when(manager.taskType()).thenReturn(ACTIVE);
+            when(manager.taskId()).thenReturn(new TaskId(0, i));
+            probeReader.register(tps[i], manager);
+        }
+
+        final Map<TaskId, Task> probeTasks = new HashMap<>();
+        for (int i = 0; i < numPartitions; i++) {
+            probeTasks.put(new TaskId(0, i), mock(Task.class));
+        }
+        probeReader.restore(probeTasks);
+
+        assertEquals(Collections.emptySet(), seekedToBeginning,
+            "the consumer was not ready to answer for 1.2s, which is inside the window the probe "
+                + "owes before it may conclude anything; these were abandoned early");
+    }
+
+    /**
+     * A task corrupted, wiped and re-registered with no offset would otherwise pay a full probe on
+     * every iteration. A probe that fell back is left alone until the backoff expires, which bounds
+     * a loop to one probe per interval without suppressing a probe that was working.
+     */
+    @Test
+    public void shouldBackOffProbingAPartitionWhoseProbeJustFailed() {
+        final long retentionMs = Duration.ofSeconds(3).toMillis();
+        final long endOffset = 1_000L;
+        final int[] probeRounds = {0};
+
+        final MockConsumer<byte[], byte[]> probeConsumer =
+            new MockConsumer<>(AutoOffsetResetStrategy.EARLIEST.name()) {
+                @Override
+                public synchronized Map<TopicPartition, Long> beginningOffsets(final Collection<TopicPartition> partitions) {
+                    probeRounds[0]++;      // only the probe looks these up
+                    return super.beginningOffsets(partitions);
+                }
+            };
+        probeConsumer.updateBeginningOffsets(Collections.singletonMap(tp, 0L));
+        probeConsumer.updateEndOffsets(Collections.singletonMap(tp, endOffset));
+        adminClient.updateEndOffsets(Collections.singletonMap(tp, endOffset));
+        // no records are ever scheduled, so no window can answer and every probe falls back
+
+        final StoreChangelogReader probeReader = new StoreChangelogReader(
+            time, config, logContext, adminClient, probeConsumer, callback, standbyListener);
+
+        final TaskId probeTaskId = new TaskId(0, 0);
+        final Map<TaskId, Task> probeTasks = Collections.singletonMap(probeTaskId, mock(Task.class));
+
+        for (int round = 0; round < 5; round++) {
+            registerRestoreAndRevoke(probeReader, probeTaskId, probeTasks, retentionMs);
+        }
+        assertEquals(1, probeRounds[0],
+            "the probe fell back, so re-registering in a loop should not probe again");
+
+        time.sleep(Duration.ofSeconds(60).toMillis());     // PROBE_RETRY_BACKOFF
+        registerRestoreAndRevoke(probeReader, probeTaskId, probeTasks, retentionMs);
+        assertEquals(2, probeRounds[0],
+            "once the backoff expires the partition is probed again, so a transient failure does "
+                + "not disable the optimisation for good");
+    }
+
+    private void registerRestoreAndRevoke(final StoreChangelogReader probeReader,
+                                          final TaskId probeTaskId,
+                                          final Map<TaskId, Task> probeTasks,
+                                          final long retentionMs) {
+        final StateStoreMetadata meta = mock(StateStoreMetadata.class);
+        final ProcessorStateManager manager = mock(ProcessorStateManager.class);
+        final StateStore store = mock(StateStore.class);
+        when(meta.changelogPartition()).thenReturn(tp);
+        when(meta.store()).thenReturn(store);
+        when(meta.offset()).thenReturn(null, 0L);
+        when(meta.retentionPeriod()).thenReturn(retentionMs);
+        when(store.name()).thenReturn(storeName);
+        when(manager.storeMetadata(tp)).thenReturn(meta);
+        when(manager.taskType()).thenReturn(ACTIVE);
+        when(manager.taskId()).thenReturn(probeTaskId);
+
+        probeReader.register(tp, manager);
+        probeReader.restore(probeTasks);
+        probeReader.unregister(Collections.singleton(tp));
+    }
+
+    /**
+     * A probe can also fail by the offset lookup timing out, which leaves through a catch rather
+     * than the normal path. That has to arm the backoff too, or a task looping on a slow broker
+     * re-probes on every iteration.
+     */
+    @Test
+    public void shouldBackOffWhenTheProbeFailsByTimeout() {
+        final long retentionMs = Duration.ofSeconds(3).toMillis();
+        final long endOffset = 1_000L;
+        final int[] lookups = {0};
+
+        final MockConsumer<byte[], byte[]> probeConsumer =
+            new MockConsumer<>(AutoOffsetResetStrategy.EARLIEST.name()) {
+                @Override
+                public synchronized Map<TopicPartition, Long> endOffsets(final Collection<TopicPartition> partitions) {
+                    lookups[0]++;
+                    throw new TimeoutException("timed out looking up end offsets");
+                }
+            };
+        probeConsumer.updateBeginningOffsets(Collections.singletonMap(tp, 0L));
+        probeConsumer.updateEndOffsets(Collections.singletonMap(tp, endOffset));
+        adminClient.updateEndOffsets(Collections.singletonMap(tp, endOffset));
+
+        final StoreChangelogReader probeReader = new StoreChangelogReader(
+            time, config, logContext, adminClient, probeConsumer, callback, standbyListener);
+
+        final TaskId probeTaskId = new TaskId(0, 0);
+        final Map<TaskId, Task> probeTasks = Collections.singletonMap(probeTaskId, mock(Task.class));
+
+        for (int round = 0; round < 4; round++) {
+            registerRestoreAndRevoke(probeReader, probeTaskId, probeTasks, retentionMs);
+        }
+
+        assertEquals(1, lookups[0],
+            "the probe failed by timeout, so re-registering in a loop should not probe again");
+    }
+
+    /**
+     * Only a probe that fell back arms the backoff. Suppressing a probe that was working would send
+     * the next restore to log start, which is what gets a partition lapped and corrupted in the
+     * first place -- the guard would sustain the loop it exists to bound.
+     */
+    @Test
+    public void shouldNotBackOffAfterAProbeThatSucceeded() {
+        final long retentionMs = Duration.ofSeconds(3).toMillis();
+        final long endOffset = 1_000L;
+        final int[] probeRounds = {0};
+
+        final MockConsumer<byte[], byte[]> probeConsumer =
+            new MockConsumer<>(AutoOffsetResetStrategy.EARLIEST.name()) {
+                @Override
+                public synchronized Map<TopicPartition, Long> beginningOffsets(final Collection<TopicPartition> partitions) {
+                    probeRounds[0]++;
+                    return super.beginningOffsets(partitions);
+                }
+
+                @Override
+                public synchronized Map<TopicPartition, OffsetAndTimestamp> offsetsForTimes(
+                        final Map<TopicPartition, Long> timestampsToSearch) {
+                    final Map<TopicPartition, OffsetAndTimestamp> result = new HashMap<>();
+                    timestampsToSearch.forEach((k, v) -> result.put(k, new OffsetAndTimestamp(1L, v)));
+                    return result;
+                }
+            };
+        probeConsumer.updateBeginningOffsets(Collections.singletonMap(tp, 0L));
+        probeConsumer.updateEndOffsets(Collections.singletonMap(tp, endOffset));
+        adminClient.updateEndOffsets(Collections.singletonMap(tp, endOffset));
+
+        for (int round = 0; round < 40; round++) {
+            probeConsumer.schedulePollTask(() -> {
+                if (probeConsumer.assignment().contains(tp)) {
+                    probeConsumer.addRecord(new ConsumerRecord<>(
+                        tp.topic(), tp.partition(), endOffset - 1, 10_000_000L, TimestampType.CREATE_TIME,
+                        0, 0, new byte[0], new byte[0], new RecordHeaders(), Optional.empty()));
+                }
+            });
+        }
+
+        final StoreChangelogReader probeReader = new StoreChangelogReader(
+            time, config, logContext, adminClient, probeConsumer, callback, standbyListener);
+
+        final TaskId probeTaskId = new TaskId(0, 0);
+        final Map<TaskId, Task> probeTasks = Collections.singletonMap(probeTaskId, mock(Task.class));
+
+        // back to back, with no time passing at all
+        registerRestoreAndRevoke(probeReader, probeTaskId, probeTasks, retentionMs);
+        registerRestoreAndRevoke(probeReader, probeTaskId, probeTasks, retentionMs);
+
+        assertEquals(2, probeRounds[0],
+            "the probe answered, so nothing should be held back on the next registration");
+    }
+
+    /**
+     * The newest timestamp sits in the middle of the window, so taking the first or the last record
+     * in offset order picks the wrong one. The probe estimates observed stream time, a maximum.
+     */
+    @Test
+    public void shouldSeekFromTheNewestTimestampInTheProbedWindow() {
+        final long retentionMs = Duration.ofSeconds(30).toMillis();
+        final long logEndOffset = 1_000L;
+        final long oldest = 500_000L;
+        final long newest = 900_000L;
+        final long middle = 700_000L;    // last in offset order, but not the newest
+
+        final Map<TopicPartition, Long> requested = new HashMap<>();
+        final MockConsumer<byte[], byte[]> probeConsumer =
+            new MockConsumer<>(AutoOffsetResetStrategy.EARLIEST.name()) {
+                @Override
+                public synchronized Map<TopicPartition, OffsetAndTimestamp> offsetsForTimes(
+                        final Map<TopicPartition, Long> timestampsToSearch) {
+                    requested.putAll(timestampsToSearch);
+                    final Map<TopicPartition, OffsetAndTimestamp> result = new HashMap<>();
+                    timestampsToSearch.forEach((k, v) -> result.put(k, new OffsetAndTimestamp(1L, v)));
+                    return result;
+                }
+            };
+        probeConsumer.updateBeginningOffsets(Collections.singletonMap(tp, 0L));
+        probeConsumer.updateEndOffsets(Collections.singletonMap(tp, logEndOffset));
+        adminClient.updateEndOffsets(Collections.singletonMap(tp, logEndOffset));
+
+        for (int round = 0; round < 8; round++) {
+            probeConsumer.schedulePollTask(() -> {
+                if (!probeConsumer.assignment().contains(tp)) {
+                    return;
+                }
+                long offset = logEndOffset - 3;
+                for (final long timestamp : new long[] {oldest, newest, middle}) {
+                    probeConsumer.addRecord(new ConsumerRecord<>(
+                        tp.topic(), tp.partition(), offset++, timestamp, TimestampType.CREATE_TIME,
+                        0, 0, new byte[0], new byte[0], new RecordHeaders(), Optional.empty()));
+                }
+            });
+        }
+
+        final StoreChangelogReader probeReader = new StoreChangelogReader(
+            time, config, logContext, adminClient, probeConsumer, callback, standbyListener);
+
+        final TaskId probeTaskId = new TaskId(0, 0);
+        final StateStoreMetadata meta = mock(StateStoreMetadata.class);
+        final ProcessorStateManager manager = mock(ProcessorStateManager.class);
+        final StateStore store = mock(StateStore.class);
+        when(meta.changelogPartition()).thenReturn(tp);
+        when(meta.store()).thenReturn(store);
+        when(meta.offset()).thenReturn(null, 0L);   // no checkpoint, then a value once restoring
+        when(meta.retentionPeriod()).thenReturn(retentionMs);
+        when(store.name()).thenReturn(storeName);
+        when(manager.storeMetadata(tp)).thenReturn(meta);
+        when(manager.taskType()).thenReturn(ACTIVE);
+        when(manager.taskId()).thenReturn(probeTaskId);
+        probeReader.register(tp, manager);
+
+        probeReader.restore(Collections.singletonMap(probeTaskId, mock(Task.class)));
+
+        assertEquals(newest - retentionMs, requested.get(tp).longValue(),
+            "the seek must be derived from the newest timestamp in the window (" + newest
+                + "), not the first or last record in offset order");
+    }
+
     @Test
     public void shouldSeekByTimestampForWindowedStoreWithoutCheckpoint() {
         final long retentionMs = Duration.ofHours(2).toMillis();


(kafka) 01/04: KAFKA-13499: Avoid restoring outdated records (#22115)

Posted by bb...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

bbejeck pushed a commit to branch 4.3
in repository https://gitbox.apache.org/repos/asf/kafka.git

commit a61e8a9b927cee0770ad32a191cf699f13de8cab
Author: gabriellefu <10...@users.noreply.github.com>
AuthorDate: Mon May 4 13:14:31 2026 -0400

    KAFKA-13499: Avoid restoring outdated records (#22115)
    
    1. Expose the retentionPeriod length to storeMetadata
    2. In prepareChangelogs(), switch it from always seektobeginning if
    checkpoint doesn't exist to seek to certain timestamp to avoid restoring
    outdated records.
    3. Change from [the ](https://github.com/apache/kafka/pull/21901):
    Instead of the wall clock, use the latest timestamp in the changelog as
    the latest time, and seek from the timestamp of
    latest_changelog_stamp_time-rention_period.
    
    Reviewers: TengYao Chi <fr...@apache.org>, Bill Bejeck
     <bb...@apache.org>
---
 .../processor/internals/ProcessorStateManager.java |  22 ++++
 .../processor/internals/StoreChangelogReader.java  | 115 ++++++++++++++++--
 ...stractDualSchemaRocksDBSegmentedBytesStore.java |   7 +-
 .../AbstractRocksDBSegmentedBytesStore.java        |   7 +-
 .../state/internals/InMemorySessionStore.java      |   7 +-
 .../state/internals/InMemoryWindowStore.java       |   7 +-
 .../state/internals/WithRetentionPeriod.java       |  21 ++++
 .../internals/StoreChangelogReaderTest.java        | 132 +++++++++++++++++++++
 8 files changed, 304 insertions(+), 14 deletions(-)

diff --git a/streams/src/main/java/org/apache/kafka/streams/processor/internals/ProcessorStateManager.java b/streams/src/main/java/org/apache/kafka/streams/processor/internals/ProcessorStateManager.java
index 71873c9abc2..6f7d4314259 100644
--- a/streams/src/main/java/org/apache/kafka/streams/processor/internals/ProcessorStateManager.java
+++ b/streams/src/main/java/org/apache/kafka/streams/processor/internals/ProcessorStateManager.java
@@ -37,6 +37,8 @@ import org.apache.kafka.streams.state.internals.CachedStateStore;
 import org.apache.kafka.streams.state.internals.LegacyCheckpointingStateStore;
 import org.apache.kafka.streams.state.internals.RecordConverter;
 import org.apache.kafka.streams.state.internals.TimeOrderedKeyValueBuffer;
+import org.apache.kafka.streams.state.internals.WithRetentionPeriod;
+import org.apache.kafka.streams.state.internals.WrappedStateStore;
 
 import org.slf4j.Logger;
 
@@ -105,6 +107,8 @@ public class ProcessorStateManager implements StateManager {
         // corrupted state store should not be included in checkpointing
         private boolean corrupted;
 
+        private final long retentionPeriod;
+
 
         private StateStoreMetadata(final StateStore stateStore,
                                    final CommitCallback commitCallback) {
@@ -115,6 +119,7 @@ public class ProcessorStateManager implements StateManager {
             this.changelogPartition = null;
             this.corrupted = false;
             this.offset = null;
+            this.retentionPeriod = -1L;
         }
 
         private StateStoreMetadata(final StateStore stateStore,
@@ -132,12 +137,24 @@ public class ProcessorStateManager implements StateManager {
             this.commitCallback = commitCallback;
             this.recordConverter = recordConverter;
             this.offset = null;
+            this.retentionPeriod = extractRetentionPeriod(stateStore);
         }
 
         private void setOffset(final Long offset) {
             this.offset = offset;
         }
 
+        private static long extractRetentionPeriod(final StateStore stateStore) {
+            StateStore current = stateStore;
+            while (current instanceof WrappedStateStore) {
+                current = ((WrappedStateStore<?, ?, ?>) current).wrapped();
+            }
+            if (current instanceof WithRetentionPeriod) {
+                return ((WithRetentionPeriod) current).retentionPeriod();
+            }
+            return -1L;
+        }
+
         // the offset is exposed to the changelog reader to determine if restoration is completed
         Long offset() {
             return this.offset;
@@ -147,6 +164,11 @@ public class ProcessorStateManager implements StateManager {
             return this.endOffset;
         }
 
+        // the retentionPeriod is exposed to the changelog reader for window restoration
+        long retentionPeriod() {
+            return retentionPeriod;
+        }
+
         public void setEndOffset(final Long endOffset) {
             this.endOffset = endOffset;
         }
diff --git a/streams/src/main/java/org/apache/kafka/streams/processor/internals/StoreChangelogReader.java b/streams/src/main/java/org/apache/kafka/streams/processor/internals/StoreChangelogReader.java
index baf51acf40d..05aec5eb8bf 100644
--- a/streams/src/main/java/org/apache/kafka/streams/processor/internals/StoreChangelogReader.java
+++ b/streams/src/main/java/org/apache/kafka/streams/processor/internals/StoreChangelogReader.java
@@ -25,6 +25,7 @@ import org.apache.kafka.clients.consumer.Consumer;
 import org.apache.kafka.clients.consumer.ConsumerRecord;
 import org.apache.kafka.clients.consumer.ConsumerRecords;
 import org.apache.kafka.clients.consumer.InvalidOffsetException;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
 import org.apache.kafka.common.IsolationLevel;
 import org.apache.kafka.common.KafkaException;
 import org.apache.kafka.common.TopicPartition;
@@ -995,7 +996,8 @@ public class StoreChangelogReader implements ChangelogReader {
     private void prepareChangelogs(final Map<TaskId, Task> tasks,
                                    final Set<ChangelogMetadata> newPartitionsToRestore) {
         // separate those who do not have the current offset loaded from checkpoint
-        final Set<TopicPartition> newPartitionsWithoutStartOffset = new HashSet<>();
+        final Set<TopicPartition> newSeekToBeginningPartitions = new HashSet<>();
+        final Map<TopicPartition, Long> newWindowedPartitionsRetention = new HashMap<>();
 
         for (final ChangelogMetadata changelogMetadata : newPartitionsToRestore) {
             final StateStoreMetadata storeMetadata = changelogMetadata.storeMetadata;
@@ -1012,18 +1014,18 @@ public class StoreChangelogReader implements ChangelogReader {
                 log.debug("Start restoring changelog partition {} from current offset {} to end offset {}.",
                     partition, currentOffset, recordEndOffset(endOffset));
             } else {
-                log.debug("Start restoring changelog partition {} from the beginning offset to end offset {} " +
-                    "since we cannot find current offset.", partition, recordEndOffset(endOffset));
-
-                newPartitionsWithoutStartOffset.add(partition);
+                final long retentionPeriod = storeMetadata.retentionPeriod();
+                if (retentionPeriod > 0 && retentionPeriod != Long.MAX_VALUE) {
+                    newWindowedPartitionsRetention.put(partition, retentionPeriod);
+                } else {
+                    log.debug("Start restoring changelog partition {} from the beginning offset to end offset {} " +
+                        "since we cannot find current offset.", partition, recordEndOffset(endOffset));
+                    newSeekToBeginningPartitions.add(partition);
+                }
             }
         }
 
-        // optimization: batch all seek-to-beginning offsets in a single request
-        //               seek is not a blocking call so there's nothing to capture
-        if (!newPartitionsWithoutStartOffset.isEmpty()) {
-            restoreConsumer.seekToBeginning(newPartitionsWithoutStartOffset);
-        }
+        seekNewPartitions(newWindowedPartitionsRetention, newSeekToBeginningPartitions);
 
         for (final ChangelogMetadata changelogMetadata : newPartitionsToRestore) {
             final StateStoreMetadata storeMetadata = changelogMetadata.storeMetadata;
@@ -1067,6 +1069,99 @@ public class StoreChangelogReader implements ChangelogReader {
         }
     }
 
+    private void seekNewPartitions(final Map<TopicPartition, Long> windowedPartitionsRetention,
+                                    final Set<TopicPartition> seekToBeginningPartitions) {
+        // Seek non-windowed partitions to beginning.
+        if (!seekToBeginningPartitions.isEmpty()) {
+            restoreConsumer.seekToBeginning(seekToBeginningPartitions);
+        }
+
+        // Try to optimize windowed partitions by seeking past expired data.
+        if (!windowedPartitionsRetention.isEmpty()) {
+            final Set<TopicPartition> allAssigned = restoreConsumer.assignment();
+            final Set<TopicPartition> previouslyPaused = new HashSet<>(restoreConsumer.paused());
+
+            try {
+                restoreConsumer.pause(allAssigned);
+                restoreConsumer.resume(windowedPartitionsRetention.keySet());
+
+                final Map<TopicPartition, Long> endOffsets =
+                    restoreConsumer.endOffsets(windowedPartitionsRetention.keySet());
+
+                for (final TopicPartition partition : windowedPartitionsRetention.keySet()) {
+                    final Long endOffset = endOffsets.get(partition);
+                    if (endOffset != null && endOffset > 0) {
+                        restoreConsumer.seek(partition, endOffset - 1);
+                    } else {
+                        restoreConsumer.seekToBeginning(Collections.singleton(partition));
+                        seekToBeginningPartitions.add(partition);
+                    }
+                }
+                windowedPartitionsRetention.keySet().removeAll(seekToBeginningPartitions);
+
+                final ConsumerRecords<byte[], byte[]> polledRecords = restoreConsumer.poll(pollTime);
+
+                seekByRetentionFromPolledRecords(polledRecords, windowedPartitionsRetention, seekToBeginningPartitions);
+            } catch (final TimeoutException e) {
+                log.debug("Could not seek by timestamp for changelog partitions {}, falling back to seek-to-beginning",
+                    windowedPartitionsRetention.keySet(), e);
+                seekToBeginningPartitions.addAll(windowedPartitionsRetention.keySet());
+            } catch (final KafkaException e) {
+                log.warn("Failed to seek by timestamp for changelog partitions {}, falling back to seek-to-beginning",
+                    windowedPartitionsRetention.keySet(), e);
+                seekToBeginningPartitions.addAll(windowedPartitionsRetention.keySet());
+            } finally {
+                restoreConsumer.pause(allAssigned);
+                final Set<TopicPartition> toResume = new HashSet<>(allAssigned);
+                toResume.removeAll(previouslyPaused);
+                if (!toResume.isEmpty()) {
+                    restoreConsumer.resume(toResume);
+                }
+            }
+        }
+
+        // Seek any windowed partitions that failed during the optimization back to the beginning.
+        // Their position was moved by seek+poll above.
+        if (!seekToBeginningPartitions.isEmpty()) {
+            restoreConsumer.seekToBeginning(seekToBeginningPartitions);
+        }
+    }
+
+    private void seekByRetentionFromPolledRecords(final ConsumerRecords<byte[], byte[]> polledRecords,
+                                                   final Map<TopicPartition, Long> windowedPartitionsRetention,
+                                                   final Set<TopicPartition> seekToBeginningPartitions) {
+        final Map<TopicPartition, Long> seekTimestamps = new HashMap<>();
+        for (final Map.Entry<TopicPartition, Long> entry : windowedPartitionsRetention.entrySet()) {
+            final TopicPartition partition = entry.getKey();
+            final long retentionPeriod = entry.getValue();
+            final List<ConsumerRecord<byte[], byte[]>> records = polledRecords.records(partition);
+            if (!records.isEmpty()) {
+                final long latestTimestamp = records.get(0).timestamp();
+                final long seekTimestamp = latestTimestamp - retentionPeriod;
+                if (seekTimestamp > 0) {
+                    seekTimestamps.put(partition, seekTimestamp);
+                    log.debug("Start restoring windowed changelog partition {} from stream-time-based timestamp {} " +
+                        "(maxStreamTime={}, retention={}).", partition, seekTimestamp, latestTimestamp, retentionPeriod);
+                    continue;
+                }
+            }
+            log.debug("Start restoring changelog partition {} from the beginning.", partition);
+            seekToBeginningPartitions.add(partition);
+        }
+
+        if (!seekTimestamps.isEmpty()) {
+            final Map<TopicPartition, OffsetAndTimestamp> offsetsByTimestamp =
+                restoreConsumer.offsetsForTimes(seekTimestamps);
+            offsetsByTimestamp.forEach((partition, offsetAndTimestamp) -> {
+                if (offsetAndTimestamp != null) {
+                    restoreConsumer.seek(partition, offsetAndTimestamp.offset());
+                } else {
+                    seekToBeginningPartitions.add(partition);
+                }
+            });
+        }
+    }
+
     @Override
     public void unregister(final Collection<TopicPartition> revokedChangelogs) {
         unregister(revokedChangelogs, StandbyUpdateListener.SuspendReason.MIGRATED);
diff --git a/streams/src/main/java/org/apache/kafka/streams/state/internals/AbstractDualSchemaRocksDBSegmentedBytesStore.java b/streams/src/main/java/org/apache/kafka/streams/state/internals/AbstractDualSchemaRocksDBSegmentedBytesStore.java
index 1633e80f015..a8802f9659c 100644
--- a/streams/src/main/java/org/apache/kafka/streams/state/internals/AbstractDualSchemaRocksDBSegmentedBytesStore.java
+++ b/streams/src/main/java/org/apache/kafka/streams/state/internals/AbstractDualSchemaRocksDBSegmentedBytesStore.java
@@ -46,7 +46,7 @@ import java.util.Optional;
 import static org.apache.kafka.streams.StreamsConfig.InternalConfig.IQ_CONSISTENCY_OFFSET_VECTOR_ENABLED;
 import static org.apache.kafka.streams.processor.internals.ProcessorContextUtils.asInternalProcessorContext;
 
-public abstract class AbstractDualSchemaRocksDBSegmentedBytesStore<S extends Segment> implements SegmentedBytesStore {
+public abstract class AbstractDualSchemaRocksDBSegmentedBytesStore<S extends Segment> implements SegmentedBytesStore, WithRetentionPeriod {
     private static final Logger LOG = LoggerFactory.getLogger(AbstractDualSchemaRocksDBSegmentedBytesStore.class);
 
     private final String name;
@@ -74,6 +74,11 @@ public abstract class AbstractDualSchemaRocksDBSegmentedBytesStore<S extends Seg
         this.retentionPeriod = retentionPeriod;
     }
 
+    @Override
+    public long retentionPeriod() {
+        return retentionPeriod;
+    }
+
     @Override
     public KeyValueIterator<Bytes, byte[]> all() {
 
diff --git a/streams/src/main/java/org/apache/kafka/streams/state/internals/AbstractRocksDBSegmentedBytesStore.java b/streams/src/main/java/org/apache/kafka/streams/state/internals/AbstractRocksDBSegmentedBytesStore.java
index dc8756c697d..d85c312499d 100644
--- a/streams/src/main/java/org/apache/kafka/streams/state/internals/AbstractRocksDBSegmentedBytesStore.java
+++ b/streams/src/main/java/org/apache/kafka/streams/state/internals/AbstractRocksDBSegmentedBytesStore.java
@@ -48,7 +48,7 @@ import java.util.Map;
 import static org.apache.kafka.streams.StreamsConfig.InternalConfig.IQ_CONSISTENCY_OFFSET_VECTOR_ENABLED;
 import static org.apache.kafka.streams.processor.internals.ProcessorContextUtils.asInternalProcessorContext;
 
-public class AbstractRocksDBSegmentedBytesStore<S extends Segment> implements SegmentedBytesStore {
+public class AbstractRocksDBSegmentedBytesStore<S extends Segment> implements SegmentedBytesStore, WithRetentionPeriod {
     private static final Logger LOG = LoggerFactory.getLogger(AbstractRocksDBSegmentedBytesStore.class);
 
     private final String name;
@@ -73,6 +73,11 @@ public class AbstractRocksDBSegmentedBytesStore<S extends Segment> implements Se
         this.segments = segments;
     }
 
+    @Override
+    public long retentionPeriod() {
+        return retentionPeriod;
+    }
+
     @Override
     public KeyValueIterator<Bytes, byte[]> fetch(final Bytes key,
                                                  final long from,
diff --git a/streams/src/main/java/org/apache/kafka/streams/state/internals/InMemorySessionStore.java b/streams/src/main/java/org/apache/kafka/streams/state/internals/InMemorySessionStore.java
index 667bd245b22..26333453d9c 100644
--- a/streams/src/main/java/org/apache/kafka/streams/state/internals/InMemorySessionStore.java
+++ b/streams/src/main/java/org/apache/kafka/streams/state/internals/InMemorySessionStore.java
@@ -54,7 +54,7 @@ import java.util.concurrent.ConcurrentSkipListMap;
 
 import static org.apache.kafka.streams.StreamsConfig.InternalConfig.IQ_CONSISTENCY_OFFSET_VECTOR_ENABLED;
 
-public class InMemorySessionStore implements SessionStore<Bytes, byte[]> {
+public class InMemorySessionStore implements SessionStore<Bytes, byte[]>, WithRetentionPeriod {
 
     private static final Logger LOG = LoggerFactory.getLogger(InMemorySessionStore.class);
 
@@ -91,6 +91,11 @@ public class InMemorySessionStore implements SessionStore<Bytes, byte[]> {
         this.position = Position.emptyPosition();
     }
 
+    @Override
+    public long retentionPeriod() {
+        return retentionPeriod;
+    }
+
     @Override
     public String name() {
         return name;
diff --git a/streams/src/main/java/org/apache/kafka/streams/state/internals/InMemoryWindowStore.java b/streams/src/main/java/org/apache/kafka/streams/state/internals/InMemoryWindowStore.java
index 7aaa383ae04..d1716b0d014 100644
--- a/streams/src/main/java/org/apache/kafka/streams/state/internals/InMemoryWindowStore.java
+++ b/streams/src/main/java/org/apache/kafka/streams/state/internals/InMemoryWindowStore.java
@@ -59,7 +59,7 @@ import static org.apache.kafka.streams.state.internals.WindowKeySchema.extractSt
 import static org.apache.kafka.streams.state.internals.WindowKeySchema.extractStoreTimestamp;
 
 
-public class InMemoryWindowStore implements WindowStore<Bytes, byte[]> {
+public class InMemoryWindowStore implements WindowStore<Bytes, byte[]>, WithRetentionPeriod {
 
     private static final Logger LOG = LoggerFactory.getLogger(InMemoryWindowStore.class);
     private static final int SEQNUM_SIZE = 4;
@@ -95,6 +95,11 @@ public class InMemoryWindowStore implements WindowStore<Bytes, byte[]> {
         this.position = Position.emptyPosition();
     }
 
+    @Override
+    public long retentionPeriod() {
+        return retentionPeriod;
+    }
+
     @Override
     public String name() {
         return name;
diff --git a/streams/src/main/java/org/apache/kafka/streams/state/internals/WithRetentionPeriod.java b/streams/src/main/java/org/apache/kafka/streams/state/internals/WithRetentionPeriod.java
new file mode 100644
index 00000000000..44dee28eafa
--- /dev/null
+++ b/streams/src/main/java/org/apache/kafka/streams/state/internals/WithRetentionPeriod.java
@@ -0,0 +1,21 @@
+/*
+ * 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.kafka.streams.state.internals;
+
+public interface WithRetentionPeriod {
+    long retentionPeriod();
+}
diff --git a/streams/src/test/java/org/apache/kafka/streams/processor/internals/StoreChangelogReaderTest.java b/streams/src/test/java/org/apache/kafka/streams/processor/internals/StoreChangelogReaderTest.java
index 56eb4c7d481..d3a38ea8cb4 100644
--- a/streams/src/test/java/org/apache/kafka/streams/processor/internals/StoreChangelogReaderTest.java
+++ b/streams/src/test/java/org/apache/kafka/streams/processor/internals/StoreChangelogReaderTest.java
@@ -27,11 +27,14 @@ import org.apache.kafka.clients.admin.OffsetSpec;
 import org.apache.kafka.clients.consumer.ConsumerRecord;
 import org.apache.kafka.clients.consumer.MockConsumer;
 import org.apache.kafka.clients.consumer.OffsetAndMetadata;
+import org.apache.kafka.clients.consumer.OffsetAndTimestamp;
 import org.apache.kafka.clients.consumer.internals.AutoOffsetResetStrategy;
 import org.apache.kafka.common.KafkaException;
 import org.apache.kafka.common.PartitionInfo;
 import org.apache.kafka.common.TopicPartition;
 import org.apache.kafka.common.errors.TimeoutException;
+import org.apache.kafka.common.header.internals.RecordHeaders;
+import org.apache.kafka.common.record.TimestampType;
 import org.apache.kafka.common.utils.LogCaptureAppender;
 import org.apache.kafka.common.utils.LogContext;
 import org.apache.kafka.common.utils.MockTime;
@@ -60,7 +63,9 @@ import org.mockito.quality.Strictness;
 
 import java.time.Duration;
 import java.util.Collections;
+import java.util.HashMap;
 import java.util.Map;
+import java.util.Optional;
 import java.util.Properties;
 import java.util.Set;
 import java.util.concurrent.atomic.AtomicBoolean;
@@ -1501,6 +1506,133 @@ public class StoreChangelogReaderTest {
         }
     }
 
+    @Test
+    public void shouldSeekByTimestampForWindowedStoreWithoutCheckpoint() {
+        final long retentionMs = Duration.ofHours(2).toMillis();
+        final long offsetForTimestamp = 42L;
+        final long latestRecordTimestamp = 10_000_000L;
+        final long endOffset = 100L;
+
+        final MockConsumer<byte[], byte[]> timestampConsumer = new MockConsumer<>(AutoOffsetResetStrategy.EARLIEST.name()) {
+            @Override
+            public synchronized Map<TopicPartition, OffsetAndTimestamp> offsetsForTimes(final Map<TopicPartition, Long> timestampsToSearch) {
+                final Map<TopicPartition, OffsetAndTimestamp> result = new HashMap<>();
+                timestampsToSearch.forEach((key, value) -> result.put(key, new OffsetAndTimestamp(offsetForTimestamp, value)));
+                return result;
+            }
+        };
+
+        final StateStoreMetadata windowStoreMetadata = mock(StateStoreMetadata.class);
+        final ProcessorStateManager windowStateManager = mock(ProcessorStateManager.class);
+        final StateStore windowStore = mock(StateStore.class);
+        when(windowStoreMetadata.changelogPartition()).thenReturn(tp);
+        when(windowStoreMetadata.store()).thenReturn(windowStore);
+        when(windowStoreMetadata.offset()).thenReturn(null);
+        when(windowStoreMetadata.retentionPeriod()).thenReturn(retentionMs);
+        when(windowStore.name()).thenReturn(storeName);
+        when(windowStateManager.storeMetadata(tp)).thenReturn(windowStoreMetadata);
+        when(windowStateManager.taskType()).thenReturn(ACTIVE);
+
+        final TaskId taskId = new TaskId(0, 0);
+        when(windowStateManager.taskId()).thenReturn(taskId);
+
+        timestampConsumer.updateBeginningOffsets(Collections.singletonMap(tp, 0L));
+        timestampConsumer.updateEndOffsets(Collections.singletonMap(tp, endOffset));
+        adminClient.updateEndOffsets(Collections.singletonMap(tp, endOffset));
+
+        // schedule adding the record during poll, after the partition is assigned
+        timestampConsumer.schedulePollTask(() -> timestampConsumer.addRecord(new ConsumerRecord<>(
+            tp.topic(), tp.partition(), endOffset - 1,
+            latestRecordTimestamp, TimestampType.CREATE_TIME,
+            0, 0, new byte[0], new byte[0],
+            new RecordHeaders(), Optional.empty())));
+
+        final StoreChangelogReader reader =
+            new StoreChangelogReader(time, config, logContext, adminClient, timestampConsumer, callback, standbyListener);
+
+        reader.register(tp, windowStateManager);
+        reader.restore(Collections.singletonMap(taskId, mock(Task.class)));
+
+        assertEquals(offsetForTimestamp, timestampConsumer.position(tp), "The consumer should be seeked to the offset returned by offsetsForTimes, not to the beginning");
+    }
+
+    @Test
+    public void shouldSeekToBeginningWhenBrokerReturnsNullForOffsetsForTimes() {
+        final long retentionMs = Duration.ofHours(2).toMillis();
+        final long latestRecordTimestamp = 10_000_000L;
+        final long endOffset = 100L;
+
+        final MockConsumer<byte[], byte[]> timestampConsumer = new MockConsumer<>(AutoOffsetResetStrategy.EARLIEST.name()) {
+            @Override
+            public synchronized Map<TopicPartition, OffsetAndTimestamp> offsetsForTimes(final Map<TopicPartition, Long> timestampsToSearch) {
+                final Map<TopicPartition, OffsetAndTimestamp> result = new HashMap<>();
+                timestampsToSearch.forEach((key, value) -> result.put(key, null));
+                return result;
+            }
+        };
+
+        final StateStoreMetadata windowStoreMetadata = mock(StateStoreMetadata.class);
+        final ProcessorStateManager windowStateManager = mock(ProcessorStateManager.class);
+        final StateStore windowStore = mock(StateStore.class);
+        when(windowStoreMetadata.changelogPartition()).thenReturn(tp);
+        when(windowStoreMetadata.store()).thenReturn(windowStore);
+        when(windowStoreMetadata.offset()).thenReturn(null);
+        when(windowStoreMetadata.retentionPeriod()).thenReturn(retentionMs);
+        when(windowStore.name()).thenReturn(storeName);
+        when(windowStateManager.storeMetadata(tp)).thenReturn(windowStoreMetadata);
+        when(windowStateManager.taskType()).thenReturn(ACTIVE);
+
+        final TaskId taskId = new TaskId(0, 0);
+        when(windowStateManager.taskId()).thenReturn(taskId);
+
+        timestampConsumer.updateBeginningOffsets(Collections.singletonMap(tp, 0L));
+        timestampConsumer.updateEndOffsets(Collections.singletonMap(tp, endOffset));
+        adminClient.updateEndOffsets(Collections.singletonMap(tp, endOffset));
+
+        // schedule adding the record during poll, after the partition is assigned
+        timestampConsumer.schedulePollTask(() -> timestampConsumer.addRecord(new ConsumerRecord<>(
+            tp.topic(), tp.partition(), endOffset - 1,
+            latestRecordTimestamp, TimestampType.CREATE_TIME,
+            0, 0, new byte[0], new byte[0],
+            new RecordHeaders(), Optional.empty())));
+
+        final StoreChangelogReader reader =
+            new StoreChangelogReader(time, config, logContext, adminClient, timestampConsumer, callback, standbyListener);
+
+        reader.register(tp, windowStateManager);
+        reader.restore(Collections.singletonMap(taskId, mock(Task.class)));
+
+        assertEquals(0L, timestampConsumer.position(tp), "When broker returns null, should fall back to seeking to the beginning");
+    }
+
+    @Test
+    public void shouldSeekToBeginningForNonWindowedStoreWithoutCheckpoint() {
+        final StateStoreMetadata kvStoreMetadata = mock(StateStoreMetadata.class);
+        final ProcessorStateManager kvStateManager = mock(ProcessorStateManager.class);
+        final StateStore kvStore = mock(StateStore.class);
+        when(kvStoreMetadata.changelogPartition()).thenReturn(tp);
+        when(kvStoreMetadata.store()).thenReturn(kvStore);
+        when(kvStoreMetadata.offset()).thenReturn(null);
+        when(kvStoreMetadata.retentionPeriod()).thenReturn(-1L);
+        when(kvStore.name()).thenReturn(storeName);
+        when(kvStateManager.storeMetadata(tp)).thenReturn(kvStoreMetadata);
+        when(kvStateManager.taskType()).thenReturn(ACTIVE);
+
+        final TaskId taskId = new TaskId(0, 0);
+        when(kvStateManager.taskId()).thenReturn(taskId);
+
+        consumer.updateBeginningOffsets(Collections.singletonMap(tp, 0L));
+        adminClient.updateEndOffsets(Collections.singletonMap(tp, 100L));
+
+        final StoreChangelogReader reader =
+            new StoreChangelogReader(time, config, logContext, adminClient, consumer, callback, standbyListener);
+
+        reader.register(tp, kvStateManager);
+        reader.restore(Collections.singletonMap(taskId, mock(Task.class)));
+
+        assertEquals(0L, consumer.position(tp), "Non-windowed store should seek to beginning, not by timestamp");
+    }
+
     private void assignPartition(final long messages,
                                  final TopicPartition topicPartition) {
         consumer.updatePartitions(


(kafka) 02/04: KAFKA-20875: Headers window store adapters must expose the retention they wrap (#23037)

Posted by bb...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

bbejeck pushed a commit to branch 4.3
in repository https://gitbox.apache.org/repos/asf/kafka.git

commit fb7279ad34a13a33ffd35791087afc8f76f01c3b
Author: Alan Lau <72...@users.noreply.github.com>
AuthorDate: Tue Aug 11 13:06:18 2026 -0400

    KAFKA-20875: Headers window store adapters must expose the retention they wrap (#23037)
    
    issue: https://issues.apache.org/jira/browse/KAFKA-20875
    
    `PlainToHeadersWindowStoreAdapter` and
    `TimestampedToHeadersWindowStoreAdapter` hold the  store they wrap in a
    field rather than participating in the `WrappedStateStore` chain, so
    `ProcessorStateManager.StateStoreMetadata.extractRetentionPeriod` —
    which finds a store's  retention by unwrapping to the innermost layer —
    terminates on the adapter and resolves -1.
    
    A -1 fails the windowed restore gate `retentionPeriod > 0 &&
    retentionPeriod != Long.MAX_VALUE`,  so the restore seeks the beginning
    of the changelog rather than skipping data the store would  discard
    anyway. On a changelog with delete retention that means starting at the
    offset  retention is deleting from, with no margin against being lapped.
    
    Each adapter now implements `WithRetentionPeriod` and unwraps its own
    delegate.
    
    Reviewers: Bill Bejeck <bb...@apache.org>
---
 .../processor/internals/ProcessorStateManager.java | 14 +---
 .../processor/internals/StoreChangelogReader.java  |  9 +++
 .../PlainToHeadersWindowStoreAdapter.java          | 13 +++-
 .../internals/SessionToHeadersStoreAdapter.java    |  9 ++-
 .../TimestampedToHeadersWindowStoreAdapter.java    | 13 +++-
 .../WindowToTimestampedWindowByteStoreAdapter.java |  9 ++-
 .../state/internals/WithRetentionPeriod.java       | 17 +++++
 .../PlainToHeadersWindowStoreAdapterTest.java      |  8 ++
 .../SessionToHeadersStoreAdapterTest.java          | 17 +++++
 ...TimestampedToHeadersWindowStoreAdapterTest.java |  8 ++
 .../TimestampedWindowStoreBuilderTest.java         | 27 +++++++
 .../state/internals/WithRetentionPeriodTest.java   | 88 ++++++++++++++++++++++
 12 files changed, 215 insertions(+), 17 deletions(-)

diff --git a/streams/src/main/java/org/apache/kafka/streams/processor/internals/ProcessorStateManager.java b/streams/src/main/java/org/apache/kafka/streams/processor/internals/ProcessorStateManager.java
index 6f7d4314259..8ab386a6709 100644
--- a/streams/src/main/java/org/apache/kafka/streams/processor/internals/ProcessorStateManager.java
+++ b/streams/src/main/java/org/apache/kafka/streams/processor/internals/ProcessorStateManager.java
@@ -38,7 +38,6 @@ import org.apache.kafka.streams.state.internals.LegacyCheckpointingStateStore;
 import org.apache.kafka.streams.state.internals.RecordConverter;
 import org.apache.kafka.streams.state.internals.TimeOrderedKeyValueBuffer;
 import org.apache.kafka.streams.state.internals.WithRetentionPeriod;
-import org.apache.kafka.streams.state.internals.WrappedStateStore;
 
 import org.slf4j.Logger;
 
@@ -137,24 +136,13 @@ public class ProcessorStateManager implements StateManager {
             this.commitCallback = commitCallback;
             this.recordConverter = recordConverter;
             this.offset = null;
-            this.retentionPeriod = extractRetentionPeriod(stateStore);
+            this.retentionPeriod = WithRetentionPeriod.resolveRetentionPeriod(stateStore);
         }
 
         private void setOffset(final Long offset) {
             this.offset = offset;
         }
 
-        private static long extractRetentionPeriod(final StateStore stateStore) {
-            StateStore current = stateStore;
-            while (current instanceof WrappedStateStore) {
-                current = ((WrappedStateStore<?, ?, ?>) current).wrapped();
-            }
-            if (current instanceof WithRetentionPeriod) {
-                return ((WithRetentionPeriod) current).retentionPeriod();
-            }
-            return -1L;
-        }
-
         // the offset is exposed to the changelog reader to determine if restoration is completed
         Long offset() {
             return this.offset;
diff --git a/streams/src/main/java/org/apache/kafka/streams/processor/internals/StoreChangelogReader.java b/streams/src/main/java/org/apache/kafka/streams/processor/internals/StoreChangelogReader.java
index 05aec5eb8bf..e634aae279b 100644
--- a/streams/src/main/java/org/apache/kafka/streams/processor/internals/StoreChangelogReader.java
+++ b/streams/src/main/java/org/apache/kafka/streams/processor/internals/StoreChangelogReader.java
@@ -38,9 +38,12 @@ import org.apache.kafka.streams.errors.StreamsException;
 import org.apache.kafka.streams.errors.TaskCorruptedException;
 import org.apache.kafka.streams.processor.StandbyUpdateListener;
 import org.apache.kafka.streams.processor.StateRestoreListener;
+import org.apache.kafka.streams.processor.StateStore;
 import org.apache.kafka.streams.processor.TaskId;
 import org.apache.kafka.streams.processor.internals.ProcessorStateManager.StateStoreMetadata;
 import org.apache.kafka.streams.processor.internals.Task.TaskType;
+import org.apache.kafka.streams.state.SessionStore;
+import org.apache.kafka.streams.state.WindowStore;
 import org.apache.kafka.streams.state.internals.MeteredStateStore;
 
 import org.slf4j.Logger;
@@ -1018,6 +1021,12 @@ public class StoreChangelogReader implements ChangelogReader {
                 if (retentionPeriod > 0 && retentionPeriod != Long.MAX_VALUE) {
                     newWindowedPartitionsRetention.put(partition, retentionPeriod);
                 } else {
+                    final StateStore store = storeMetadata.store();
+                    if (store instanceof WindowStore || store instanceof SessionStore) {
+                        log.warn("Windowed store {} reported no usable retention period ({}), so changelog " +
+                            "partition {} is restored in full rather than skipping expired data.",
+                            store.name(), retentionPeriod, partition);
+                    }
                     log.debug("Start restoring changelog partition {} from the beginning offset to end offset {} " +
                         "since we cannot find current offset.", partition, recordEndOffset(endOffset));
                     newSeekToBeginningPartitions.add(partition);
diff --git a/streams/src/main/java/org/apache/kafka/streams/state/internals/PlainToHeadersWindowStoreAdapter.java b/streams/src/main/java/org/apache/kafka/streams/state/internals/PlainToHeadersWindowStoreAdapter.java
index a463dbc97f2..023aaa52499 100644
--- a/streams/src/main/java/org/apache/kafka/streams/state/internals/PlainToHeadersWindowStoreAdapter.java
+++ b/streams/src/main/java/org/apache/kafka/streams/state/internals/PlainToHeadersWindowStoreAdapter.java
@@ -55,7 +55,7 @@ import static org.apache.kafka.streams.state.internals.Utils.rawPlainValue;
  *   <li>Read: {@code [value]} → {@code [headers][timestamp][value]} (add empty headers and timestamp=-1)</li>
  * </ul>
  */
-public class PlainToHeadersWindowStoreAdapter implements WindowStore<Bytes, byte[]> {
+public class PlainToHeadersWindowStoreAdapter implements WindowStore<Bytes, byte[]>, WithRetentionPeriod {
     private final WindowStore<Bytes, byte[]> store;
 
     public PlainToHeadersWindowStoreAdapter(final WindowStore<Bytes, byte[]> store) {
@@ -68,6 +68,17 @@ public class PlainToHeadersWindowStoreAdapter implements WindowStore<Bytes, byte
         this.store = store;
     }
 
+    /**
+     * Report the retention of the store being adapted. This adapter holds its delegate in a private
+     * field rather than as a {@link WrappedStateStore}, so {@code extractRetentionPeriod}'s unwrap
+     * walk terminates here; without this it resolves -1 and the KAFKA-13499 windowed-restore
+     * optimisation is silently skipped for every store behind the adapter.
+     */
+    @Override
+    public long retentionPeriod() {
+        return WithRetentionPeriod.resolveRetentionPeriod(store);
+    }
+
     @Override
     public void put(final Bytes key, final byte[] valueWithTimestampAndHeaders, final long windowStartTimestamp) {
         store.put(key, rawPlainValue(valueWithTimestampAndHeaders), windowStartTimestamp);
diff --git a/streams/src/main/java/org/apache/kafka/streams/state/internals/SessionToHeadersStoreAdapter.java b/streams/src/main/java/org/apache/kafka/streams/state/internals/SessionToHeadersStoreAdapter.java
index db753e52bbe..af89603a670 100644
--- a/streams/src/main/java/org/apache/kafka/streams/state/internals/SessionToHeadersStoreAdapter.java
+++ b/streams/src/main/java/org/apache/kafka/streams/state/internals/SessionToHeadersStoreAdapter.java
@@ -53,9 +53,16 @@ import static org.apache.kafka.streams.state.HeadersBytesStore.convertToHeaderFo
  * @see SessionToHeadersIteratorAdapter
  */
 @SuppressWarnings("unchecked")
-public class SessionToHeadersStoreAdapter implements SessionStore<Bytes, byte[]> {
+public class SessionToHeadersStoreAdapter implements SessionStore<Bytes, byte[]>, WithRetentionPeriod {
     final SessionStore<Bytes, byte[]> store;
 
+    // the delegate is held in a field rather than as a WrappedStateStore, so an unwrap walk
+    // terminates here; without this the windowed restore optimisation resolves -1 and is skipped
+    @Override
+    public long retentionPeriod() {
+        return WithRetentionPeriod.resolveRetentionPeriod(store);
+    }
+
     SessionToHeadersStoreAdapter(final SessionStore<Bytes, byte[]> store) {
         if (!store.persistent()) {
             throw new IllegalArgumentException("Provided store must be a persistent store, but it is not.");
diff --git a/streams/src/main/java/org/apache/kafka/streams/state/internals/TimestampedToHeadersWindowStoreAdapter.java b/streams/src/main/java/org/apache/kafka/streams/state/internals/TimestampedToHeadersWindowStoreAdapter.java
index 2b054532a6b..5992b0f0333 100644
--- a/streams/src/main/java/org/apache/kafka/streams/state/internals/TimestampedToHeadersWindowStoreAdapter.java
+++ b/streams/src/main/java/org/apache/kafka/streams/state/internals/TimestampedToHeadersWindowStoreAdapter.java
@@ -57,9 +57,20 @@ import static org.apache.kafka.streams.state.HeadersBytesStore.convertToHeaderFo
  *   <li>Read: {@code [timestamp][value]} → {@code [headers][timestamp][value]} (add empty headers)</li>
  * </ul>
  */
-public class TimestampedToHeadersWindowStoreAdapter implements WindowStore<Bytes, byte[]> {
+public class TimestampedToHeadersWindowStoreAdapter implements WindowStore<Bytes, byte[]>, WithRetentionPeriod {
     final WindowStore<Bytes, byte[]> store;
 
+    /**
+     * Report the retention of the store being adapted. This adapter holds its delegate in a field
+     * rather than as a {@link WrappedStateStore}, so {@code extractRetentionPeriod}'s unwrap walk
+     * terminates here; without this it resolves -1 and the windowed restore optimisation is
+     * silently skipped for every store behind the adapter.
+     */
+    @Override
+    public long retentionPeriod() {
+        return WithRetentionPeriod.resolveRetentionPeriod(store);
+    }
+
     public TimestampedToHeadersWindowStoreAdapter(final WindowStore<Bytes, byte[]> store) {
         if (!store.persistent()) {
             throw new IllegalArgumentException("Provided store must be a persistent store, but it is not.");
diff --git a/streams/src/main/java/org/apache/kafka/streams/state/internals/WindowToTimestampedWindowByteStoreAdapter.java b/streams/src/main/java/org/apache/kafka/streams/state/internals/WindowToTimestampedWindowByteStoreAdapter.java
index 5a7f05c1b2b..ce04513188d 100644
--- a/streams/src/main/java/org/apache/kafka/streams/state/internals/WindowToTimestampedWindowByteStoreAdapter.java
+++ b/streams/src/main/java/org/apache/kafka/streams/state/internals/WindowToTimestampedWindowByteStoreAdapter.java
@@ -36,9 +36,16 @@ import java.util.Map;
 import static org.apache.kafka.streams.state.TimestampedBytesStore.convertToTimestampedFormat;
 import static org.apache.kafka.streams.state.internals.ValueAndTimestampDeserializer.rawValue;
 
-public class WindowToTimestampedWindowByteStoreAdapter implements WindowStore<Bytes, byte[]> {
+public class WindowToTimestampedWindowByteStoreAdapter implements WindowStore<Bytes, byte[]>, WithRetentionPeriod {
     final WindowStore<Bytes, byte[]> store;
 
+    // the delegate is held in a field rather than as a WrappedStateStore, so an unwrap walk
+    // terminates here; without this the windowed restore optimisation resolves -1 and is skipped
+    @Override
+    public long retentionPeriod() {
+        return WithRetentionPeriod.resolveRetentionPeriod(store);
+    }
+
     WindowToTimestampedWindowByteStoreAdapter(final WindowStore<Bytes, byte[]> store) {
         if (!store.persistent()) {
             throw new IllegalArgumentException("Provided store must be a persistent store, but it is not.");
diff --git a/streams/src/main/java/org/apache/kafka/streams/state/internals/WithRetentionPeriod.java b/streams/src/main/java/org/apache/kafka/streams/state/internals/WithRetentionPeriod.java
index 44dee28eafa..ba3ef5237fd 100644
--- a/streams/src/main/java/org/apache/kafka/streams/state/internals/WithRetentionPeriod.java
+++ b/streams/src/main/java/org/apache/kafka/streams/state/internals/WithRetentionPeriod.java
@@ -16,6 +16,23 @@
  */
 package org.apache.kafka.streams.state.internals;
 
+import org.apache.kafka.streams.processor.StateStore;
+
 public interface WithRetentionPeriod {
     long retentionPeriod();
+
+    /**
+     * Unwrap to the innermost store and return its retention, or -1 if it does not report one.
+     * Stores that hold their delegate in a field rather than as a {@link WrappedStateStore} end the
+     * walk, so they resolve their own delegate through here.
+     */
+    static long resolveRetentionPeriod(final StateStore store) {
+        StateStore current = store;
+        while (current instanceof WrappedStateStore) {
+            current = ((WrappedStateStore<?, ?, ?>) current).wrapped();
+        }
+        return current instanceof WithRetentionPeriod
+            ? ((WithRetentionPeriod) current).retentionPeriod()
+            : -1L;
+    }
 }
diff --git a/streams/src/test/java/org/apache/kafka/streams/state/internals/PlainToHeadersWindowStoreAdapterTest.java b/streams/src/test/java/org/apache/kafka/streams/state/internals/PlainToHeadersWindowStoreAdapterTest.java
index 6c3400c344e..f44f0cba510 100644
--- a/streams/src/test/java/org/apache/kafka/streams/state/internals/PlainToHeadersWindowStoreAdapterTest.java
+++ b/streams/src/test/java/org/apache/kafka/streams/state/internals/PlainToHeadersWindowStoreAdapterTest.java
@@ -300,4 +300,12 @@ public class PlainToHeadersWindowStoreAdapterTest {
         }
         assertFalse(foundAdapterInfo, "Expected no execution info from adapter when not requested");
     }
+
+    @Test
+    public void shouldReportRetentionPeriodOfUnderlyingStore() {
+        // typed as StateStore so this compiles, and fails, when the adapter does not expose it
+        final StateStore store = adapter;
+        assertInstanceOf(WithRetentionPeriod.class, store);
+        assertEquals(RETENTION_PERIOD, ((WithRetentionPeriod) store).retentionPeriod());
+    }
 }
diff --git a/streams/src/test/java/org/apache/kafka/streams/state/internals/SessionToHeadersStoreAdapterTest.java b/streams/src/test/java/org/apache/kafka/streams/state/internals/SessionToHeadersStoreAdapterTest.java
index 2f3b3ebe65f..6330ff38be5 100644
--- a/streams/src/test/java/org/apache/kafka/streams/state/internals/SessionToHeadersStoreAdapterTest.java
+++ b/streams/src/test/java/org/apache/kafka/streams/state/internals/SessionToHeadersStoreAdapterTest.java
@@ -48,6 +48,7 @@ import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
+import static org.mockito.Mockito.withSettings;
 
 @ExtendWith(MockitoExtension.class)
 @MockitoSettings(strictness = Strictness.STRICT_STUBS)
@@ -253,4 +254,20 @@ public class SessionToHeadersStoreAdapterTest {
     public void shouldReturnNullFromRawAggregationValueForNull() {
         assertNull(Utils.rawAggregation(null));
     }
+
+    @Test
+    public void shouldReportRetentionPeriodOfUnderlyingStore() {
+        final long retentionMs = 60_000L;
+        @SuppressWarnings("unchecked")
+        final SessionStore<Bytes, byte[]> retentionAwareStore =
+            mock(SessionStore.class, withSettings().extraInterfaces(WithRetentionPeriod.class));
+        when(retentionAwareStore.persistent()).thenReturn(true);
+        when(((WithRetentionPeriod) retentionAwareStore).retentionPeriod()).thenReturn(retentionMs);
+
+        // typed as StateStore so this compiles, and fails, when the adapter does not expose it
+        final StateStore store = new SessionToHeadersStoreAdapter(retentionAwareStore);
+
+        assertInstanceOf(WithRetentionPeriod.class, store);
+        assertEquals(retentionMs, ((WithRetentionPeriod) store).retentionPeriod());
+    }
 }
diff --git a/streams/src/test/java/org/apache/kafka/streams/state/internals/TimestampedToHeadersWindowStoreAdapterTest.java b/streams/src/test/java/org/apache/kafka/streams/state/internals/TimestampedToHeadersWindowStoreAdapterTest.java
index cf1649b144c..30d20516e7b 100644
--- a/streams/src/test/java/org/apache/kafka/streams/state/internals/TimestampedToHeadersWindowStoreAdapterTest.java
+++ b/streams/src/test/java/org/apache/kafka/streams/state/internals/TimestampedToHeadersWindowStoreAdapterTest.java
@@ -319,4 +319,12 @@ public class TimestampedToHeadersWindowStoreAdapterTest {
         }
         assertFalse(foundAdapterInfo, "Expected no execution info from adapter when not requested");
     }
+
+    @Test
+    public void shouldReportRetentionPeriodOfUnderlyingStore() {
+        // typed as StateStore so this compiles, and fails, when the adapter does not expose it
+        final StateStore store = adapter;
+        assertInstanceOf(WithRetentionPeriod.class, store);
+        assertEquals(RETENTION_PERIOD, ((WithRetentionPeriod) store).retentionPeriod());
+    }
 }
\ No newline at end of file
diff --git a/streams/src/test/java/org/apache/kafka/streams/state/internals/TimestampedWindowStoreBuilderTest.java b/streams/src/test/java/org/apache/kafka/streams/state/internals/TimestampedWindowStoreBuilderTest.java
index c403614e2b7..ddaedbe0a50 100644
--- a/streams/src/test/java/org/apache/kafka/streams/state/internals/TimestampedWindowStoreBuilderTest.java
+++ b/streams/src/test/java/org/apache/kafka/streams/state/internals/TimestampedWindowStoreBuilderTest.java
@@ -39,6 +39,7 @@ import java.time.Duration;
 import java.util.Collections;
 
 import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.core.Is.is;
 import static org.hamcrest.core.IsInstanceOf.instanceOf;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertFalse;
@@ -198,6 +199,32 @@ public class TimestampedWindowStoreBuilderTest {
         assertThat(((WrappedStateStore) store).wrapped(), instanceOf(WindowToTimestampedWindowByteStoreAdapter.class));
     }
 
+    @ValueSource(strings = {TIMESTAMP_STORE_NAME, TIMEORDERED_STORE_NAME})
+    @ParameterizedTest
+    public void shouldExposeRetentionPeriodThroughTimestampedAdapter(final String storeName) {
+        final long retentionMs = 10L;
+        setUp(storeName);
+        when(supplier.get()).thenReturn(new RocksDBWindowStore(
+            new RocksDBSegmentedBytesStore(
+                "name",
+                "metric-scope",
+                retentionMs,
+                5L,
+                new WindowKeySchema()),
+            false,
+            1L));
+
+        final TimestampedWindowStore<String, String> store = builder
+            .withLoggingDisabled()
+            .withCachingDisabled()
+            .build();
+
+        // typed as StateStore so this compiles, and fails, when the adapter does not expose it
+        final StateStore adapter = ((WrappedStateStore) store).wrapped();
+        assertThat(adapter, instanceOf(WithRetentionPeriod.class));
+        assertThat(((WithRetentionPeriod) adapter).retentionPeriod(), is(retentionMs));
+    }
+
     @ValueSource(strings = {TIMESTAMP_STORE_NAME, TIMEORDERED_STORE_NAME})
     @ParameterizedTest
     public void shouldDisableCachingWithRetainDuplicates(final String storeName) {
diff --git a/streams/src/test/java/org/apache/kafka/streams/state/internals/WithRetentionPeriodTest.java b/streams/src/test/java/org/apache/kafka/streams/state/internals/WithRetentionPeriodTest.java
new file mode 100644
index 00000000000..e6983fad8db
--- /dev/null
+++ b/streams/src/test/java/org/apache/kafka/streams/state/internals/WithRetentionPeriodTest.java
@@ -0,0 +1,88 @@
+/*
+ * 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.kafka.streams.state.internals;
+
+import org.apache.kafka.streams.processor.StateStore;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import static org.mockito.Mockito.withSettings;
+
+public class WithRetentionPeriodTest {
+
+    private static final long RETENTION_MS = 60_000L;
+
+    private static class TestWrapper extends WrappedStateStore<StateStore, Object, Object> {
+        TestWrapper(final StateStore wrapped) {
+            super(wrapped);
+        }
+    }
+
+    private static StateStore storeReportingRetention() {
+        final StateStore store = mock(StateStore.class, withSettings().extraInterfaces(WithRetentionPeriod.class));
+        when(((WithRetentionPeriod) store).retentionPeriod()).thenReturn(RETENTION_MS);
+        return store;
+    }
+
+    @Test
+    public void shouldReturnRetentionOfStoreThatReportsItDirectly() {
+        assertEquals(RETENTION_MS, WithRetentionPeriod.resolveRetentionPeriod(storeReportingRetention()));
+    }
+
+    @Test
+    public void shouldResolveRetentionThroughWrappedStores() {
+        final StateStore wrapped = new TestWrapper(new TestWrapper(storeReportingRetention()));
+
+        assertEquals(RETENTION_MS, WithRetentionPeriod.resolveRetentionPeriod(wrapped));
+    }
+
+    @Test
+    public void shouldReturnMinusOneWhenStoreDoesNotReportRetention() {
+        assertEquals(-1L, WithRetentionPeriod.resolveRetentionPeriod(mock(StateStore.class)));
+    }
+
+    @Test
+    public void shouldReturnMinusOneWhenNoWrappedStoreReportsRetention() {
+        final StateStore wrapped = new TestWrapper(new TestWrapper(mock(StateStore.class)));
+
+        assertEquals(-1L, WithRetentionPeriod.resolveRetentionPeriod(wrapped));
+    }
+
+    @Test
+    public void shouldNotConsultOuterLayersThatReportRetention() {
+        // retention belongs to the innermost store, so an outer layer reporting one is ignored
+        final StateStore outer = new RetentionReportingWrapper(mock(StateStore.class));
+
+        assertEquals(-1L, WithRetentionPeriod.resolveRetentionPeriod(outer));
+    }
+
+    private static class RetentionReportingWrapper extends WrappedStateStore<StateStore, Object, Object>
+        implements WithRetentionPeriod {
+
+        RetentionReportingWrapper(final StateStore wrapped) {
+            super(wrapped);
+        }
+
+        @Override
+        public long retentionPeriod() {
+            return RETENTION_MS;
+        }
+    }
+}