From 5910be5be7f4bfadbdc6903b70452735f82c0201 Mon Sep 17 00:00:00 2001 From: kayokoi Zhang <113896798+wozhenbang2004@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:02:42 -0800 Subject: [PATCH 1/3] Reject AutoSwitch HA truncation below the confirmed offset Related to #11603. --- .../ha/autoswitch/AutoSwitchHAClient.java | 18 +++++- .../AutoSwitchHAStateValidationTest.java | 59 +++++++++++++++++++ 2 files changed, 75 insertions(+), 2 deletions(-) diff --git a/store/src/main/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAClient.java b/store/src/main/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAClient.java index 665d9aae3b0..2a6a2481072 100644 --- a/store/src/main/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAClient.java +++ b/store/src/main/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAClient.java @@ -40,6 +40,7 @@ import org.apache.rocketmq.store.ha.HAConnectionState; import org.apache.rocketmq.store.ha.io.AbstractHAReader; import org.apache.rocketmq.store.ha.io.HAWriter; +import org.rocksdb.RocksDBException; public class AutoSwitchHAClient extends ServiceThread implements HAClient { @@ -459,8 +460,7 @@ private boolean doTruncate(List masterEpochEntries, long masterEndOf LOGGER.error("Failed to find a consistent point between masterEpoch:{} and slaveEpoch:{}", masterEpochEntries, localEpochEntries); return false; } - if (!this.messageStore.truncateFiles(truncateOffset)) { - LOGGER.error("Failed to truncate slave log to {}", truncateOffset); + if (!truncateSlaveLog(truncateOffset)) { return false; } final long maxPhyOffset = this.messageStore.getMaxPhyOffset(); @@ -478,6 +478,20 @@ private boolean doTruncate(List masterEpochEntries, long masterEndOf return true; } + boolean truncateSlaveLog(long truncateOffset) throws RocksDBException { + final long confirmOffset = this.messageStore.getConfirmOffset(); + if (truncateOffset < confirmOffset) { + LOGGER.error("Refusing to truncate slave log below confirmOffset: brokerId={}, masterHaAddress={}, truncateOffset={}, confirmOffset={}", + this.brokerId, getHaMasterAddress(), truncateOffset, confirmOffset); + return false; + } + if (!this.messageStore.truncateFiles(truncateOffset)) { + LOGGER.error("Failed to truncate slave log to {}", truncateOffset); + return false; + } + return true; + } + class HAClientReader extends AbstractHAReader { @Override diff --git a/store/src/test/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAStateValidationTest.java b/store/src/test/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAStateValidationTest.java index c7ed78058d3..170ad9d404e 100644 --- a/store/src/test/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAStateValidationTest.java +++ b/store/src/test/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAStateValidationTest.java @@ -21,16 +21,22 @@ import java.nio.ByteBuffer; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; +import java.util.Collections; import java.util.concurrent.atomic.AtomicInteger; import org.apache.rocketmq.common.BrokerConfig; +import org.apache.rocketmq.remoting.protocol.EpochEntry; import org.apache.rocketmq.store.DefaultMessageStore; import org.apache.rocketmq.store.config.MessageStoreConfig; import org.apache.rocketmq.store.ha.HAConnectionState; import org.junit.Test; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class AutoSwitchHAStateValidationTest { @@ -91,6 +97,59 @@ public void testClientReaderHandlesKnownMasterStateOrdinals() throws Exception { HAConnectionState.TRANSFER.ordinal(), AutoSwitchHAConnection.TRANSFER_HEADER_SIZE)); } + @Test + public void testTruncateSlaveLogProtectsConfirmOffset() throws Exception { + AutoSwitchHAService haService = mock(AutoSwitchHAService.class); + DefaultMessageStore messageStore = mock(DefaultMessageStore.class); + when(haService.getDefaultMessageStore()).thenReturn(messageStore); + when(messageStore.getBrokerConfig()).thenReturn(new BrokerConfig()); + when(messageStore.getMessageStoreConfig()).thenReturn(new MessageStoreConfig()); + when(messageStore.getConfirmOffset()).thenReturn(1024L); + + AutoSwitchHAClient client = new AutoSwitchHAClient(haService, messageStore, new EpochFileCache(), 1L); + try { + assertFalse(client.truncateSlaveLog(1023L)); + verify(messageStore, never()).truncateFiles(anyLong()); + } finally { + client.shutdown(); + } + } + + @Test + public void testClientHandshakeAtConfirmOffset() throws Exception { + long confirmOffset = 1024L; + int epoch = 1; + AutoSwitchHAService haService = mock(AutoSwitchHAService.class); + DefaultMessageStore messageStore = mock(DefaultMessageStore.class); + when(haService.getDefaultMessageStore()).thenReturn(messageStore); + when(messageStore.getBrokerConfig()).thenReturn(new BrokerConfig()); + when(messageStore.getMessageStoreConfig()).thenReturn(new MessageStoreConfig()); + when(messageStore.getConfirmOffset()).thenReturn(confirmOffset); + when(messageStore.getMaxPhyOffset()).thenReturn(confirmOffset); + when(messageStore.truncateFiles(confirmOffset)).thenReturn(true); + EpochFileCache epochCache = new EpochFileCache(); + epochCache.initCacheFromEntries(Collections.singletonList(new EpochEntry(epoch, 0L))); + + AutoSwitchHAClient client = new AutoSwitchHAClient(haService, messageStore, epochCache, 1L); + try { + client.changeCurrentState(HAConnectionState.HANDSHAKE); + ByteBuffer frame = ByteBuffer.allocate(AutoSwitchHAConnection.HANDSHAKE_HEADER_SIZE + + AutoSwitchHAConnection.EPOCH_ENTRY_SIZE); + frame.putInt(HAConnectionState.HANDSHAKE.ordinal()); + frame.putInt(AutoSwitchHAConnection.EPOCH_ENTRY_SIZE); + frame.putLong(confirmOffset); + frame.putInt(epoch); + frame.putInt(epoch); + frame.putLong(0L); + + assertTrue(client.new HAClientReader().processReadResult(frame)); + assertEquals(HAConnectionState.TRANSFER, client.getCurrentState()); + verify(messageStore).truncateFiles(confirmOffset); + } finally { + client.shutdown(); + } + } + private boolean processMasterState(int stateOrdinal, int headerSize) throws Exception { AutoSwitchHAService haService = mock(AutoSwitchHAService.class); DefaultMessageStore messageStore = mock(DefaultMessageStore.class); From cf0f0f56ccf0fc2970cb5834f181aea87ee249fa Mon Sep 17 00:00:00 2001 From: kayokoi Zhang <113896798+wozhenbang2004@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:41:16 -0800 Subject: [PATCH 2/3] [ISSUE #11603] Keep broker fencing and follower refusal in effect --- .../broker/controller/ReplicasManager.java | 16 ++++---- docs/en/controller/confirmed-data-recovery.md | 38 ++++++++++++------- docs/en/controller/deploy.md | 5 +++ .../ha/autoswitch/AutoSwitchHAClient.java | 7 ++++ 4 files changed, 44 insertions(+), 22 deletions(-) diff --git a/broker/src/main/java/org/apache/rocketmq/broker/controller/ReplicasManager.java b/broker/src/main/java/org/apache/rocketmq/broker/controller/ReplicasManager.java index b4bb8ddb745..fe1da55864f 100644 --- a/broker/src/main/java/org/apache/rocketmq/broker/controller/ReplicasManager.java +++ b/broker/src/main/java/org/apache/rocketmq/broker/controller/ReplicasManager.java @@ -618,15 +618,15 @@ private boolean registerBrokerToController() { if (responsePair == null) return false; RegisterBrokerToControllerResponseHeader response = responsePair.getObject1(); - if (!Objects.equals(this.brokerStartupGeneration, response.getBrokerStartupGeneration()) - || !this.brokerStartupId.equals(response.getBrokerStartupId()) || response.getMasterEpoch() == null) { - LOGGER.error("Controller did not acknowledge this broker startup; upgrade the controller before starting this broker"); - this.startupRegistered = false; - this.roleReady = false; - setFenced(true); - return false; - } synchronized (this) { + if (!Objects.equals(this.brokerStartupGeneration, response.getBrokerStartupGeneration()) + || !this.brokerStartupId.equals(response.getBrokerStartupId()) || response.getMasterEpoch() == null) { + LOGGER.error("Controller did not acknowledge this broker startup; upgrade the controller before starting this broker"); + this.startupRegistered = false; + this.roleReady = false; + setFenced(true); + return false; + } this.startupMasterEpoch = Math.max(this.startupMasterEpoch, response.getMasterEpoch()); this.startupRegistered = true; } diff --git a/docs/en/controller/confirmed-data-recovery.md b/docs/en/controller/confirmed-data-recovery.md index 247b0ca3730..e3f02f3116d 100644 --- a/docs/en/controller/confirmed-data-recovery.md +++ b/docs/en/controller/confirmed-data-recovery.md @@ -4,7 +4,9 @@ In controller mode, a replica refuses a handshake that would truncate its log be `confirmOffset`. The refusal is saved beside `storePathEpochFile`, with the suffix `.confirmed-offset-guard`. Reconnecting, restarting, changing the master address or receiving a larger offset does not remove it. A damaged guard record stops initialization instead of enabling -replication. +replication. The refusal blocks the follower's HA handshake. It does not freeze the local store +or stop normal retention. Stop the refused replica and preserve its store before attempting +recovery. If saving a refusal fails, the running follower still refuses handshakes and retries saving the same evidence. Resolve the storage failure before restarting it: evidence which never reached durable @@ -18,16 +20,19 @@ force that replica to join. ## Upgrade order and restart behavior -Coordinate the upgrade across the controller group and its brokers. Upgrade every controller before -starting an upgraded broker, and upgrade every broker in the affected group before relying on the -new startup-epoch behavior. The guarantee does not apply to mixed-version deployments. +Coordinate the upgrade across the controller group and its brokers. Upgrade every controller member, +including controllers embedded in NameServers, before starting an upgraded broker. Do not let an +older controller rejoin the group. A startup acknowledgment comes from the current leader and does +not establish that the other members support the new registration. Upgrade every broker in the +affected group before relying on the new startup-epoch behavior. Before upgrading, take consistent backups of the controller snapshots and logs and the corresponding -broker stores and identities. After accepting a new startup registration, do not downgrade either -component in place over the newer state. Older controllers do not apply the same startup metadata, -and older brokers do not honor the new refusal guard or startup registration. Rollback requires -coordinated recovery from compatible controller and broker backups and reconciliation of any writes -since those backups. +broker stores and identities. Once the first new startup registration commits, do not downgrade +either component in place over the newer state. A timed-out request may still commit; if the outcome +is unknown, treat it as committed for rollback decisions. Older controllers do not apply the same +startup metadata, and older brokers do not honor the new refusal guard or startup registration. +Rollback requires coordinated recovery from compatible controller and broker backups and +reconciliation of any writes since those backups. Each broker startup persists a monotonically increasing generation beside `storePathBrokerIdentity` with the suffix `-startup`, and uses a fresh startup ID for registration. The controller persists the @@ -36,10 +41,14 @@ with another startup ID, is refused. An upgraded broker stays fenced if the cont acknowledge its startup identity. When the current master restarts, the controller grants a new master epoch without reducing the -SyncStateSet. The broker durably records that epoch at the recovered log end before enabling writes. +SyncStateSet. The broker records that epoch at the recovered log end before enabling writes. Thus replacement messages cannot extend the previous epoch. A follower restart does not advance the group's master epoch. Duplicate grants in one startup retain the original epoch boundary. +The broker replaces its startup, epoch, and refusal metadata files atomically on filesystems that +support atomic replacement. On Windows, RocketMQ does not sync the parent directory; do not assume +an atomic replacement will survive a power loss. + Keep the broker identity and its startup metadata together. Restoring an old startup counter is not a supported way to rejoin an existing broker identity; the controller may correctly refuse it. Use a new replica identity for a replacement store. @@ -83,10 +92,11 @@ the refused member, clear its guard, or infer a rollback point from its first re 4. Start the replacement as a follower of the selected group. It copies the master's retained CommitLog; it does not reconstruct expired or missing history. Keep the old replica stopped, so its address and broker identity cannot be reused concurrently. -5. Check actual message contents and queue order over the required range, the epoch history, - `maxOffset`, `confirmOffset`, checkpoint and ConsumeQueue progress. Confirm that new messages also - replicate. Equal offsets alone are insufficient. Recheck after a normal restart of the new - replica before considering the replacement complete. +5. Read and compare actual messages and queue order over the required range, and confirm that new + messages also replicate. Check the epoch history, `maxOffset`, `confirmOffset`, checkpoint and + ConsumeQueue progress separately. A matching maximum offset in runtime stats does not establish + the confirmed offset or the message contents. Recheck after a normal restart of the new replica + before considering the replacement complete. 6. Retire the old stopped identity using the existing controller administration procedure only after the replacement is healthy. Retiring the identity does not remove the need to retain and reconcile the preserved data and refusal record. diff --git a/docs/en/controller/deploy.md b/docs/en/controller/deploy.md index 84849510ef3..a6458db9852 100644 --- a/docs/en/controller/deploy.md +++ b/docs/en/controller/deploy.md @@ -97,6 +97,11 @@ The specific behavior is shown in the following table: ## Upgrade Considerations +If your Controller-mode group already uses persistent BrokerIDs and you are upgrading to a version +with confirmed-offset protection, follow the +[Controller-first upgrade and rollback guide](confirmed-data-recovery.md#upgrade-order-and-restart-behavior). +The older BrokerID migration below does not apply: keep the Controller data and broker epoch files. + From the compatibility statements above, it can be seen that NameServer can be upgraded normally without compatibility issues. In the case where the Nameserver is not to be upgraded, the controller component can be deployed independently to obtain switching capabilities. For broker upgrades, there are two cases: 1. Master-Slave deployment is upgraded to controller switching architecture diff --git a/store/src/main/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAClient.java b/store/src/main/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAClient.java index ac943c1474c..bc2583157eb 100644 --- a/store/src/main/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAClient.java +++ b/store/src/main/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAClient.java @@ -390,6 +390,13 @@ public void run() { this.flowMonitor.shutdown(true); return; case READY: + final ConfirmedOffsetGuard guard = this.haService.getConfirmedOffsetGuard(); + if (guard.isBlocked()) { + // Retry the local record without changing the refused follower's history. + guard.ensurePersisted(); + waitForRunning(1000 * 5); + continue; + } // Truncate invalid msg first final long truncateOffset = AutoSwitchHAClient.this.haService.truncateInvalidMsg(); if (truncateOffset >= 0 && !AutoSwitchHAClient.this.epochCache.truncateSuffixByOffset(truncateOffset)) { From ca494f67fad3a9a698f661a3391a6b246799b1c4 Mon Sep 17 00:00:00 2001 From: kayokoi Zhang <113896798+wozhenbang2004@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:09:50 -0800 Subject: [PATCH 3/3] Handle symlinked epoch checkpoint directories and size the HA recovery test --- .../rocketmq/common/utils/CheckpointFile.java | 5 ++++- store/BUILD.bazel | 1 + .../ha/autoswitch/AutoSwitchHAService.java | 7 ++++-- .../autoswitch/AutoSwitchHAServiceTest.java | 22 +++++++++++++++++++ 4 files changed, 32 insertions(+), 3 deletions(-) diff --git a/common/src/main/java/org/apache/rocketmq/common/utils/CheckpointFile.java b/common/src/main/java/org/apache/rocketmq/common/utils/CheckpointFile.java index efb65717bb3..176323d7470 100644 --- a/common/src/main/java/org/apache/rocketmq/common/utils/CheckpointFile.java +++ b/common/src/main/java/org/apache/rocketmq/common/utils/CheckpointFile.java @@ -222,7 +222,10 @@ public synchronized void writeAtomically(final List entries) throws IOExcepti if (path.getFileName() == null || parent == null) { throw new IOException("Invalid checkpoint path: " + this.filePath); } - Files.createDirectories(parent); + // createDirectories rejects a directory symlink in the last component, such as /tmp on macOS. + if (!Files.isDirectory(parent)) { + Files.createDirectories(parent); + } final Path temporaryFile = Files.createTempFile(parent, "checkpoint-", ".tmp"); try { try (FileChannel channel = FileChannel.open(temporaryFile, StandardOpenOption.WRITE)) { diff --git a/store/BUILD.bazel b/store/BUILD.bazel index 66af7d6b45c..cfef487b20b 100644 --- a/store/BUILD.bazel +++ b/store/BUILD.bazel @@ -78,6 +78,7 @@ GenTestRules( "src/test/java/org/apache/rocketmq/store/dledger/DLedgerMultiPathTest", ], medium_tests = [ + "src/test/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAHistoryRecoveryTest", "src/test/java/org/apache/rocketmq/store/DefaultMessageStoreTest", "src/test/java/org/apache/rocketmq/store/HATest", "src/test/java/org/apache/rocketmq/store/dledger/DLedgerCommitlogTest", diff --git a/store/src/main/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAService.java b/store/src/main/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAService.java index 2c7f7d8826d..15817eb1015 100644 --- a/store/src/main/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAService.java +++ b/store/src/main/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAService.java @@ -85,10 +85,13 @@ public AutoSwitchHAService() { @Override public void init(final DefaultMessageStore defaultMessageStore) throws IOException { final Path epochFilePath = Paths.get(defaultMessageStore.getMessageStoreConfig().getStorePathEpochFile()).toAbsolutePath(); - if (epochFilePath.getFileName() == null || epochFilePath.getParent() == null) { + final Path parent = epochFilePath.getParent(); + if (epochFilePath.getFileName() == null || parent == null) { throw new IOException("Invalid epoch file path: " + epochFilePath); } - Files.createDirectories(epochFilePath.getParent()); + if (!Files.isDirectory(parent)) { + Files.createDirectories(parent); + } this.epochCache = new EpochFileCache(epochFilePath.toString()); if (!this.epochCache.initCacheFromFile()) { throw new IOException("Failed to load epoch history: " + epochFilePath); diff --git a/store/src/test/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAServiceTest.java b/store/src/test/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAServiceTest.java index c91f3cef8bb..a47c739ccbf 100644 --- a/store/src/test/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAServiceTest.java +++ b/store/src/test/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAServiceTest.java @@ -27,6 +27,7 @@ import org.apache.rocketmq.remoting.protocol.EpochEntry; import org.apache.rocketmq.store.DefaultMessageStore; import org.apache.rocketmq.store.config.MessageStoreConfig; +import org.junit.Assume; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; @@ -47,6 +48,27 @@ public class AutoSwitchHAServiceTest { @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); + @Test + public void testEpochCheckpointUnderSymlinkedDirectory() throws Exception { + final Path directory = tempFolder.newFolder("store").toPath(); + final Path link = directory.resolveSibling("link"); + try { + Files.createSymbolicLink(link, directory); + } catch (IOException | UnsupportedOperationException e) { + Assume.assumeNoException("Symbolic links are unavailable on this filesystem", e); + } + final AutoSwitchHAService service = new AutoSwitchHAService(); + service.init(mockMessageStore(link.resolve("epoch").toString(), 0)); + try { + assertTrue(service.changeToMaster(1)); + } finally { + service.shutdown(); + } + final EpochFileCache reloaded = new EpochFileCache(directory.resolve("epoch").toString()); + assertTrue(reloaded.initCacheFromFile()); + assertEquals(new EpochEntry(1, 0), reloaded.lastEntry()); + } + @Test public void testChangeToMasterWithSameEpochKeepsOriginalStartOffset() throws Exception { final String epochFilePath = epochFilePath();