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 a1506fec5d [ISSUE #11215] Fix offset-init race that drops the first 
message with CONSUME_FROM_LAST_OFFSET (#11216)
a1506fec5d is described below

commit a1506fec5ddec1a0507afe2135ddc76ccfad46ac
Author: ymwneu <[email protected]>
AuthorDate: Tue Nov 24 17:43:09 2026 +0800

    [ISSUE #11215] Fix offset-init race that drops the first message with 
CONSUME_FROM_LAST_OFFSET (#11216)
    
    When a consumer using CONSUME_FROM_LAST_OFFSET queries the offset of a
    brand-new queue with no stored offset, the broker returned QUERY_NOT_FOUND
    for an empty queue, and the client fell back to a separate GET_MAX_OFFSET
    request. A message appended between the two non-atomic requests pinned the
    start offset at 1 and skipped the message at offset 0 forever.
    
    Add MessageStore#shouldInitConsumeOffsetToZero to centralize the decision:
    an empty queue (maxOffset == 0) starts from 0, a young queue whose first
    message is still in memory starts from 0, otherwise start from the tail so
    aged history is not replayed. ConsumerManageProcessor,
    PopMessageProcessor#getInitOffset and BroadcastOffsetManager#getOffset all
    delegate to it; ConsumerManageProcessor falls back to QUERY_NOT_FOUND when
    the queue state cannot be determined.
    
    Fixes #11215
---
 .../broker/offset/BroadcastOffsetManager.java      |  2 +-
 .../broker/processor/ConsumerManageProcessor.java  | 26 ++++++--
 .../broker/processor/PopMessageProcessor.java      |  5 +-
 .../broker/offset/BroadcastOffsetManagerTest.java  | 12 +++-
 .../processor/ConsumerManageProcessorTest.java     | 73 +++++++++++++++++++++-
 .../broker/processor/PopMessageProcessorTest.java  | 20 ++++++
 .../org/apache/rocketmq/store/MessageStore.java    | 25 ++++++++
 7 files changed, 149 insertions(+), 14 deletions(-)

diff --git 
a/broker/src/main/java/org/apache/rocketmq/broker/offset/BroadcastOffsetManager.java
 
b/broker/src/main/java/org/apache/rocketmq/broker/offset/BroadcastOffsetManager.java
index 79bb0c771d..f2345643c8 100644
--- 
a/broker/src/main/java/org/apache/rocketmq/broker/offset/BroadcastOffsetManager.java
+++ 
b/broker/src/main/java/org/apache/rocketmq/broker/offset/BroadcastOffsetManager.java
@@ -114,7 +114,7 @@ public class BroadcastOffsetManager extends ServiceThread {
                 
brokerController.getConsumerOffsetManager().queryOffset(broadcastGroupId(groupId),
 topic, queueId);
         }
         if (storeOffset < 0) {
-            if 
(this.brokerController.getMessageStore().checkInMemByConsumeOffset(topic, 
queueId, 0, 1)) {
+            if 
(this.brokerController.getMessageStore().shouldInitConsumeOffsetToZero(topic, 
queueId)) {
                 storeOffset = 0;
             } else {
                 storeOffset = 
brokerController.getMessageStore().getMaxOffsetInQueue(topic, queueId, true);
diff --git 
a/broker/src/main/java/org/apache/rocketmq/broker/processor/ConsumerManageProcessor.java
 
b/broker/src/main/java/org/apache/rocketmq/broker/processor/ConsumerManageProcessor.java
index 48ac7e6d87..949e6e67d2 100644
--- 
a/broker/src/main/java/org/apache/rocketmq/broker/processor/ConsumerManageProcessor.java
+++ 
b/broker/src/main/java/org/apache/rocketmq/broker/processor/ConsumerManageProcessor.java
@@ -44,6 +44,7 @@ import 
org.apache.rocketmq.remoting.protocol.statictopic.TopicQueueMappingUtils;
 import org.apache.rocketmq.remoting.rpc.RpcClientUtils;
 import org.apache.rocketmq.remoting.rpc.RpcRequest;
 import org.apache.rocketmq.remoting.rpc.RpcResponse;
+import org.apache.rocketmq.store.exception.ConsumeQueueException;
 
 import static 
org.apache.rocketmq.remoting.protocol.RemotingCommand.buildErrorResponse;
 
@@ -322,15 +323,10 @@ public class ConsumerManageProcessor implements 
NettyRequestProcessor {
             response.setCode(ResponseCode.SUCCESS);
             response.setRemark(null);
         } else {
-            long minOffset =
-                
this.brokerController.getMessageStore().getMinOffsetInQueue(requestHeader.getTopic(),
-                    requestHeader.getQueueId());
             if (requestHeader.getSetZeroIfNotFound() != null && 
Boolean.FALSE.equals(requestHeader.getSetZeroIfNotFound())) {
                 response.setCode(ResponseCode.QUERY_NOT_FOUND);
                 response.setRemark("Not found, do not set to zero, maybe this 
group boot first");
-            } else if (minOffset <= 0
-                && 
this.brokerController.getMessageStore().checkInMemByConsumeOffset(
-                requestHeader.getTopic(), requestHeader.getQueueId(), 0, 1)) {
+            } else if (this.shouldInitConsumeOffsetToZero(requestHeader)) {
                 responseHeader.setOffset(0L);
                 response.setCode(ResponseCode.SUCCESS);
                 response.setRemark(null);
@@ -347,4 +343,22 @@ public class ConsumerManageProcessor implements 
NettyRequestProcessor {
 
         return response;
     }
+
+    /**
+     * Delegates to {@link 
org.apache.rocketmq.store.MessageStore#shouldInitConsumeOffsetToZero(String, 
int)}.
+     * If the store cannot determine the queue state, falls back to 
QUERY_NOT_FOUND so the SDK performs
+     * its own GET_MAX_OFFSET step (same as pre-fix behavior).
+     */
+    private boolean 
shouldInitConsumeOffsetToZero(QueryConsumerOffsetRequestHeader requestHeader) {
+        try {
+            return 
this.brokerController.getMessageStore().shouldInitConsumeOffsetToZero(
+                requestHeader.getTopic(), requestHeader.getQueueId());
+        } catch (ConsumeQueueException e) {
+            // Cannot confirm the queue is empty when max offset is 
unavailable; fall back to
+            // QUERY_NOT_FOUND so the SDK performs its GET_MAX_OFFSET step 
(same as pre-fix behavior).
+            LOGGER.warn("shouldInitConsumeOffsetToZero failed, fallback to 
QUERY_NOT_FOUND, topic={} queueId={}",
+                requestHeader.getTopic(), requestHeader.getQueueId(), e);
+            return false;
+        }
+    }
 }
diff --git 
a/broker/src/main/java/org/apache/rocketmq/broker/processor/PopMessageProcessor.java
 
b/broker/src/main/java/org/apache/rocketmq/broker/processor/PopMessageProcessor.java
index 779e6fef2d..e9ca8436ea 100644
--- 
a/broker/src/main/java/org/apache/rocketmq/broker/processor/PopMessageProcessor.java
+++ 
b/broker/src/main/java/org/apache/rocketmq/broker/processor/PopMessageProcessor.java
@@ -912,9 +912,8 @@ public class PopMessageProcessor implements 
NettyRequestProcessor {
         if (ConsumeInitMode.MIN == initMode || 
topic.startsWith(MixAll.RETRY_GROUP_TOPIC_PREFIX)) {
             offset = 
this.brokerController.getMessageStore().getMinOffsetInQueue(topic, queueId);
         } else {
-            if 
(this.brokerController.getBrokerConfig().isInitPopOffsetByCheckMsgInMem() &&
-                
this.brokerController.getMessageStore().getMinOffsetInQueue(topic, queueId) <= 
0 &&
-                
this.brokerController.getMessageStore().checkInMemByConsumeOffset(topic, 
queueId, 0, 1)) {
+            if 
(this.brokerController.getBrokerConfig().isInitPopOffsetByCheckMsgInMem()
+                && 
this.brokerController.getMessageStore().shouldInitConsumeOffsetToZero(topic, 
queueId)) {
                 offset = 0;
             } else {
                 // pop last one,then commit offset.
diff --git 
a/broker/src/test/java/org/apache/rocketmq/broker/offset/BroadcastOffsetManagerTest.java
 
b/broker/src/test/java/org/apache/rocketmq/broker/offset/BroadcastOffsetManagerTest.java
index ad5af92646..c5815d61f7 100644
--- 
a/broker/src/test/java/org/apache/rocketmq/broker/offset/BroadcastOffsetManagerTest.java
+++ 
b/broker/src/test/java/org/apache/rocketmq/broker/offset/BroadcastOffsetManagerTest.java
@@ -47,6 +47,7 @@ public class BroadcastOffsetManagerTest {
 
     private final ConsumerOffsetManager consumerOffsetManager = 
mock(ConsumerOffsetManager.class);
     private final ConsumerManager consumerManager = 
mock(ConsumerManager.class);
+    private final MessageStore messageStore = mock(MessageStore.class);
     private final BrokerConfig brokerConfig = new BrokerConfig();
     private final Set<String> onlineClientIdSet = new HashSet<>();
     private BroadcastOffsetManager broadcastOffsetManager;
@@ -76,7 +77,6 @@ public class BroadcastOffsetManagerTest {
         }).when(consumerOffsetManager).commitOffset(anyString(), anyString(), 
anyString(), anyInt(), anyLong());
         
when(brokerController.getConsumerOffsetManager()).thenReturn(consumerOffsetManager);
 
-        MessageStore messageStore = mock(MessageStore.class);
         doAnswer((Answer<Long>) mock -> maxOffset.get())
             .when(messageStore).getMaxOffsetInQueue(anyString(), anyInt(), 
anyBoolean());
         when(brokerController.getMessageStore()).thenReturn(messageStore);
@@ -84,6 +84,16 @@ public class BroadcastOffsetManagerTest {
         broadcastOffsetManager = new BroadcastOffsetManager(brokerController);
     }
 
+    @Test
+    public void testInitOffsetToZeroWhenFirstMsgInMem() throws 
ConsumeQueueException {
+        // No stored/committed offset and the first message (offset 0) is 
still in memory:
+        // init the broadcast offset to 0 rather than the queue tail, so the 
first message is
+        // not skipped by a message arriving during the init race.
+        when(messageStore.shouldInitConsumeOffsetToZero("topic", 
0)).thenReturn(true);
+        long offset = broadcastOffsetManager.queryInitOffset("topic", "group", 
0, "client1", -1, true);
+        Assert.assertEquals(0, offset);
+    }
+
     @Test
     public void testBroadcastOffsetSwitch() throws ConsumeQueueException {
         // client1 connect to broker
diff --git 
a/broker/src/test/java/org/apache/rocketmq/broker/processor/ConsumerManageProcessorTest.java
 
b/broker/src/test/java/org/apache/rocketmq/broker/processor/ConsumerManageProcessorTest.java
index 6b3c2578af..3369530cbd 100644
--- 
a/broker/src/test/java/org/apache/rocketmq/broker/processor/ConsumerManageProcessorTest.java
+++ 
b/broker/src/test/java/org/apache/rocketmq/broker/processor/ConsumerManageProcessorTest.java
@@ -48,6 +48,7 @@ import org.apache.rocketmq.remoting.rpc.RpcException;
 import org.apache.rocketmq.remoting.rpc.RpcResponse;
 import org.apache.rocketmq.store.MessageStore;
 import org.apache.rocketmq.store.config.MessageStoreConfig;
+import org.apache.rocketmq.store.exception.ConsumeQueueException;
 import org.junit.Before;
 import org.junit.Test;
 import org.junit.runner.RunWith;
@@ -167,11 +168,17 @@ public class ConsumerManageProcessorTest {
     }
 
     @Test
-    public void testQueryConsumerOffset() throws RemotingCommandException, 
ExecutionException, InterruptedException {
+    public void testQueryConsumerOffset() throws RemotingCommandException, 
ExecutionException, InterruptedException, ConsumeQueueException {
+        // shouldInitConsumeOffsetToZero is a default method on MessageStore; 
make the mock run its
+        // real body so the getMin/getMax/checkInMem stubs below actually 
drive the decision.
+        when(messageStore.shouldInitConsumeOffsetToZero(anyString(), 
anyInt())).thenCallRealMethod();
         RemotingCommand request = buildQueryConsumerOffsetRequest(group, 
topic, 0, true);
         RemotingCommand response = 
consumerManageProcessor.processRequest(handlerContext, request);
         assertThat(response).isNotNull();
-        assertThat(response.getCode()).isEqualTo(ResponseCode.QUERY_NOT_FOUND);
+        // No stored offset + empty queue (default mock: minOffset=0, 
maxOffset=0): the start
+        // offset is initialized to 0 and SUCCESS is returned (previously 
returning QUERY_NOT_FOUND
+        // triggered the lost-first-message race).
+        assertThat(response.getCode()).isEqualTo(ResponseCode.SUCCESS);
 
         
when(brokerController.getConsumerOffsetManager()).thenReturn(consumerOffsetManager);
         
when(consumerOffsetManager.queryOffset(anyString(),anyString(),anyInt())).thenReturn(0L);
@@ -180,7 +187,10 @@ public class ConsumerManageProcessorTest {
         assertThat(response.getCode()).isEqualTo(ResponseCode.SUCCESS);
 
         
when(consumerOffsetManager.queryOffset(anyString(),anyString(),anyInt())).thenReturn(-1L);
-        
when(messageStore.getMinOffsetInQueue(anyString(),anyInt())).thenReturn(-1L);
+        
when(messageStore.getMinOffsetInQueue(anyString(),anyInt())).thenReturn(0L);
+        // Non-empty queue (maxOffset>0) with the first message still in 
memory: start offset is
+        // set to 0 and SUCCESS is returned.
+        
when(messageStore.getMaxOffsetInQueue(anyString(),anyInt())).thenReturn(10L);
         
when(messageStore.checkInMemByConsumeOffset(anyString(),anyInt(),anyLong(),anyInt())).thenReturn(true);
         response = consumerManageProcessor.processRequest(handlerContext, 
request);
         assertThat(response).isNotNull();
@@ -222,6 +232,63 @@ public class ConsumerManageProcessorTest {
         assertThat(response.getCode()).isEqualTo(ResponseCode.QUERY_NOT_FOUND);
     }
 
+    @Test
+    public void testQueryConsumerOffsetInitToZeroForEmptyQueue() throws 
Exception {
+        // Regression test: with no stored offset + an empty queue 
(maxOffset==0, checkInMem
+        // returns false), the first query must return SUCCESS offset=0 
instead of QUERY_NOT_FOUND;
+        // otherwise it triggers the client's second GET_MAX_OFFSET step and 
the lost-first-message
+        // race.
+        
when(brokerController.getConsumerOffsetManager()).thenReturn(consumerOffsetManager);
+        when(consumerOffsetManager.queryOffset(anyString(), anyString(), 
anyInt())).thenReturn(-1L);
+        when(messageStore.shouldInitConsumeOffsetToZero(anyString(), 
anyInt())).thenCallRealMethod();
+        when(messageStore.getMinOffsetInQueue(anyString(), 
anyInt())).thenReturn(0L);
+        when(messageStore.getMaxOffsetInQueue(anyString(), 
anyInt())).thenReturn(0L);
+
+        RemotingCommand request = buildQueryConsumerOffsetRequest(group, 
topic, 0, true);
+        RemotingCommand response = 
consumerManageProcessor.processRequest(handlerContext, request);
+        assertThat(response).isNotNull();
+        assertThat(response.getCode()).isEqualTo(ResponseCode.SUCCESS);
+        QueryConsumerOffsetResponseHeader responseHeader =
+            (QueryConsumerOffsetResponseHeader) response.readCustomHeader();
+        assertThat(responseHeader.getOffset()).isEqualTo(0L);
+    }
+
+    @Test
+    public void testQueryConsumerOffsetNotFoundWhenFirstMessageOnDisk() throws 
Exception {
+        // Non-empty queue (maxOffset>0) whose first message has been swapped 
out of memory
+        // (checkInMem returns false): still return QUERY_NOT_FOUND so the 
client starts from the
+        // tail, avoiding re-consumption of already-aged historical messages.
+        
when(brokerController.getConsumerOffsetManager()).thenReturn(consumerOffsetManager);
+        when(consumerOffsetManager.queryOffset(anyString(), anyString(), 
anyInt())).thenReturn(-1L);
+        when(messageStore.shouldInitConsumeOffsetToZero(anyString(), 
anyInt())).thenCallRealMethod();
+        when(messageStore.getMinOffsetInQueue(anyString(), 
anyInt())).thenReturn(0L);
+        when(messageStore.getMaxOffsetInQueue(anyString(), 
anyInt())).thenReturn(100L);
+        when(messageStore.checkInMemByConsumeOffset(anyString(), anyInt(), 
anyLong(), anyInt())).thenReturn(false);
+
+        RemotingCommand request = buildQueryConsumerOffsetRequest(group, 
topic, 0, true);
+        RemotingCommand response = 
consumerManageProcessor.processRequest(handlerContext, request);
+        assertThat(response).isNotNull();
+        assertThat(response.getCode()).isEqualTo(ResponseCode.QUERY_NOT_FOUND);
+    }
+
+    @Test
+    public void testQueryConsumerOffsetFallbackWhenMaxOffsetQueryFails() 
throws Exception {
+        // When getMaxOffsetInQueue fails we cannot confirm the queue is 
empty, so the exception is
+        // swallowed and QUERY_NOT_FOUND is returned, letting the client fall 
back to its own
+        // GET_MAX_OFFSET path (same behavior as before this fix).
+        
when(brokerController.getConsumerOffsetManager()).thenReturn(consumerOffsetManager);
+        when(consumerOffsetManager.queryOffset(anyString(), anyString(), 
anyInt())).thenReturn(-1L);
+        when(messageStore.shouldInitConsumeOffsetToZero(anyString(), 
anyInt())).thenCallRealMethod();
+        when(messageStore.getMinOffsetInQueue(anyString(), 
anyInt())).thenReturn(0L);
+        when(messageStore.getMaxOffsetInQueue(anyString(), anyInt()))
+            .thenThrow(new ConsumeQueueException("mock failure"));
+
+        RemotingCommand request = buildQueryConsumerOffsetRequest(group, 
topic, 0, true);
+        RemotingCommand response = 
consumerManageProcessor.processRequest(handlerContext, request);
+        assertThat(response).isNotNull();
+        assertThat(response.getCode()).isEqualTo(ResponseCode.QUERY_NOT_FOUND);
+    }
+
     @Test
     public void testRewriteRequestForStaticTopic() throws RpcException, 
ExecutionException, InterruptedException {
         UpdateConsumerOffsetRequestHeader requestHeader = new 
UpdateConsumerOffsetRequestHeader();
diff --git 
a/broker/src/test/java/org/apache/rocketmq/broker/processor/PopMessageProcessorTest.java
 
b/broker/src/test/java/org/apache/rocketmq/broker/processor/PopMessageProcessorTest.java
index 5d7b97f229..2e32fa32df 100644
--- 
a/broker/src/test/java/org/apache/rocketmq/broker/processor/PopMessageProcessorTest.java
+++ 
b/broker/src/test/java/org/apache/rocketmq/broker/processor/PopMessageProcessorTest.java
@@ -215,6 +215,26 @@ public class PopMessageProcessorTest {
         messageStore.getMaxOffsetInQueue(topic, 0); // prevent 
UnnecessaryStubbingException
     }
 
+    @Test
+    public void testGetInitOffset_normalTopic_initToZeroWhenFirstMsgInMem() 
throws RemotingCommandException, ConsumeQueueException {
+        when(messageStore.getMessageStoreConfig()).thenReturn(new 
MessageStoreConfig());
+        // First message (offset 0) is still in memory: init the consume 
offset to 0 rather than the
+        // queue tail, so a message arriving during the init race is not 
skipped.
+        when(messageStore.shouldInitConsumeOffsetToZero(topic, 
0)).thenReturn(true);
+        String newGroup = group + "-" + System.currentTimeMillis();
+        GetMessageResult getMessageResult = createGetMessageResult(0);
+        when(messageStore.getMessageAsync(eq(newGroup), anyString(), anyInt(), 
anyLong(), anyInt(), any()))
+                
.thenReturn(CompletableFuture.completedFuture(getMessageResult));
+
+        long offset = 
brokerController.getConsumerOffsetManager().queryOffset(newGroup, topic, 0);
+        assertEquals(-1, offset);
+
+        RemotingCommand request = createPopMsgCommand(newGroup, topic, 0, 
ConsumeInitMode.MAX);
+        popMessageProcessor.processRequest(handlerContext, request);
+        offset = 
brokerController.getConsumerOffsetManager().queryOffset(newGroup, topic, 0);
+        assertEquals(0, offset);
+    }
+
     @Test
     public void testBuildCkMsgJsonParsing() {
         PopCheckPoint ck = new PopCheckPoint();
diff --git a/store/src/main/java/org/apache/rocketmq/store/MessageStore.java 
b/store/src/main/java/org/apache/rocketmq/store/MessageStore.java
index 2490bb5b2f..9c6f2c76cd 100644
--- a/store/src/main/java/org/apache/rocketmq/store/MessageStore.java
+++ b/store/src/main/java/org/apache/rocketmq/store/MessageStore.java
@@ -208,6 +208,31 @@ public interface MessageStore {
      */
     long getMinOffsetInQueue(final String topic, final int queueId);
 
+    /**
+     * Decides whether a consumer with no stored offset should start from 0 
for this queue.
+     *
+     * <p>Returns true only when the queue's min offset is 0 (no messages have 
been deleted) and one
+     * of the following holds: the queue is empty (maxOffset == 0, so the 
"last offset" is 0), or the
+     * first message (offset 0) is still in memory.
+     *
+     * <p>Treating an empty queue as "start from 0" avoids a 
lost-first-message race: if the callers
+     * instead jumped to the queue tail when the queue looks empty, a message 
arriving concurrently
+     * would push the tail past offset 0 and that first message would be 
skipped forever.
+     *
+     * @param topic   Topic name.
+     * @param queueId Queue ID.
+     * @return true if the initial consume offset should be 0.
+     */
+    default boolean shouldInitConsumeOffsetToZero(final String topic, final 
int queueId) throws ConsumeQueueException {
+        if (getMinOffsetInQueue(topic, queueId) > 0) {
+            return false;
+        }
+        if (getMaxOffsetInQueue(topic, queueId) <= 0) {
+            return true;
+        }
+        return checkInMemByConsumeOffset(topic, queueId, 0, 1);
+    }
+
     TimerMessageStore getTimerMessageStore();
 
     TimerMessageRocksDBStore getTimerMessageRocksDBStore();

Reply via email to