This is an automated email from the ASF dual-hosted git repository.
ShannonDing 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 ac105b761e [ISSUE #11585] Fix AutoSwitchHA slave unable to rejoin
after same-epoch master restart (#11588)
ac105b761e is described below
commit ac105b761e42174630a84d731903a685037732de
Author: frotmo <[email protected]>
AuthorDate: Wed Nov 25 20:21:11 2026 +0800
[ISSUE #11585] Fix AutoSwitchHA slave unable to rejoin after same-epoch
master restart (#11588)
* [ISSUE #11585] Fix AutoSwitchHA slave unable to rejoin after same-epoch
master restart
The controller keeps the master epoch unchanged when the original master
restarts. AutoSwitchHAService.changeToMaster then rewrote the existing
epoch entry's start offset to the current max physical offset, while the
slave still held the original start offset. The two epoch entries could
never match in findConsistentPoint, so the slave kept failing with
"Failed to find a consistent point" and never rejoined the sync state set.
Keep the original epoch entry when the master epoch already exists locally.
A new epoch is still appended at the max physical offset as before.
Add a unit test for the same-epoch restart case and an AutoSwitchHA
integration test covering slave rejoin and ongoing replication.
* [ISSUE #11585] Remove unreachable epoch truncation in AutoSwitchHAService
Both callers reject masterEpoch < lastEpoch before appending, and the
same-epoch case returns early in appendEpochEntry, so the truncation
branch for lastEpoch > masterEpoch could never be executed. Remove it.
* [ISSUE #11585] Rewrite epoch entry if its start offset exceeds
maxPhyOffset
After an unclean shutdown the epoch file may record a start offset beyond
the recovered commitlog end. Reusing that entry on a same-epoch master
restart makes the slave's handshake treat its own tail as consistent and
the replicas can silently diverge. Reuse the existing entry only when its
start offset is within the local commitlog; otherwise rewrite it at
maxPhyOffset as before.
---
.../store/ha/autoswitch/AutoSwitchHAService.java | 43 ++++--
.../ha/autoswitch/AutoSwitchHAServiceTest.java | 168 +++++++++++++++++++++
.../store/ha/autoswitch/AutoSwitchHATest.java | 28 ++++
3 files changed, 229 insertions(+), 10 deletions(-)
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 9af47693f1..7ea988123a 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
@@ -141,11 +141,7 @@ public class AutoSwitchHAService extends DefaultHAService {
}
// Append new epoch to epochFile
- final EpochEntry newEpochEntry = new EpochEntry(masterEpoch,
this.defaultMessageStore.getMaxPhyOffset());
- if (this.epochCache.lastEpoch() >= masterEpoch) {
- this.epochCache.truncateSuffixByEpoch(masterEpoch);
- }
- this.epochCache.appendEntry(newEpochEntry);
+ final EpochEntry newEpochEntry = appendEpochEntry(masterEpoch);
// Waiting consume queue dispatch
while (defaultMessageStore.dispatchBehindBytes() > 0) {
@@ -209,11 +205,7 @@ public class AutoSwitchHAService extends DefaultHAService {
return false;
}
// Append new epoch to epochFile
- final EpochEntry newEpochEntry = new EpochEntry(masterEpoch,
this.defaultMessageStore.getMaxPhyOffset());
- if (this.epochCache.lastEpoch() >= masterEpoch) {
- this.epochCache.truncateSuffixByEpoch(masterEpoch);
- }
- this.epochCache.appendEntry(newEpochEntry);
+ final EpochEntry newEpochEntry = appendEpochEntry(masterEpoch);
this.defaultMessageStore.setStateMachineVersion(masterEpoch);
LOGGER.info("Change ha to master success, last role is master,
newMasterEpoch:{}, startOffset:{}",
@@ -221,6 +213,37 @@ public class AutoSwitchHAService extends DefaultHAService {
return true;
}
+ /**
+ * Append the master epoch to the epoch file. If the epoch already exists
locally, keep the original entry
+ * instead of rewriting its start offset with the current max physical
offset. A broker that restarts and is
+ * elected as the master again with the same epoch would otherwise move
the start offset of the epoch, and the
+ * slave holding the original start offset could never find a consistent
point, so it would never rejoin the
+ * sync state set.
+ * <p>
+ * The entry is only reused if its start offset is within the local
commitlog. The epoch file is not trimmed
+ * against the recovered commitlog on startup, so after an unclean
shutdown the recorded start offset may be
+ * greater than the recovered max physical offset. Reusing such an entry
would make the slave treat its own
+ * tail as consistent with the master, and the two replicas would silently
diverge.
+ */
+ private EpochEntry appendEpochEntry(final int masterEpoch) {
+ final int lastEpoch = this.epochCache.lastEpoch();
+ if (lastEpoch == masterEpoch) {
+ final EpochEntry existingEntry = this.epochCache.lastEntry();
+ final long maxPhyOffset =
this.defaultMessageStore.getMaxPhyOffset();
+ if (existingEntry.getStartOffset() <= maxPhyOffset) {
+ LOGGER.info("Epoch entry already exists locally, keep the
original startOffset. epoch:{}, startOffset:{}",
+ existingEntry.getEpoch(), existingEntry.getStartOffset());
+ return existingEntry;
+ }
+ LOGGER.warn("Epoch {} startOffset {} exceeds maxPhyOffset {},
rewrite the entry",
+ masterEpoch, existingEntry.getStartOffset(), maxPhyOffset);
+ this.epochCache.truncateSuffixByEpoch(masterEpoch);
+ }
+ final EpochEntry newEpochEntry = new EpochEntry(masterEpoch,
this.defaultMessageStore.getMaxPhyOffset());
+ this.epochCache.appendEntry(newEpochEntry);
+ return newEpochEntry;
+ }
+
@Override
public boolean changeToSlaveWhenMasterNotChange(String newMasterAddr, int
newMasterEpoch) {
final int lastEpoch = this.epochCache.lastEpoch();
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
new file mode 100644
index 0000000000..c33de6af77
--- /dev/null
+++
b/store/src/test/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHAServiceTest.java
@@ -0,0 +1,168 @@
+/*
+ * 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.rocketmq.store.ha.autoswitch;
+
+import java.io.File;
+import java.util.List;
+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.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+public class AutoSwitchHAServiceTest {
+
+ @Rule
+ public TemporaryFolder tempFolder = new TemporaryFolder();
+
+ @Test
+ public void testChangeToMasterWithSameEpochKeepsOriginalStartOffset()
throws Exception {
+ final String epochFilePath = epochFilePath();
+
+ AutoSwitchHAService haService = new AutoSwitchHAService();
+ haService.init(mockMessageStore(epochFilePath, 0L));
+ try {
+ assertTrue(haService.changeToMaster(1));
+ assertEpochEntry(haService, 1, 0L);
+ } finally {
+ haService.shutdown();
+ }
+
+ // Simulate the broker restart: the epoch file is recovered from disk
and the broker is elected
+ // as the master again with the same epoch, while the commitlog has
grown to 5802.
+ haService = new AutoSwitchHAService();
+ haService.init(mockMessageStore(epochFilePath, 5802L));
+ try {
+ assertTrue(haService.changeToMaster(1));
+ assertEpochEntry(haService, 1, 0L);
+ } finally {
+ haService.shutdown();
+ }
+ }
+
+ @Test
+ public void testChangeToMasterWithNewEpochAppendsEntryAtMaxPhyOffset()
throws Exception {
+ final String epochFilePath = epochFilePath();
+
+ AutoSwitchHAService haService = new AutoSwitchHAService();
+ haService.init(mockMessageStore(epochFilePath, 0L));
+ try {
+ assertTrue(haService.changeToMaster(1));
+ } finally {
+ haService.shutdown();
+ }
+
+ haService = new AutoSwitchHAService();
+ haService.init(mockMessageStore(epochFilePath, 5802L));
+ try {
+ assertTrue(haService.changeToMaster(2));
+ final List<EpochEntry> epochEntries = haService.getEpochEntries();
+ assertEquals(2, epochEntries.size());
+ assertEquals(1, epochEntries.get(0).getEpoch());
+ assertEquals(0L, epochEntries.get(0).getStartOffset());
+ assertEquals(2, epochEntries.get(1).getEpoch());
+ assertEquals(5802L, epochEntries.get(1).getStartOffset());
+ } finally {
+ haService.shutdown();
+ }
+ }
+
+ @Test
+ public void
testChangeToMasterWhenLastRoleIsMasterWithSameEpochKeepsOriginalStartOffset()
throws Exception {
+ final String epochFilePath = epochFilePath();
+
+ AutoSwitchHAService haService = new AutoSwitchHAService();
+ haService.init(mockMessageStore(epochFilePath, 0L));
+ try {
+ assertTrue(haService.changeToMaster(1));
+ } finally {
+ haService.shutdown();
+ }
+
+ haService = new AutoSwitchHAService();
+ haService.init(mockMessageStore(epochFilePath, 5802L));
+ try {
+ assertTrue(haService.changeToMasterWhenLastRoleIsMaster(1));
+ assertEpochEntry(haService, 1, 0L);
+ } finally {
+ haService.shutdown();
+ }
+ }
+
+ @Test
+ public void
testChangeToMasterRewritesEpochWhenStartOffsetExceedsMaxPhyOffset() throws
Exception {
+ final String epochFilePath = epochFilePath();
+
+ final DefaultMessageStore messageStore =
mockMessageStore(epochFilePath, 0L);
+ AutoSwitchHAService haService = new AutoSwitchHAService();
+ haService.init(messageStore);
+ try {
+ assertTrue(haService.changeToMaster(1));
+ when(messageStore.getMaxPhyOffset()).thenReturn(5000L);
+ assertTrue(haService.changeToMaster(2));
+ final EpochEntry secondEntry = haService.getEpochEntries().get(1);
+ assertEquals(2, secondEntry.getEpoch());
+ assertEquals(5000L, secondEntry.getStartOffset());
+ } finally {
+ haService.shutdown();
+ }
+
+ // Restart after an unclean shutdown: the commitlog recovers to 4800,
before the recorded epoch start,
+ // so the recorded entry must be rewritten instead of being reused.
+ haService = new AutoSwitchHAService();
+ haService.init(mockMessageStore(epochFilePath, 4800L));
+ try {
+ assertTrue(haService.changeToMaster(2));
+ final List<EpochEntry> epochEntries = haService.getEpochEntries();
+ assertEquals(2, epochEntries.size());
+ assertEquals(1, epochEntries.get(0).getEpoch());
+ assertEquals(0L, epochEntries.get(0).getStartOffset());
+ assertEquals(2, epochEntries.get(1).getEpoch());
+ assertEquals(4800L, epochEntries.get(1).getStartOffset());
+ } finally {
+ haService.shutdown();
+ }
+ }
+
+ private String epochFilePath() {
+ return new File(tempFolder.getRoot(),
"EpochFileCache").getAbsolutePath();
+ }
+
+ private DefaultMessageStore mockMessageStore(final String epochFilePath,
final long maxPhyOffset) {
+ final DefaultMessageStore messageStore =
mock(DefaultMessageStore.class);
+ final MessageStoreConfig messageStoreConfig = new MessageStoreConfig();
+ messageStoreConfig.setStorePathEpochFile(epochFilePath);
+
when(messageStore.getMessageStoreConfig()).thenReturn(messageStoreConfig);
+ when(messageStore.getBrokerConfig()).thenReturn(new BrokerConfig());
+ when(messageStore.getMaxPhyOffset()).thenReturn(maxPhyOffset);
+ return messageStore;
+ }
+
+ private void assertEpochEntry(final AutoSwitchHAService haService, final
int epoch, final long startOffset) {
+ final List<EpochEntry> epochEntries = haService.getEpochEntries();
+ assertEquals(1, epochEntries.size());
+ assertEquals(epoch, epochEntries.get(0).getEpoch());
+ assertEquals(startOffset, epochEntries.get(0).getStartOffset());
+ }
+}
\ No newline at end of file
diff --git
a/store/src/test/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHATest.java
b/store/src/test/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHATest.java
index 503706e5b9..1627e2b7b7 100644
---
a/store/src/test/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHATest.java
+++
b/store/src/test/java/org/apache/rocketmq/store/ha/autoswitch/AutoSwitchHATest.java
@@ -524,6 +524,34 @@ public class AutoSwitchHATest {
UtilAll.deleteFile(file);
}
+ @Test
+ public void testSlaveRejoinAfterMasterRestartWithSameEpoch() throws
Exception {
+ init(defaultMappedFileSize);
+ ((AutoSwitchHAService)
this.messageStore1.getHaService()).setSyncStateSet(new
HashSet<>(Collections.singletonList(1L)));
+ assertTrue(changeMasterAndPutMessage(this.messageStore1,
this.storeConfig1, this.messageStore2, 2, this.storeConfig2, 1,
store1HaAddress, 10));
+ checkMessage(this.messageStore2, 10, 0);
+
+ // Restart the master, the controller elects it as master again with
the same epoch
+ this.messageStore1 = shutdownStore(this.messageStore1);
+ storeConfig1.setBrokerRole(BrokerRole.SYNC_MASTER);
+ messageStore1 = buildMessageStore(storeConfig1, 1L);
+ assertTrue(messageStore1.load());
+ messageStore1.start();
+ AutoSwitchHAService masterHaService = (AutoSwitchHAService)
messageStore1.getHaService();
+ masterHaService.setSyncStateSet(new
HashSet<>(Collections.singletonList(1L)));
+ assertTrue(masterHaService.changeToMaster(1));
+ assertEquals(0L,
masterHaService.getEpochEntries().get(0).getStartOffset());
+
+ // The old slave should reconnect, be added back to the sync state set
and continue to replicate
+ await().atMost(30, TimeUnit.SECONDS).until(() ->
masterHaService.getConnectionCount().get() > 0);
+ await().atMost(30, TimeUnit.SECONDS).until(() ->
masterHaService.isSynchronizingSyncStateSet());
+
+ for (int i = 0; i < 5; i++) {
+ assertTrue(messageStore1.putMessage(buildMessage()).isOk());
+ }
+ checkMessage(this.messageStore2, 15, 0);
+ }
+
private DefaultMessageStore shutdownStore(DefaultMessageStore
messageStore) {
if (messageStore != null) {
messageStore.shutdown();