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

lizhimins pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/rocketmq.git


The following commit(s) were added to refs/heads/develop by this push:
     new e114b54262 [ISSUE #11533] Keep base timerwheel always latest via 
atomic snapshot replacement (#11534)
e114b54262 is described below

commit e114b542620c4169d016f25b63c2c377b2e279a7
Author: lizhimins <[email protected]>
AuthorDate: Thu Nov 26 10:07:34 2026 +0800

    [ISSUE #11533] Keep base timerwheel always latest via atomic snapshot 
replacement (#11534)
    
    Snapshot cycle writes timerwheel.<offset>.tmp in forced 1 MiB segments,
    atomically renames to timerwheel.<offset>, persists checkpoint == offset,
    then atomically replaces the base (REPLACE_EXISTING, no delete). Recovery
    prefers the newest numeric snapshot, else base + CP pinned to the base
    end; mode captured at construction, switch changes require restart.
    Rollback to false / older images degrades to a normal rolling restart.
---
 .../rocketmq/store/timer/TimerCheckpoint.java      |   2 +-
 .../rocketmq/store/timer/TimerMessageStore.java    | 138 +++--
 .../apache/rocketmq/store/timer/TimerWheel.java    |  95 +++-
 .../rocketmq/store/timer/TimerCheckPointTest.java  |  33 ++
 .../store/timer/TimerMessageStoreTest.java         | 600 +++++++++++++++++++++
 .../rocketmq/store/timer/TimerWheelTest.java       | 195 +++++++
 6 files changed, 1004 insertions(+), 59 deletions(-)

diff --git 
a/store/src/main/java/org/apache/rocketmq/store/timer/TimerCheckpoint.java 
b/store/src/main/java/org/apache/rocketmq/store/timer/TimerCheckpoint.java
index 0c67c0d134..8825b69cd6 100644
--- a/store/src/main/java/org/apache/rocketmq/store/timer/TimerCheckpoint.java
+++ b/store/src/main/java/org/apache/rocketmq/store/timer/TimerCheckpoint.java
@@ -105,7 +105,7 @@ public class TimerCheckpoint {
         }
     }
 
-    public void flush() {
+    public synchronized void flush() {
         if (null == this.mappedByteBuffer) {
             return;
         }
diff --git 
a/store/src/main/java/org/apache/rocketmq/store/timer/TimerMessageStore.java 
b/store/src/main/java/org/apache/rocketmq/store/timer/TimerMessageStore.java
index a6059ce75f..4a2008ae7f 100644
--- a/store/src/main/java/org/apache/rocketmq/store/timer/TimerMessageStore.java
+++ b/store/src/main/java/org/apache/rocketmq/store/timer/TimerMessageStore.java
@@ -59,6 +59,7 @@ import org.apache.rocketmq.common.utils.ThreadUtils;
 import org.apache.rocketmq.logging.org.slf4j.Logger;
 import org.apache.rocketmq.logging.org.slf4j.LoggerFactory;
 import org.apache.rocketmq.store.DefaultMessageStore;
+import org.apache.rocketmq.store.MappedFileQueue;
 import org.apache.rocketmq.store.MessageStore;
 import org.apache.rocketmq.store.PutMessageResult;
 import org.apache.rocketmq.store.RunningFlags;
@@ -164,6 +165,11 @@ public class TimerMessageStore {
 
     private final Object lockWhenFlush = new Object();
 
+    // captured at construction; mode switches require a restart, hot updates 
must not mismatch mmap state.
+    private final boolean timerWheelSnapshotMode;
+    private final long loadedSnapshotOffset;
+    private volatile boolean recoveryCompleted;
+
     public TimerMessageStore(final MessageStore messageStore, final 
MessageStoreConfig storeConfig,
         TimerCheckpoint timerCheckpoint, TimerMetrics timerMetrics,
         final BrokerStatsManager brokerStatsManager) throws IOException {
@@ -178,15 +184,14 @@ public class TimerMessageStore {
         this.slotsTotal = TIMER_WHEEL_TTL_DAY * DAY_SECS;
 
         String timerWheelPath = 
getTimerWheelPath(storeConfig.getStorePathRootDir());
+        this.timerWheelSnapshotMode = storeConfig.isTimerWheelSnapshotFlush();
         long snapOffset = -1;
-        if (storeConfig.isTimerWheelSnapshotFlush()) {
+        if (this.timerWheelSnapshotMode) {
             snapOffset = TimerWheel.getMaxSnapshotFlag(timerWheelPath);
-            if (snapOffset > 0) {
-                // correct recover offset
-                timerCheckpoint.setLastTimerLogFlushPos(snapOffset);
+            if (snapOffset >= 0) {
                 LOGGER.info("found timerWheel snapshot offset {}", snapOffset);
             } else {
-                LOGGER.info("not found timerWheel snapshot", snapOffset);
+                LOGGER.info("not found timerWheel snapshot, recover from base 
+ checkpoint");
             }
         }
 
@@ -196,11 +201,12 @@ public class TimerMessageStore {
         }
 
         this.timerWheel = new TimerWheel(
-            timerWheelPath, this.slotsTotal, precisionMs, snapOffset);
+            timerWheelPath, this.slotsTotal, precisionMs, snapOffset, 
this.timerWheelSnapshotMode);
         this.timerLog = new 
TimerLog(getTimerLogPath(storeConfig.getStorePathRootDir()), timerLogFileSize,
             runningFlags, storeConfig.isWriteWithoutMmap());
         this.timerMetrics = timerMetrics;
         this.timerCheckpoint = timerCheckpoint;
+        this.loadedSnapshotOffset = snapOffset;
         this.lastBrokerRole = storeConfig.getBrokerRole();
 
         if (messageStore instanceof DefaultMessageStore) {
@@ -264,11 +270,49 @@ public class TimerMessageStore {
 
     public boolean load() {
         this.initService();
-        boolean load = timerLog.load();
-        load = load && this.timerMetrics.load();
+        if (!timerLog.load() || !this.timerMetrics.load()) {
+            return false;
+        }
+        if (!hasSnapshotLogCoverage()) {
+            LOGGER.error("Cannot recover timer snapshot at {}: timerlog files 
do not cover its replay range",
+                loadedSnapshotOffset);
+            return false;
+        }
         recover();
+        recoveryCompleted = true;
+        if (loadedSnapshotOffset >= 0) {
+            try {
+                timerFlushService.flush(true);
+            } catch (IOException e) {
+                LOGGER.error("Failed to commit recovered timer wheel", e);
+                return false;
+            }
+        }
         calcTimerDistribution();
-        return load;
+        return true;
+    }
+
+    private boolean hasSnapshotLogCoverage() {
+        if (loadedSnapshotOffset < 0) {
+            return true;
+        }
+        List<MappedFile> files = 
timerLog.getMappedFileQueue().getMappedFiles();
+        if (files.isEmpty()) {
+            return loadedSnapshotOffset == 0;
+        }
+        long nextOffset = loadedSnapshotOffset - loadedSnapshotOffset % 
timerLogFileSize;
+        for (MappedFile file : files) {
+            if (file.getFileFromOffset() < nextOffset) {
+                continue;
+            }
+            if (file.getFileFromOffset() != nextOffset) {
+                return false;
+            }
+            nextOffset += file.getFileSize();
+        }
+        MappedFile lastFile = files.get(files.size() - 1);
+        return nextOffset > loadedSnapshotOffset ||
+            lastFile.getFileFromOffset() + lastFile.getFileSize() == 
loadedSnapshotOffset;
     }
 
     public static String getTimerWheelPath(final String rootDir) {
@@ -301,7 +345,8 @@ public class TimerMessageStore {
     @SuppressWarnings("NonAtomicOperationOnVolatileField")
     public void recover() {
         //recover timerLog
-        long lastFlushPos = timerCheckpoint.getLastTimerLogFlushPos();
+        long lastFlushPos = loadedSnapshotOffset >= 0 ?
+            loadedSnapshotOffset : timerCheckpoint.getLastTimerLogFlushPos();
         MappedFile lastFile = 
timerLog.getMappedFileQueue().getLastMappedFile();
         if (null != lastFile) {
             lastFlushPos = lastFlushPos - lastFile.getFileSize();
@@ -580,16 +625,15 @@ public class TimerMessageStore {
             }
         }
 
-        //first save checkpoint
-        if (timerCheckpoint != null) {
-            prepareTimerCheckPoint();
-        }
-
         if (timerFlushService != null) {
             timerFlushService.shutdown();
         }
 
         if (timerCheckpoint != null) {
+            // Failed recovery must not overwrite the existing checkpoint with 
uninitialized progress.
+            if (recoveryCompleted) {
+                prepareTimerCheckPoint();
+            }
             timerCheckpoint.shutdown();
         }
 
@@ -860,6 +904,17 @@ public class TimerMessageStore {
                 recallToTimeline(delayedTime, offsetPy, sizePy, messageExt);
             }
         }
+        if (timerWheelSnapshotMode) {
+            synchronized (lockWhenFlush) {
+                return appendToTimerWheel(offsetPy, sizePy, delayedTime, 
tmpWriteTimeMs, magic, messageExt);
+            }
+        }
+        return appendToTimerWheel(offsetPy, sizePy, delayedTime, 
tmpWriteTimeMs, magic, messageExt);
+    }
+
+    private boolean appendToTimerWheel(long offsetPy, int sizePy, long 
delayedTime,
+        long tmpWriteTimeMs, int magic, MessageExt messageExt) {
+        boolean isDelete = needDelete(magic);
         String realTopic = 
messageExt.getProperty(MessageConst.PROPERTY_REAL_TOPIC);
         Slot slot = timerWheel.getSlot(delayedTime);
         ByteBuffer tmpBuffer = timerLogBuffer;
@@ -1516,13 +1571,7 @@ public class TimerMessageStore {
                 CountDownLatch latch = new CountDownLatch(trs.size());
                 for (TimerRequest req : trs) {
                     req.setLatch(latch);
-                    if (storeConfig.isTimerWheelSnapshotFlush()) {
-                        synchronized (lockWhenFlush) {
-                            this.putMessageToTimerWheel(req);
-                        }
-                    } else {
-                        this.putMessageToTimerWheel(req);
-                    }
+                    this.putMessageToTimerWheel(req);
                 }
                 checkDequeueLatch(latch, -1);
                 boolean allSuccess = 
trs.stream().allMatch(TimerRequest::isSucc);
@@ -1853,15 +1902,39 @@ public class TimerMessageStore {
         long lastSnapshotTime = System.currentTimeMillis();
 
         public void flush() throws IOException {
-            if (storeConfig.isTimerWheelSnapshotFlush()) {
-                synchronized (lockWhenFlush) {
-                    prepareTimerCheckPoint();
-                    timerLog.getMappedFileQueue().flush(0);
-                    if (System.currentTimeMillis() - lastSnapshotTime > 
storeConfig.getTimerWheelSnapshotIntervalMs()) {
-                        lastSnapshotTime = System.currentTimeMillis();
-                        
timerWheel.backup(timerLog.getMappedFileQueue().getFlushedWhere());
+            flush(false);
+        }
+
+        private void flush(boolean forceSnapshot) throws IOException {
+            if (timerWheelSnapshotMode) {
+                MappedFileQueue logQueue = timerLog.getMappedFileQueue();
+                prepareTimerCheckPoint();
+                long snapshotPos = -1;
+                if (forceSnapshot || System.currentTimeMillis() -
+                    lastSnapshotTime > 
storeConfig.getTimerWheelSnapshotIntervalMs()) {
+                    synchronized (lockWhenFlush) {
+                        timerWheel.copyForSnapshot();
+                        snapshotPos = logQueue.getMaxWrotePosition();
+                    }
+                }
+                logQueue.flush(0);
+                if (snapshotPos >= 0) {
+                    while (logQueue.getFlushedWhere() < snapshotPos) {
+                        long flushedWhere = logQueue.getFlushedWhere();
+                        logQueue.flush(0);
+                        if (logQueue.getFlushedWhere() == flushedWhere) {
+                            throw new IOException("Timer snapshot flush 
stalled at " + flushedWhere + " behind " + snapshotPos);
+                        }
                     }
-                    timerCheckpoint.flush();
+                }
+                if (snapshotPos >= 0) {
+                    timerWheel.backup(snapshotPos);
+                    timerWheel.promoteToBase(snapshotPos);
+                    timerCheckpoint.setLastTimerLogFlushPos(snapshotPos);
+                }
+                timerCheckpoint.flush();
+                if (snapshotPos >= 0) {
+                    lastSnapshotTime = System.currentTimeMillis();
                 }
             } else {
                 prepareTimerCheckPoint();
@@ -1946,7 +2019,10 @@ public class TimerMessageStore {
     }
 
     public void prepareTimerCheckPoint() {
-        
timerCheckpoint.setLastTimerLogFlushPos(timerLog.getMappedFileQueue().getFlushedWhere());
+        // Snapshot mode advances the log watermark only after the base is 
durable.
+        if (!timerWheelSnapshotMode) {
+            
timerCheckpoint.setLastTimerLogFlushPos(timerLog.getMappedFileQueue().getFlushedWhere());
+        }
         timerCheckpoint.setLastReadTimeMs(commitReadTimeMs);
         if (shouldRunningDequeue) {
             timerCheckpoint.setMasterTimerQueueOffset(commitQueueOffset);
diff --git 
a/store/src/main/java/org/apache/rocketmq/store/timer/TimerWheel.java 
b/store/src/main/java/org/apache/rocketmq/store/timer/TimerWheel.java
index 2d5ce38201..5695755139 100644
--- a/store/src/main/java/org/apache/rocketmq/store/timer/TimerWheel.java
+++ b/store/src/main/java/org/apache/rocketmq/store/timer/TimerWheel.java
@@ -38,6 +38,7 @@ import java.nio.channels.FileChannel;
 public class TimerWheel {
 
     private static final Logger log = 
LoggerFactory.getLogger(LoggerName.STORE_LOGGER_NAME);
+    private static final int BACKUP_SEGMENT_BYTES = 1024 * 1024;
     public static final String TIMER_WHEEL_FILE_NAME = "timerwheel";
     public static final int BLANK = -1, IGNORE = -2;
     public final int slotsTotal;
@@ -56,11 +57,15 @@ public class TimerWheel {
     private final int wheelLength;
 
     private long snapOffset;
+    private ByteBuffer snapshotBuffer;
 
     public TimerWheel(String fileName, int slotsTotal, int precisionMs) throws 
IOException {
-        this(fileName, slotsTotal, precisionMs, -1);
+        this(fileName, slotsTotal, precisionMs, -1, false);
     }
     public TimerWheel(String fileName, int slotsTotal, int precisionMs, long 
snapOffset) throws IOException {
+        this(fileName, slotsTotal, precisionMs, snapOffset, snapOffset >= 0);
+    }
+    public TimerWheel(String fileName, int slotsTotal, int precisionMs, long 
snapOffset, boolean snapshotMode) throws IOException {
         this.slotsTotal = slotsTotal;
         this.precisionMs = precisionMs;
         this.fileName = fileName;
@@ -79,7 +84,8 @@ public class TimerWheel {
                     randomAccessFile.length(), wheelLength));
             }
             randomAccessFile.setLength(wheelLength);
-            if (snapOffset < 0) {
+            // snapshot mode: promoteToBase swaps the base inode, so it must 
never be mmap'd here.
+            if (!snapshotMode) {
                 fileChannel = randomAccessFile.getChannel();
                 mappedByteBuffer = 
fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, wheelLength);
                 assert wheelLength == mappedByteBuffer.remaining();
@@ -115,12 +121,15 @@ public class TimerWheel {
         // unmap mappedByteBuffer
         UtilAll.cleanBuffer(this.mappedByteBuffer);
         UtilAll.cleanBuffer(this.byteBuffer);
+        UtilAll.cleanBuffer(this.snapshotBuffer);
         localBuffer.remove();
 
-        try {
-            this.fileChannel.close();
-        } catch (Throwable t) {
-            log.error("Shutdown error in timer wheel", t);
+        if (null != this.fileChannel) {
+            try {
+                this.fileChannel.close();
+            } catch (Throwable t) {
+                log.error("Shutdown error in timer wheel", t);
+            }
         }
     }
 
@@ -141,44 +150,59 @@ public class TimerWheel {
         this.mappedByteBuffer.force();
     }
 
-    /**
-     * Perform backup operation.
-     * <p>
-     * Select snapshot file based on the provided flag, write current buffer 
content to a temporary file,
-     * then rename the temporary file to the formal snapshot file. If rename 
fails, delete the temporary file.
-     * Finally clean up expired snapshot files.
-     *
-     * @param flushWhere Flag used to select snapshot file.
-     * @throws IOException If I/O error occurs during backup process.
-     */
-    public void backup(long flushWhere) throws IOException {
-        // Get current local buffer and position it to the beginning
+    /* Caller holds lockWhenFlush; the frozen buffer stays immutable until the 
next copy. */
+    public void copyForSnapshot() {
+        if (snapshotBuffer == null) {
+            snapshotBuffer = ByteBuffer.allocateDirect(wheelLength);
+        }
         ByteBuffer bf = localBuffer.get();
         bf.position(0);
         bf.limit(wheelLength);
+        snapshotBuffer.clear();
+        snapshotBuffer.put(bf);
+        snapshotBuffer.flip();
+    }
+
+    /* 1 MiB segments + force bound the writeback burst; tmp + atomic rename 
keep the snapshot complete. */
+    public void backup(long flushWhere) throws IOException {
+        ByteBuffer bf = snapshotBuffer;
+        bf.position(0);
+        bf.limit(wheelLength);
 
-        // Select snapshot file name based on flag
         String fileName = selectSnapshotByFlag(flushWhere);
         File bakFile = new File(fileName);
-        // Create or open temporary file for snapshot, ready for writing
         File tmpFile = new File(fileName + ".tmp");
-        // Delete if exists first
         Files.deleteIfExists(tmpFile.toPath());
         try (RandomAccessFile randomAccessFile = new RandomAccessFile(tmpFile, 
"rw")) {
             try (FileChannel fileChannel = randomAccessFile.getChannel()) {
-                fileChannel.write(bf);
+                while (bf.hasRemaining()) {
+                    bf.limit(Math.min(bf.position() + BACKUP_SEGMENT_BYTES, 
wheelLength));
+                    while (bf.hasRemaining()) {
+                        fileChannel.write(bf);
+                    }
+                    fileChannel.force(false);
+                    bf.limit(wheelLength);
+                }
                 fileChannel.force(true);
             }
         }
 
         if (tmpFile.exists()) {
-            // atomic move
-            Files.move(tmpFile.toPath(), bakFile.toPath(), 
StandardCopyOption.ATOMIC_MOVE);
-
-            // sync the directory, ensure that the bak file is visible
+            Files.move(tmpFile.toPath(), bakFile.toPath(),
+                StandardCopyOption.ATOMIC_MOVE, 
StandardCopyOption.REPLACE_EXISTING);
             MixAll.fsyncDirectory(Paths.get(bakFile.getParent()));
         }
-        cleanExpiredSnapshot(); // Clean up expired snapshot files
+        cleanExpiredSnapshot();
+    }
+
+    /* The checkpoint must not advance until replacement and directory fsync 
complete. */
+    public void promoteToBase(long offset) throws IOException {
+        File snapshot = new File(selectSnapshotByFlag(offset));
+        File base = new File(this.fileName);
+        Files.move(snapshot.toPath(), base.toPath(),
+            StandardCopyOption.ATOMIC_MOVE, 
StandardCopyOption.REPLACE_EXISTING);
+        MixAll.fsyncDirectory(Paths.get(base.getParent()));
+        cleanAllSnapshots();
     }
 
     /**
@@ -228,6 +252,23 @@ public class TimerWheel {
         }
     }
 
+    private void cleanAllSnapshots() {
+        File dir = new File(this.fileName).getParentFile();
+        File[] files = dir.listFiles();
+        if (files == null) {
+            return;
+        }
+        for (File file : files) {
+            String fileName = file.getName();
+            if (fileName.startsWith(TIMER_WHEEL_FILE_NAME + ".")) {
+                long flag = 
UtilAll.asLong(fileName.substring(TIMER_WHEEL_FILE_NAME.length() + 1), -1);
+                if (flag >= 0) {
+                    UtilAll.deleteFile(file);
+                }
+            }
+        }
+    }
+
     /**
      * Get the maximum flag from existing snapshot files.
      *
diff --git 
a/store/src/test/java/org/apache/rocketmq/store/timer/TimerCheckPointTest.java 
b/store/src/test/java/org/apache/rocketmq/store/timer/TimerCheckPointTest.java
index f72874af2d..0f87d1827b 100644
--- 
a/store/src/test/java/org/apache/rocketmq/store/timer/TimerCheckPointTest.java
+++ 
b/store/src/test/java/org/apache/rocketmq/store/timer/TimerCheckPointTest.java
@@ -19,12 +19,18 @@ package org.apache.rocketmq.store.timer;
 
 import java.io.File;
 import java.io.IOException;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.FutureTask;
+import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicLong;
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
 
+import static org.awaitility.Awaitility.await;
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
 
 public class TimerCheckPointTest {
 
@@ -118,6 +124,33 @@ public class TimerCheckPointTest {
         assertEquals(first.getDataVersion().getCounter().get(), 1600);
     }
 
+    @Test
+    public void flushUsesCheckpointMonitorTest() throws Exception {
+        TimerCheckpoint checkpoint = new TimerCheckpoint(baseDir + 
File.separator + "timercheck-monitor");
+        CountDownLatch flushStarted = new CountDownLatch(1);
+        FutureTask<Void> flushTask = new FutureTask<>(() -> {
+            flushStarted.countDown();
+            checkpoint.flush();
+            return null;
+        });
+        Thread flushThread = new Thread(flushTask, 
"timer-checkpoint-flush-test");
+        flushThread.setDaemon(true);
+        try {
+            synchronized (checkpoint) {
+                flushThread.start();
+                assertTrue(flushStarted.await(5, TimeUnit.SECONDS));
+                await().atMost(5, TimeUnit.SECONDS).until(() -> 
flushThread.getState() == Thread.State.BLOCKED);
+                assertFalse(flushTask.isDone());
+            }
+            flushTask.get(5, TimeUnit.SECONDS);
+        } finally {
+            flushTask.cancel(true);
+            flushThread.join(TimeUnit.SECONDS.toMillis(5));
+            assertFalse("Flush thread did not terminate", 
flushThread.isAlive());
+            checkpoint.shutdown();
+        }
+    }
+
     @After
     public void shutdown() {
         if (null != baseDir) {
diff --git 
a/store/src/test/java/org/apache/rocketmq/store/timer/TimerMessageStoreTest.java
 
b/store/src/test/java/org/apache/rocketmq/store/timer/TimerMessageStoreTest.java
index 8264b35a7f..c7dc45881f 100644
--- 
a/store/src/test/java/org/apache/rocketmq/store/timer/TimerMessageStoreTest.java
+++ 
b/store/src/test/java/org/apache/rocketmq/store/timer/TimerMessageStoreTest.java
@@ -19,11 +19,15 @@ package org.apache.rocketmq.store.timer;
 
 import java.io.File;
 import java.io.IOException;
+import java.io.RandomAccessFile;
+import java.lang.management.ManagementFactory;
+import java.lang.management.ThreadInfo;
 import java.lang.reflect.Field;
 import java.net.InetAddress;
 import java.net.InetSocketAddress;
 import java.net.SocketAddress;
 import java.nio.ByteBuffer;
+import java.nio.file.Files;
 import java.util.ArrayList;
 import java.util.HashSet;
 import java.util.List;
@@ -32,6 +36,7 @@ import java.util.Set;
 import java.util.concurrent.Callable;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.FutureTask;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicInteger;
 import org.apache.rocketmq.common.BrokerConfig;
@@ -47,6 +52,8 @@ import org.apache.rocketmq.store.MessageStore;
 import org.apache.rocketmq.store.PutMessageResult;
 import org.apache.rocketmq.store.DefaultMessageStore;
 import org.apache.rocketmq.store.PutMessageStatus;
+import org.apache.rocketmq.store.SelectMappedBufferResult;
+import org.apache.rocketmq.store.config.BrokerRole;
 import org.apache.rocketmq.store.config.FlushDiskType;
 import org.apache.rocketmq.store.config.MessageStoreConfig;
 import org.apache.rocketmq.store.stats.BrokerStatsManager;
@@ -65,6 +72,7 @@ import org.mockito.Mockito;
 
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.awaitility.Awaitility.await;
+import static org.junit.Assert.assertArrayEquals;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotEquals;
 import static org.junit.Assert.assertNotNull;
@@ -491,6 +499,8 @@ public class TimerMessageStoreTest {
 
     @Test
     public void testStateAndRecover() throws Exception {
+        // damage the wheel via the non-snapshot flush path to trigger 
checkPhyPos on recovery.
+        storeConfig.setTimerWheelSnapshotFlush(false);
         final String topic = "TimerTest_testStateAndRecover";
 
         String base = StoreTestUtils.createBaseDir();
@@ -653,6 +663,523 @@ public class TimerMessageStoreTest {
         assertEquals(2, 
timerMessageStore.getTimerMetrics().getTimingCount(topic));
     }
 
+    @Test
+    public void snapshotFlushAndRecoverTest() throws Exception {
+        storeConfig.setTimerWheelSnapshotFlush(true);
+        storeConfig.setTimerWheelSnapshotIntervalMs(0);
+        storeConfig.setTimerFlushIntervalMs(100);
+        final String topic = "TimerTest_snapshotFlushAndRecover";
+
+        String base = StoreTestUtils.createBaseDir();
+        final TimerMessageStore first = createTimerMessageStore(base, false);
+        first.load();
+        first.start(true);
+
+        final int shortNum = 300;
+        final int longNum = 10;
+        long curr = System.currentTimeMillis() / precisionMs * precisionMs;
+        final long longDeliverMs = curr + 60000 - precisionMs;
+        for (int i = 0; i < shortNum + longNum; i++) {
+            MessageExtBrokerInner inner = buildMessage(curr + (i < shortNum ? 
5000 : 60000), topic, false);
+            transformTimerMessage(first, inner);
+            assertEquals(PutMessageStatus.PUT_OK, 
messageStore.putMessage(inner).getPutMessageStatus());
+        }
+        await().atMost(5000, TimeUnit.MILLISECONDS).until(() -> 
first.getCommitQueueOffset() == shortNum + longNum);
+
+        // wait for a promote covering every enqueued record: base latest, no 
numeric snapshot, CP paired.
+        long target = 
first.getTimerLog().getMappedFileQueue().getMaxWrotePosition();
+        String wheelPath = 
TimerMessageStore.getTimerWheelPath(storeConfig.getStorePathRootDir());
+        await().atMost(5000, TimeUnit.MILLISECONDS).until(() ->
+            first.getTimerCheckpoint().getLastTimerLogFlushPos() >= target &&
+                TimerWheel.getMaxSnapshotFlag(wheelPath) == -1);
+        assertThat(first.getTimerCheckpoint().getLastTimerLogFlushPos())
+            
.isLessThanOrEqualTo(first.getTimerLog().getMappedFileQueue().getMaxWrotePosition());
+        // base is the promoted wheel; recovery rewinds one timerlog file and 
replays the gap (verified below).
+        assertEquals(604800L * 2 * Slot.SIZE, new File(wheelPath).length());
+        first.shutdown();
+
+        final TimerMessageStore second = createTimerMessageStore(base, false);
+        assertTrue(second.load());
+        assertEquals(shortNum + longNum, second.getQueueOffset());
+        assertEquals(second.getCommitQueueOffset(), second.getQueueOffset());
+        assertEquals(first.getCommitReadTimeMs(), 
second.getCommitReadTimeMs());
+        assertEquals(longNum, second.getTimerWheel().getNum(longDeliverMs));
+        second.start(true);
+
+        await().atMost(30000, TimeUnit.MILLISECONDS).until(() -> {
+            ConsumeQueue cq = (ConsumeQueue) 
messageStore.getConsumeQueue(topic, 0);
+            return cq != null && cq.getMaxOffsetInQueue() >= shortNum;
+        });
+        for (int i = 0; i < shortNum; i++) {
+            assertThat(getOneMessage(topic, 0, i, 2000)).isNotNull();
+        }
+        assertEquals(longNum, second.getTimerWheel().getNum(longDeliverMs));
+        second.shutdown();
+    }
+
+    @Test
+    public void snapshotRollMessageTest() throws Exception {
+        storeConfig.setTimerWheelSnapshotFlush(true);
+        storeConfig.setTimerWheelSnapshotIntervalMs(0);
+        storeConfig.setTimerFlushIntervalMs(100);
+        storeConfig.setTimerRollWindowSlot(2);
+        String topic = "TimerTest_snapshotRollMessage";
+
+        TimerMessageStore timerMessageStore = createTimerMessageStore(null, 
false);
+        timerMessageStore.load();
+        timerMessageStore.start(true);
+
+        long curr = System.currentTimeMillis() / precisionMs * precisionMs;
+        long delayMs = curr + 4 * precisionMs;
+        MessageExtBrokerInner inner = buildMessage(delayMs, topic, false);
+        transformTimerMessage(timerMessageStore, inner);
+        assertEquals(PutMessageStatus.PUT_OK, 
messageStore.putMessage(inner).getPutMessageStatus());
+
+        ByteBuffer msgBuff = getOneMessage(topic, 0, 0, 5000);
+        assertNotNull(msgBuff);
+        MessageExt msgExt = MessageDecoder.decode(msgBuff);
+        assertNotNull(msgExt);
+        assertEquals(1, 
Integer.valueOf(msgExt.getProperty(MessageConst.PROPERTY_TIMER_ROLL_TIMES)).intValue());
+        storeConfig.setTimerRollWindowSlot(Integer.MAX_VALUE);
+    }
+
+    @Test
+    public void checkpointPinnedBetweenSnapshotsTest() throws Exception {
+        storeConfig.setTimerWheelSnapshotFlush(true);
+        storeConfig.setTimerWheelSnapshotIntervalMs(600000); // no auto 
snapshot during the test
+        storeConfig.setTimerFlushIntervalMs(100);
+        final String topic = "TimerTest_checkpointPinned";
+
+        String base = StoreTestUtils.createBaseDir();
+        final TimerMessageStore first = createTimerMessageStore(base, false);
+        first.load();
+        first.start(true);
+
+        final int msgNum = 50;
+        long curr = System.currentTimeMillis() / precisionMs * precisionMs;
+        for (int i = 0; i < msgNum; i++) {
+            MessageExtBrokerInner inner = buildMessage(curr + 60000, topic, 
false);
+            transformTimerMessage(first, inner);
+            assertEquals(PutMessageStatus.PUT_OK, 
messageStore.putMessage(inner).getPutMessageStatus());
+        }
+        await().atMost(5000, TimeUnit.MILLISECONDS).until(() -> 
first.getCommitQueueOffset() == msgNum);
+        // let timerlog flush ahead while no snapshot is taken
+        await().atMost(5000, TimeUnit.MILLISECONDS).until(() ->
+            first.getTimerLog().getMappedFileQueue().getFlushedWhere() > 0);
+        // CP must stay pinned to the base end (0, no promote yet), not 
advance with flushedWhere
+        first.getTimerFlushService().flush();
+        assertEquals(0, first.getTimerCheckpoint().getLastTimerLogFlushPos());
+
+        // now promote a snapshot: CP advances to the flag and base becomes 
latest
+        storeConfig.setTimerWheelSnapshotIntervalMs(0);
+        long target = 
first.getTimerLog().getMappedFileQueue().getMaxWrotePosition();
+        String wheelPath = 
TimerMessageStore.getTimerWheelPath(storeConfig.getStorePathRootDir());
+        await().atMost(5000, TimeUnit.MILLISECONDS).until(() ->
+            first.getTimerCheckpoint().getLastTimerLogFlushPos() >= target &&
+                TimerWheel.getMaxSnapshotFlag(wheelPath) == -1);
+        first.shutdown();
+
+        // recovery replays [base end, crash) from timerlog: zero loss
+        final TimerMessageStore second = createTimerMessageStore(base, false);
+        assertTrue(second.load());
+        assertEquals(msgNum, second.getQueueOffset());
+        second.shutdown();
+    }
+
+    @Test
+    public void recoverFromPendingSnapshotTest() throws Exception {
+        storeConfig.setTimerWheelSnapshotFlush(true);
+        storeConfig.setTimerWheelSnapshotIntervalMs(0);
+        storeConfig.setTimerFlushIntervalMs(100);
+        final String topic = "TimerTest_pendingSnapshot";
+
+        String base = StoreTestUtils.createBaseDir();
+        final TimerMessageStore first = createTimerMessageStore(base, false);
+        first.load();
+        first.start(true);
+
+        final int longNum = 8;
+        long curr = System.currentTimeMillis() / precisionMs * precisionMs;
+        final long longDeliverMs = curr + 60000 - precisionMs;
+        for (int i = 0; i < longNum; i++) {
+            MessageExtBrokerInner inner = buildMessage(curr + 60000, topic, 
false);
+            transformTimerMessage(first, inner);
+            assertEquals(PutMessageStatus.PUT_OK, 
messageStore.putMessage(inner).getPutMessageStatus());
+        }
+        await().atMost(5000, TimeUnit.MILLISECONDS).until(() -> 
first.getCommitQueueOffset() == longNum);
+        String wheelPath = 
TimerMessageStore.getTimerWheelPath(storeConfig.getStorePathRootDir());
+        await().atMost(5000, TimeUnit.MILLISECONDS).until(() ->
+            first.getTimerCheckpoint().getLastTimerLogFlushPos() > 0 &&
+                TimerWheel.getMaxSnapshotFlag(wheelPath) == -1);
+        long promotedFlag = 
first.getTimerCheckpoint().getLastTimerLogFlushPos();
+
+        // freeze a pending snapshot WITHOUT promoting: the "CP old, pending x 
present" crash window.
+        storeConfig.setTimerWheelSnapshotIntervalMs(600000);
+        final int moreNum = 6;
+        for (int i = 0; i < moreNum; i++) {
+            MessageExtBrokerInner inner = buildMessage(curr + 60000, topic, 
false);
+            transformTimerMessage(first, inner);
+            assertEquals(PutMessageStatus.PUT_OK, 
messageStore.putMessage(inner).getPutMessageStatus());
+        }
+        await().atMost(5000, TimeUnit.MILLISECONDS).until(() -> 
first.getCommitQueueOffset() == longNum + moreNum);
+        first.getTimerWheel().copyForSnapshot();
+        long pendingFlag = 
first.getTimerLog().getMappedFileQueue().getMaxWrotePosition();
+        first.getTimerLog().getMappedFileQueue().flush(0);
+        first.getTimerWheel().backup(pendingFlag);
+        assertThat(pendingFlag).isGreaterThan(promotedFlag);
+        assertEquals(pendingFlag, TimerWheel.getMaxSnapshotFlag(wheelPath));
+        first.shutdown();
+        // after shutdown CP is pinned to the old base end while the pending 
snapshot remains on disk
+        assertEquals(promotedFlag, 
first.getTimerCheckpoint().getLastTimerLogFlushPos());
+        assertEquals(pendingFlag, TimerWheel.getMaxSnapshotFlag(wheelPath));
+
+        // recovery must prefer the pending snapshot (flag) over base + old 
CP: zero loss
+        final TimerMessageStore second = createTimerMessageStore(base, false);
+        assertTrue(second.load());
+        assertEquals(longNum + moreNum, second.getQueueOffset());
+        assertEquals(longNum + moreNum, 
second.getTimerWheel().getNum(longDeliverMs));
+        second.shutdown();
+    }
+
+    @Test
+    public void checkpointPinnedDuringPromotionAndRoleChangeTest() throws 
Exception {
+        TimerMessageStore store = createSnapshotFixture();
+        long baseOffset = readPersistedTimerOffset();
+        long target = 
store.getTimerLog().getMappedFileQueue().getMaxWrotePosition();
+        TimerCheckpoint checkpoint = Mockito.spy(store.getTimerCheckpoint());
+        Field checkpointField = 
TimerMessageStore.class.getDeclaredField("timerCheckpoint");
+        checkpointField.setAccessible(true);
+        checkpointField.set(store, checkpoint);
+        CountDownLatch prepareStarted = new CountDownLatch(1);
+        CountDownLatch continuePrepare = new CountDownLatch(1);
+        FutureTask<Void> prepare = new FutureTask<>(() -> {
+            store.prepareTimerCheckPoint();
+            return null;
+        });
+        Thread prepareThread = new Thread(prepare, 
"TimerCheckpointPrepareTest");
+        Mockito.doAnswer(invocation -> {
+            if (Thread.currentThread() == prepareThread) {
+                prepareStarted.countDown();
+                assertTrue(continuePrepare.await(10, TimeUnit.SECONDS));
+            }
+            return invocation.callRealMethod();
+        }).when(checkpoint).setLastReadTimeMs(Mockito.anyLong());
+        TimerWheel wheel = spyTimerWheel(store);
+        CountDownLatch beforePromote = new CountDownLatch(1);
+        CountDownLatch continuePromote = new CountDownLatch(1);
+        Mockito.doAnswer(invocation -> {
+            beforePromote.countDown();
+            assertTrue(continuePromote.await(10, TimeUnit.SECONDS));
+            return invocation.callRealMethod();
+        }).when(wheel).promoteToBase(target);
+        FutureTask<Void> flush = new FutureTask<>(() -> {
+            forceSnapshot(store);
+            return null;
+        });
+        Thread thread = new Thread(flush, "TimerSnapshotCommitTest");
+        thread.start();
+        try {
+            assertTrue(beforePromote.await(10, TimeUnit.SECONDS));
+            assertEquals(baseOffset, readPersistedTimerOffset());
+            storeConfig.setBrokerRole(BrokerRole.SLAVE);
+            store.enqueue(0);
+            storeConfig.setBrokerRole(BrokerRole.SYNC_MASTER);
+            store.enqueue(0);
+            checkpoint.flush();
+            assertEquals(baseOffset, checkpoint.getLastTimerLogFlushPos());
+            assertEquals(baseOffset, readPersistedTimerOffset());
+            Mockito.verify(checkpoint, 
Mockito.never()).setLastTimerLogFlushPos(baseOffset);
+            prepareThread.start();
+            assertTrue(prepareStarted.await(10, TimeUnit.SECONDS));
+            continuePromote.countDown();
+            flush.get(10, TimeUnit.SECONDS);
+            assertFalse(prepare.isDone());
+            assertEquals(target, readPersistedTimerOffset());
+        } finally {
+            continuePrepare.countDown();
+            continuePromote.countDown();
+            prepareThread.join(10000);
+            thread.join(10000);
+        }
+        prepare.get(10, TimeUnit.SECONDS);
+        checkpoint.flush();
+        assertEquals(target, checkpoint.getLastTimerLogFlushPos());
+        assertEquals(target, readPersistedTimerOffset());
+        Mockito.verify(checkpoint, 
Mockito.times(1)).setLastTimerLogFlushPos(target);
+        Mockito.verify(checkpoint, 
Mockito.never()).setLastTimerLogFlushPos(baseOffset);
+    }
+
+    @Test
+    public void timelineRecallSharesSnapshotBoundaryTest() throws Exception {
+        TimerMessageStore store = createSnapshotFixture();
+        long delayedTime = store.getCommitReadTimeMs() + 20000;
+        MessageExtBrokerInner message = buildMessage(delayedTime + 
precisionMs, "TimerTest_snapshotCommit", false);
+        transformTimerMessage(store, message);
+        MessageAccessor.putProperty(message, 
TimerMessageStore.TIMER_DELETE_UNIQUE_KEY, "recall-test");
+        PutMessageResult result = messageStore.putMessage(message);
+        assertEquals(PutMessageStatus.PUT_OK, result.getPutMessageStatus());
+        TimerLog log = Mockito.spy(store.getTimerLog());
+        Field logField = TimerMessageStore.class.getDeclaredField("timerLog");
+        logField.setAccessible(true);
+        logField.set(store, log);
+        TimerWheel wheel = spyTimerWheel(store);
+        CountDownLatch appended = new CountDownLatch(1);
+        CountDownLatch continueEnqueue = new CountDownLatch(1);
+        Mockito.doAnswer(invocation -> {
+            Object offset = invocation.callRealMethod();
+            appended.countDown();
+            assertTrue(continueEnqueue.await(10, TimeUnit.SECONDS));
+            return offset;
+        }).when(log).append(Mockito.any(byte[].class), Mockito.eq(0), 
Mockito.eq(TimerLog.UNIT_SIZE));
+        FutureTask<Boolean> enqueue = new FutureTask<>(() -> store.doEnqueue(
+            result.getAppendMessageResult().getWroteOffset(), 
result.getAppendMessageResult().getWroteBytes(),
+            delayedTime, message, true));
+        Thread enqueueThread = new Thread(enqueue, 
"TimelineRecallSnapshotTest");
+        FutureTask<Void> flush = new FutureTask<>(() -> {
+            forceSnapshot(store);
+            return null;
+        });
+        Thread flushThread = new Thread(flush, "TimelineSnapshotFlushTest");
+        enqueueThread.start();
+        try {
+            assertTrue(appended.await(10, TimeUnit.SECONDS));
+            flushThread.start();
+            await().atMost(10, TimeUnit.SECONDS).until(() -> {
+                ThreadInfo info = 
ManagementFactory.getThreadMXBean().getThreadInfo(flushThread.getId());
+                return flush.isDone() || info != null && info.getLockOwnerId() 
== enqueueThread.getId();
+            });
+            assertFalse(flush.isDone());
+            Mockito.verify(wheel, Mockito.never()).copyForSnapshot();
+        } finally {
+            continueEnqueue.countDown();
+            enqueueThread.join(10000);
+            flushThread.join(10000);
+        }
+        assertTrue(enqueue.get(10, TimeUnit.SECONDS));
+        flush.get(10, TimeUnit.SECONDS);
+        TimerWheel base = new TimerWheel(wheel.getFileName(), 
wheel.slotsTotal, precisionMs);
+        try {
+            assertEquals(wheel.getSlot(delayedTime).lastPos, 
base.getSlot(delayedTime).lastPos);
+            assertEquals(wheel.getSlot(delayedTime).num, 
base.getSlot(delayedTime).num);
+        } finally {
+            base.shutdown();
+        }
+    }
+
+    @Test
+    public void snapshotPromotionFailureRollbackTest() throws Exception {
+        TimerMessageStore first = createSnapshotFixture();
+        long firstTime = first.getCommitReadTimeMs() + 10000;
+        long baseOffset = readPersistedTimerOffset();
+        TimerWheel wheel = spyTimerWheel(first);
+        Mockito.doThrow(new IOException("promotion 
failed")).when(wheel).promoteToBase(Mockito.anyLong());
+        Assert.assertThrows(IOException.class, () -> forceSnapshot(first));
+        assertEquals(baseOffset, readPersistedTimerOffset());
+        assertEquals(0, first.getTimerFlushService().lastSnapshotTime);
+        first.shutdown();
+        storeConfig.setTimerWheelSnapshotFlush(false);
+        TimerMessageStore second = 
createTimerMessageStore(storeConfig.getStorePathRootDir(), false);
+        assertTrue(second.load());
+        assertSnapshotFixtureSlots(second.getTimerWheel(), firstTime);
+        assertEquals(50, second.getQueueOffset());
+    }
+
+    @Test
+    public void snapshotPostRenameFailureRetryTest() throws Exception {
+        TimerMessageStore store = createSnapshotFixture();
+        long baseOffset = readPersistedTimerOffset();
+        long target = 
store.getTimerLog().getMappedFileQueue().getMaxWrotePosition();
+        TimerWheel wheel = spyTimerWheel(store);
+        Mockito.doAnswer(invocation -> {
+            invocation.callRealMethod();
+            throw new IOException("failure after replacement");
+        }).doCallRealMethod().when(wheel).promoteToBase(target);
+        Assert.assertThrows(IOException.class, () -> forceSnapshot(store));
+        assertEquals(baseOffset, readPersistedTimerOffset());
+        assertEquals(-1, TimerWheel.getMaxSnapshotFlag(wheel.getFileName()));
+        assertEquals(0, store.getTimerFlushService().lastSnapshotTime);
+        store.getTimerFlushService().flush();
+        assertEquals(target, readPersistedTimerOffset());
+        assertTrue(store.getTimerFlushService().lastSnapshotTime > 0);
+    }
+
+    @Test
+    public void pendingSnapshotImmediateRollbackDeliveryTest() throws 
Exception {
+        verifyPendingSnapshotRollback(false);
+        TimerMessageStore store = timerStores.get(timerStores.size() - 1);
+        store.start(true);
+        await().atMost(45000, TimeUnit.MILLISECONDS).until(() -> {
+            ConsumeQueue queue = (ConsumeQueue) 
messageStore.getConsumeQueue("TimerTest_snapshotCommit", 0);
+            return queue != null && queue.getMaxOffsetInQueue() == 50;
+        });
+        Set<String> tags = new HashSet<>();
+        for (int i = 0; i < 50; i++) {
+            MessageExt message = 
MessageDecoder.decode(getOneMessage("TimerTest_snapshotCommit", 0, i, 2000));
+            assertNotNull(message);
+            tags.add(message.getTags());
+        }
+        assertEquals(50, tags.size());
+    }
+
+    @Test
+    public void pendingSnapshotOrdinaryFlushRollbackTest() throws Exception {
+        verifyPendingSnapshotRollback(true);
+    }
+
+    @Test
+    public void recoveredSnapshotCommitFailureTest() throws Exception {
+        TimerMessageStore first = createSnapshotFixture();
+        long baseOffset = readPersistedTimerOffset();
+        String wheelPath = first.getTimerWheel().getFileName();
+        byte[] baseBefore = Files.readAllBytes(new File(wheelPath).toPath());
+        first.getTimerWheel().copyForSnapshot();
+        long target = 
first.getTimerLog().getMappedFileQueue().getMaxWrotePosition();
+        first.getTimerWheel().backup(target);
+        first.shutdown();
+        TimerMessageStore second = 
createTimerMessageStore(storeConfig.getStorePathRootDir(), false);
+        assertEquals(baseOffset, 
second.getTimerCheckpoint().getLastTimerLogFlushPos());
+        Mockito.doThrow(new IOException("startup promotion failed"))
+            .when(spyTimerWheel(second)).promoteToBase(Mockito.anyLong());
+        assertFalse(second.load());
+        second.shutdown();
+        assertEquals(baseOffset, readPersistedTimerOffset());
+        assertArrayEquals(baseBefore, Files.readAllBytes(new 
File(wheelPath).toPath()));
+        assertEquals(target, TimerWheel.getMaxSnapshotFlag(wheelPath));
+    }
+
+    @Test
+    public void pendingSnapshotBehindCheckpointWithCompleteLogsTest() throws 
Exception {
+        TimerMessageStore first = createSnapshotFixture();
+        long firstTime = first.getCommitReadTimeMs() + 10000;
+        String wheelPath = first.getTimerWheel().getFileName();
+        long baseOffset = readPersistedTimerOffset();
+        long target = 
first.getTimerLog().getMappedFileQueue().getMaxWrotePosition();
+        Files.copy(new File(wheelPath).toPath(), new File(wheelPath + "." + 
baseOffset).toPath());
+        first.shutdown();
+        TimerCheckpoint checkpoint = new 
TimerCheckpoint(timerCheckpointFile().getPath());
+        checkpoint.setLastTimerLogFlushPos(target);
+        checkpoint.shutdown();
+        TimerMessageStore second = 
createTimerMessageStore(storeConfig.getStorePathRootDir(), false);
+        assertTrue(second.load());
+        assertSnapshotFixtureSlots(second.getTimerWheel(), firstTime);
+        assertEquals(target, readPersistedTimerOffset());
+        assertEquals(-1, TimerWheel.getMaxSnapshotFlag(wheelPath));
+    }
+
+    @Test
+    public void pendingSnapshotMissingMiddleLogRejectsLoadTest() throws 
Exception {
+        TimerMessageStore first = createSnapshotFixture();
+        String wheelPath = first.getTimerWheel().getFileName();
+        long baseOffset = readPersistedTimerOffset();
+        Files.copy(new File(wheelPath).toPath(), new File(wheelPath + "." + 
baseOffset).toPath());
+        File missingFile = new 
File(first.getTimerLog().getMappedFileQueue().getMappedFiles().get(3).getFileName());
+        first.shutdown();
+        byte[] baseBefore = Files.readAllBytes(new File(wheelPath).toPath());
+        byte[] checkpointBefore = 
Files.readAllBytes(timerCheckpointFile().toPath());
+        Files.delete(missingFile.toPath());
+        TimerMessageStore second = 
createTimerMessageStore(storeConfig.getStorePathRootDir(), false);
+        assertFalse(second.load());
+        second.shutdown();
+        assertArrayEquals(baseBefore, Files.readAllBytes(new 
File(wheelPath).toPath()));
+        assertArrayEquals(checkpointBefore, 
Files.readAllBytes(timerCheckpointFile().toPath()));
+        assertEquals(baseOffset, TimerWheel.getMaxSnapshotFlag(wheelPath));
+    }
+
+    private TimerMessageStore createSnapshotFixture() throws Exception {
+        storeConfig.setMappedFileSizeTimerLog(512);
+        storeConfig.setTimerWheelSnapshotFlush(true);
+        storeConfig.setTimerWheelSnapshotIntervalMs(600000);
+        TimerMessageStore store = 
createTimerMessageStore(storeConfig.getStorePathRootDir(), false);
+        assertTrue(store.load());
+        long now = System.currentTimeMillis() / precisionMs * precisionMs;
+        store.currReadTimeMs = now;
+        store.commitReadTimeMs = now;
+        store.currWriteTimeMs = now;
+        for (int i = 0; i < 50; i++) {
+            long delayedTime = now + 10000 + (long) i * precisionMs;
+            MessageExtBrokerInner message = buildMessage(delayedTime + 
precisionMs, "TimerTest_snapshotCommit", false);
+            transformTimerMessage(store, message);
+            PutMessageResult result = messageStore.putMessage(message);
+            assertEquals(PutMessageStatus.PUT_OK, 
result.getPutMessageStatus());
+            
assertTrue(store.doEnqueue(result.getAppendMessageResult().getWroteOffset(),
+                result.getAppendMessageResult().getWroteBytes(), delayedTime, 
message, false));
+            store.currQueueOffset = i + 1;
+            store.commitQueueOffset = i + 1;
+            store.getTimerCheckpoint().setMasterTimerQueueOffset(i + 1);
+            if (i == 9) {
+                forceSnapshot(store);
+            }
+        }
+        long target = 
store.getTimerLog().getMappedFileQueue().getMaxWrotePosition();
+        while (store.getTimerLog().getMappedFileQueue().getFlushedWhere() < 
target) {
+            long before = 
store.getTimerLog().getMappedFileQueue().getFlushedWhere();
+            store.getTimerLog().getMappedFileQueue().flush(0);
+            
assertTrue(store.getTimerLog().getMappedFileQueue().getFlushedWhere() > before);
+        }
+        store.getTimerFlushService().flush();
+        await().atMost(5000, TimeUnit.MILLISECONDS).until(() ->
+            messageStore.getConsumeQueue(TimerMessageStore.TIMER_TOPIC, 0) != 
null &&
+                messageStore.getConsumeQueue(TimerMessageStore.TIMER_TOPIC, 
0).getMaxOffsetInQueue() == 50);
+        return store;
+    }
+
+    private void verifyPendingSnapshotRollback(boolean ordinaryFlush) throws 
Exception {
+        TimerMessageStore first = createSnapshotFixture();
+        long firstTime = first.getCommitReadTimeMs() + 10000;
+        long target = 
first.getTimerLog().getMappedFileQueue().getMaxWrotePosition();
+        first.getTimerWheel().copyForSnapshot();
+        first.getTimerWheel().backup(target);
+        first.shutdown();
+        TimerMessageStore second = 
createTimerMessageStore(storeConfig.getStorePathRootDir(), false);
+        assertTrue(second.load());
+        assertEquals(target, readPersistedTimerOffset());
+        assertEquals(-1, 
TimerWheel.getMaxSnapshotFlag(second.getTimerWheel().getFileName()));
+        if (ordinaryFlush) {
+            second.getTimerFlushService().flush();
+        }
+        second.shutdown();
+        storeConfig.setTimerWheelSnapshotFlush(false);
+        TimerMessageStore third = 
createTimerMessageStore(storeConfig.getStorePathRootDir(), false);
+        assertTrue(third.load());
+        assertEquals(50, third.getQueueOffset());
+        assertSnapshotFixtureSlots(third.getTimerWheel(), firstTime);
+    }
+
+    private void assertSnapshotFixtureSlots(TimerWheel wheel, long firstTime) {
+        long previousPosition = -1;
+        for (int i = 0; i < 50; i++) {
+            Slot slot = wheel.getSlot(firstTime + (long) i * precisionMs);
+            assertEquals(firstTime + (long) i * precisionMs, slot.timeMs);
+            assertEquals(slot.firstPos, slot.lastPos);
+            assertTrue(slot.firstPos > previousPosition);
+            previousPosition = slot.firstPos;
+        }
+    }
+
+    private void forceSnapshot(TimerMessageStore store) throws IOException {
+        store.getTimerFlushService().lastSnapshotTime = 0;
+        store.getTimerFlushService().flush();
+    }
+
+    private TimerWheel spyTimerWheel(TimerMessageStore store) throws Exception 
{
+        TimerWheel wheel = Mockito.spy(store.getTimerWheel());
+        Field field = TimerMessageStore.class.getDeclaredField("timerWheel");
+        field.setAccessible(true);
+        field.set(store, wheel);
+        return wheel;
+    }
+
+    private File timerCheckpointFile() {
+        return new File(storeConfig.getStorePathRootDir(), 
"config/timercheck");
+    }
+
+    private long readPersistedTimerOffset() throws IOException {
+        try (RandomAccessFile file = new 
RandomAccessFile(timerCheckpointFile(), "r")) {
+            file.seek(8);
+            return file.readLong();
+        }
+    }
+
     public ByteBuffer getOneMessage(String topic, int queue, long offset, int 
timeout) throws Exception {
         int retry = timeout / 100;
         while (retry-- > 0) {
@@ -691,6 +1218,79 @@ public class TimerMessageStoreTest {
         return msg;
     }
 
+    @Test
+    public void oldNewOldNewStalePendingBoundaryTest() throws Exception {
+        storeConfig.setMappedFileSizeTimerLog(TimerLog.UNIT_SIZE * 40);
+        storeConfig.setTimerWheelSnapshotFlush(true);
+        storeConfig.setTimerWheelSnapshotIntervalMs(0);
+        storeConfig.setTimerFlushIntervalMs(100);
+        final String topic = "TimerTest_oldNewOldNew";
+        long curr = System.currentTimeMillis() / precisionMs * precisionMs;
+        long t1 = curr + 60000, t2 = curr + 61000;
+
+        String base = StoreTestUtils.createBaseDir();
+        final TimerMessageStore new1 = createTimerMessageStore(base, false);
+        new1.load();
+        new1.start(true);
+        for (int i = 0; i < 50; i++) {
+            MessageExtBrokerInner inner = buildMessage(t1 + 100, topic, false);
+            transformTimerMessage(new1, inner);
+            assertEquals(PutMessageStatus.PUT_OK, 
messageStore.putMessage(inner).getPutMessageStatus());
+        }
+        await().atMost(5000, TimeUnit.MILLISECONDS).until(() -> 
new1.getCommitQueueOffset() == 50);
+        long target1 = 
new1.getTimerLog().getMappedFileQueue().getMaxWrotePosition();
+        String wheelPath = 
TimerMessageStore.getTimerWheelPath(storeConfig.getStorePathRootDir());
+        await().atMost(5000, TimeUnit.MILLISECONDS).until(() ->
+            new1.getTimerCheckpoint().getLastTimerLogFlushPos() >= target1 &&
+                TimerWheel.getMaxSnapshotFlag(wheelPath) == -1);
+        new1.shutdown();
+        long staleFlag = new1.getTimerCheckpoint().getLastTimerLogFlushPos();
+        // crash-leftover shape: a complete wheel image under a numeric flag 
beside the promoted base
+        Files.copy(new File(wheelPath).toPath(), new File(wheelPath + "." + 
staleFlag).toPath());
+
+        // old single-file period: base stays fresh, the stale snapshot is 
ignored and never cleaned
+        storeConfig.setTimerWheelSnapshotFlush(false);
+        final TimerMessageStore old = createTimerMessageStore(base, false);
+        old.load();
+        old.start(true);
+        for (int i = 0; i < 100; i++) {
+            MessageExtBrokerInner inner = buildMessage(t2 + 100, topic, false);
+            transformTimerMessage(old, inner);
+            assertEquals(PutMessageStatus.PUT_OK, 
messageStore.putMessage(inner).getPutMessageStatus());
+        }
+        await().atMost(5000, TimeUnit.MILLISECONDS).until(() -> 
old.getCommitQueueOffset() == 150);
+        long target2 = 
old.getTimerLog().getMappedFileQueue().getMaxWrotePosition();
+        await().atMost(5000, TimeUnit.MILLISECONDS).until(() ->
+            old.getTimerCheckpoint().getLastTimerLogFlushPos() >= target2);
+        // long interval: commitlog rolls and timerlog files expire, same call 
as the 30s scheduler
+        SelectMappedBufferResult sbr = old.getTimerLog().getWholeBuffer(100 * 
TimerLog.UNIT_SIZE);
+        sbr.getByteBuffer().position((100 * TimerLog.UNIT_SIZE) % 
storeConfig.getMappedFileSizeTimerLog() +
+            TimerLog.UNIT_PRE_SIZE_FOR_MSG);
+        long minPySim = sbr.getByteBuffer().getLong();
+        sbr.release();
+        
old.getTimerLog().getMappedFileQueue().deleteExpiredFileByOffsetForTimerLog(
+            minPySim, old.getTimerLog().getOffsetForLastUnit(), 
TimerLog.UNIT_SIZE);
+        long t2InBase = old.getTimerWheel().getNum(t2);
+        assertThat(t2InBase).isGreaterThanOrEqualTo(100);
+        old.shutdown();
+
+        byte[] baseBefore = Files.readAllBytes(new File(wheelPath).toPath());
+        File checkpointFile = new File(base, "config/timercheck");
+        byte[] checkpointBefore = Files.readAllBytes(checkpointFile.toPath());
+        storeConfig.setTimerWheelSnapshotFlush(true);
+        final TimerMessageStore new2 = createTimerMessageStore(base, false);
+        assertFalse(new2.load());
+        new2.shutdown();
+        assertArrayEquals(baseBefore, Files.readAllBytes(new 
File(wheelPath).toPath()));
+        assertArrayEquals(checkpointBefore, 
Files.readAllBytes(checkpointFile.toPath()));
+
+        assertTrue(new File(wheelPath + "." + staleFlag).delete());
+        final TimerMessageStore new3 = createTimerMessageStore(base, false);
+        assertTrue(new3.load());
+        assertEquals(t2InBase, new3.getTimerWheel().getNum(t2));
+        new3.shutdown();
+    }
+
     private class MyMessageArrivingListener implements MessageArrivingListener 
{
         @Override
         public void arriving(String topic, int queueId, long logicOffset, long 
tagsCode, long msgStoreTime,
diff --git 
a/store/src/test/java/org/apache/rocketmq/store/timer/TimerWheelTest.java 
b/store/src/test/java/org/apache/rocketmq/store/timer/TimerWheelTest.java
index 10d8cecc1f..22c3938f2d 100644
--- a/store/src/test/java/org/apache/rocketmq/store/timer/TimerWheelTest.java
+++ b/store/src/test/java/org/apache/rocketmq/store/timer/TimerWheelTest.java
@@ -20,9 +20,13 @@ import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
 
+import java.io.File;
 import java.io.IOException;
 
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertThrows;
+import static org.junit.Assert.assertTrue;
 
 public class TimerWheelTest {
 
@@ -142,6 +146,195 @@ public class TimerWheelTest {
         TimerWheel tmpWheel = new TimerWheel(baseDir, slotsTotal + 1, 
precisionMs);
     }
 
+    @Test
+    public void copyForSnapshotIsolationTest() throws Exception {
+        long delayedTime = defaultDelay + precisionMs;
+        timerWheel.putSlot(delayedTime, 1, 2, 3, 4);
+        timerWheel.copyForSnapshot();
+        // writes after the freeze must not leak into the snapshot
+        timerWheel.putSlot(delayedTime, 5, 6, 7, 8);
+        timerWheel.putSlot(delayedTime + precisionMs, 9, 10, 11, 12);
+        timerWheel.backup(12345);
+
+        TimerWheel snapWheel = new TimerWheel(baseDir, slotsTotal, 
precisionMs, 12345);
+        Slot slot = snapWheel.getSlot(delayedTime);
+        assertEquals(1, slot.firstPos);
+        assertEquals(2, slot.lastPos);
+        assertEquals(3, slot.num);
+        assertEquals(4, slot.magic);
+        assertEquals(-1, snapWheel.getSlot(delayedTime + precisionMs).timeMs);
+        snapWheel.shutdown();
+
+        timerWheel.copyForSnapshot();
+        timerWheel.backup(12345);
+        TimerWheel replacement = new TimerWheel(baseDir, slotsTotal, 
precisionMs, 12345);
+        try {
+            assertEquals(5, replacement.getSlot(delayedTime).firstPos);
+            assertEquals(6, replacement.getSlot(delayedTime).lastPos);
+            assertEquals(7, replacement.getSlot(delayedTime).num);
+            assertEquals(9, replacement.getSlot(delayedTime + 
precisionMs).firstPos);
+        } finally {
+            replacement.shutdown();
+        }
+    }
+
+    @Test
+    public void segmentedBackupRoundTripTest() throws Exception {
+        int bigSlots = 40000;
+        String bigFileName = baseDir + "_big";
+        TimerWheel bigWheel = new TimerWheel(bigFileName, bigSlots, 
precisionMs);
+        for (int i = 0; i < bigSlots; i++) {
+            bigWheel.putSlot(defaultDelay + (long) i * precisionMs, i, i + 1, 
i + 2, i + 3);
+        }
+        bigWheel.copyForSnapshot();
+        bigWheel.backup(67890);
+        assertEquals((long) bigSlots * 2 * Slot.SIZE, new File(bigFileName + 
".67890").length());
+        TimerWheel snapWheel = new TimerWheel(bigFileName, bigSlots, 
precisionMs, 67890);
+        for (int i = 0; i < bigSlots; i++) {
+            Slot slot = snapWheel.getRawSlot(defaultDelay + (long) i * 
precisionMs);
+            assertEquals(i, slot.firstPos);
+            assertEquals(i + 1, slot.lastPos);
+            assertEquals(i + 2, slot.num);
+            assertEquals(i + 3, slot.magic);
+        }
+        snapWheel.shutdown();
+        bigWheel.shutdown();
+        StoreTestUtils.deleteFile(bigFileName);
+        StoreTestUtils.deleteFile(bigFileName + ".67890");
+    }
+
+    @Test
+    public void promoteToBaseRoundTripTest() throws Exception {
+        // snapshot-mode wheel on a dedicated path holds no handle on base, so 
the atomic
+        // replace also succeeds on Windows, where a mmap-held base cannot be 
replaced
+        String dir = StoreTestUtils.createBaseDir();
+        assertTrue(new File(dir).mkdirs());
+        String wheelPath = dir + File.separator + 
TimerWheel.TIMER_WHEEL_FILE_NAME;
+        TimerWheel wheel = new TimerWheel(wheelPath, slotsTotal, precisionMs, 
-1, true);
+        long delayedTime = defaultDelay + precisionMs;
+        wheel.putSlot(delayedTime, 1, 2, 3, 4);
+        wheel.copyForSnapshot();
+        wheel.backup(100);
+        assertTrue(new File(wheelPath + ".100").exists());
+
+        wheel.promoteToBase(100);
+        assertFalse(new File(wheelPath + ".100").exists());
+        assertFalse(new File(wheelPath + ".100.tmp").exists());
+
+        // base now holds the snapshot content; read it via the non-snapshot 
(mmap) constructor
+        TimerWheel baseWheel = new TimerWheel(wheelPath, slotsTotal, 
precisionMs);
+        Slot slot = baseWheel.getSlot(delayedTime);
+        assertEquals(1, slot.firstPos);
+        assertEquals(2, slot.lastPos);
+        assertEquals(3, slot.num);
+        assertEquals(4, slot.magic);
+        baseWheel.shutdown();
+        wheel.shutdown();
+        StoreTestUtils.deleteFile(dir);
+    }
+
+    @Test
+    public void promoteToBaseReplacesOldBaseTest() throws Exception {
+        String dir = StoreTestUtils.createBaseDir();
+        assertTrue(new File(dir).mkdirs());
+        String wheelPath = dir + File.separator + 
TimerWheel.TIMER_WHEEL_FILE_NAME;
+        TimerWheel wheel = new TimerWheel(wheelPath, slotsTotal, precisionMs, 
-1, true);
+        long delayedTime = defaultDelay + precisionMs;
+
+        // first promote lays down an old base
+        wheel.putSlot(delayedTime, 1, 1, 1, 1);
+        wheel.copyForSnapshot();
+        wheel.backup(100);
+        wheel.promoteToBase(100);
+        assertTrue(new File(wheelPath).exists());
+        assertEquals((long) slotsTotal * 2 * Slot.SIZE, new 
File(wheelPath).length());
+
+        // second promote must REPLACE the existing base, not skip or fail
+        wheel.putSlot(delayedTime, 9, 9, 9, 9);
+        wheel.copyForSnapshot();
+        wheel.backup(200);
+        wheel.promoteToBase(200);
+        assertFalse(new File(wheelPath + ".200").exists());
+        assertEquals((long) slotsTotal * 2 * Slot.SIZE, new 
File(wheelPath).length());
+
+        TimerWheel baseWheel = new TimerWheel(wheelPath, slotsTotal, 
precisionMs);
+        Slot slot = baseWheel.getSlot(delayedTime);
+        assertEquals(9, slot.firstPos);
+        assertEquals(9, slot.num);
+        baseWheel.shutdown();
+        wheel.shutdown();
+        StoreTestUtils.deleteFile(dir);
+    }
+
+    @Test
+    public void missingSnapshotDoesNotPromoteTest() throws IOException {
+        long delayedTime = defaultDelay + precisionMs;
+        timerWheel.putSlot(delayedTime, 1, 2, 3, 4);
+        timerWheel.flush();
+        File baseFile = new File(baseDir);
+        File snapshotFile = new File(baseDir + ".100");
+        assertTrue(baseFile.isFile());
+        assertFalse(snapshotFile.exists());
+
+        assertThrows(IOException.class, () -> timerWheel.promoteToBase(100));
+        assertTrue(baseFile.isFile());
+        assertFalse(snapshotFile.exists());
+        assertEquals((long) slotsTotal * 2 * Slot.SIZE, baseFile.length());
+
+        TimerWheel reopened = new TimerWheel(baseDir, slotsTotal, precisionMs);
+        try {
+            Slot slot = reopened.getSlot(delayedTime);
+            assertEquals(delayedTime, slot.timeMs);
+            assertEquals(1, slot.firstPos);
+            assertEquals(2, slot.lastPos);
+            assertEquals(3, slot.num);
+            assertEquals(4, slot.magic);
+        } finally {
+            reopened.shutdown();
+        }
+    }
+
+    @Test
+    public void snapshotModeNoMmapTest() throws Exception {
+        String path = baseDir + "_snap";
+        // snapshot mode with no snapshot yet loads the base file but must not 
mmap it
+        TimerWheel snapWheel = new TimerWheel(path, slotsTotal, precisionMs, 
-1, true);
+        snapWheel.putSlot(defaultDelay + precisionMs, 1, 2, 3, 4);
+        snapWheel.flush(); // no-op in snapshot mode
+
+        TimerWheel baseReader = new TimerWheel(path, slotsTotal, precisionMs);
+        assertEquals(-1, baseReader.getSlot(defaultDelay + 
precisionMs).timeMs);
+        baseReader.shutdown();
+        // the in-memory wheel still holds the slot
+        assertEquals(3, snapWheel.getNum(defaultDelay + precisionMs));
+        snapWheel.shutdown();
+        StoreTestUtils.deleteFile(path);
+    }
+
+    @Test
+    public void promoteCleansLegacySnapshotsTest() throws Exception {
+        String dir = StoreTestUtils.createBaseDir();
+        assertTrue(new File(dir).mkdirs());
+        String wheelPath = dir + File.separator + 
TimerWheel.TIMER_WHEEL_FILE_NAME;
+        TimerWheel wheel = new TimerWheel(wheelPath, slotsTotal, precisionMs, 
-1, true);
+        wheel.putSlot(defaultDelay + precisionMs, 1, 2, 3, 4);
+        wheel.copyForSnapshot();
+        wheel.backup(100);
+        wheel.backup(200);
+        assertEquals(200, TimerWheel.getMaxSnapshotFlag(wheelPath));
+
+        wheel.promoteToBase(200);
+        assertEquals(-1, TimerWheel.getMaxSnapshotFlag(wheelPath));
+        assertFalse(new File(wheelPath + ".100").exists());
+        assertFalse(new File(wheelPath + ".200").exists());
+
+        TimerWheel baseReader = new TimerWheel(wheelPath, slotsTotal, 
precisionMs);
+        assertEquals(3, baseReader.getSlot(defaultDelay + precisionMs).num);
+        baseReader.shutdown();
+        wheel.shutdown();
+        StoreTestUtils.deleteFile(dir);
+    }
+
     @After
     public void shutdown() {
         if (null != timerWheel) {
@@ -149,6 +342,8 @@ public class TimerWheelTest {
         }
         if (null != baseDir) {
             StoreTestUtils.deleteFile(baseDir);
+            StoreTestUtils.deleteFile(baseDir + ".12345");
+            StoreTestUtils.deleteFile(baseDir + ".12345.tmp");
         }
     }
 

Reply via email to