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 875aeb0c79 [ISSUE #11528] Release the leases of a lost Lite pop 
response on retry (#11529)
875aeb0c79 is described below

commit 875aeb0c79f89e48cb88a2a079c01640e6392c6d
Author: Quan <[email protected]>
AuthorDate: Wed Nov 25 10:31:22 2026 +0800

    [ISSUE #11528] Release the leases of a lost Lite pop response on retry 
(#11529)
    
    - Track the latest pop with an attemptId of each client and the leases it 
takes
    - Release the unacked leases of an attempt on its retry without committing 
offset, and re-dispatch them
    - Stop a pop superseded by a newer request, pass on its events and release 
a lease it takes afterwards
    - Reject renewing or suspending a released lease
    - Add unit tests for lease release and recovery
---
 .../offset/MemoryConsumerOrderInfoManager.java     |  27 +
 .../processor/ChangeInvisibleTimeProcessor.java    |   5 +
 .../broker/processor/PopLiteMessageProcessor.java  | 223 +++++-
 .../processor/PopLiteAttemptRecoveryTest.java      | 571 +++++++++++++++
 .../PopLiteMessageProcessorAttemptReleaseTest.java | 762 +++++++++++++++++++++
 .../PopLiteMessageProcessorEventLossTest.java      |   4 +-
 .../processor/PopLiteMessageProcessorTest.java     |  48 +-
 .../proxy/service/message/LocalMessageService.java |   5 +
 .../service/message/LocalMessageServiceTest.java   |  12 +
 9 files changed, 1618 insertions(+), 39 deletions(-)

diff --git 
a/broker/src/main/java/org/apache/rocketmq/broker/offset/MemoryConsumerOrderInfoManager.java
 
b/broker/src/main/java/org/apache/rocketmq/broker/offset/MemoryConsumerOrderInfoManager.java
index fad3a5b444..fcae3e9328 100644
--- 
a/broker/src/main/java/org/apache/rocketmq/broker/offset/MemoryConsumerOrderInfoManager.java
+++ 
b/broker/src/main/java/org/apache/rocketmq/broker/offset/MemoryConsumerOrderInfoManager.java
@@ -20,7 +20,9 @@ package org.apache.rocketmq.broker.offset;
 import org.apache.rocketmq.broker.BrokerController;
 import org.apache.rocketmq.broker.pop.orderly.QueueLevelConsumerManager;
 
+import java.util.Objects;
 import java.util.concurrent.ConcurrentHashMap;
+import java.util.stream.IntStream;
 
 /**
  * Memory-based Consumer Order Information Manager for Lite Topics
@@ -70,6 +72,31 @@ public class MemoryConsumerOrderInfoManager extends 
QueueLevelConsumerManager {
         updateLockFreeTimestamp(topic, group, queueId, orderInfo);
     }
 
+    public boolean isPopTimeMatched(String topic, String group, int queueId, 
long popTime) {
+        ConcurrentHashMap<Integer, OrderInfo> queues = 
getTable().get(buildKey(topic, group));
+        OrderInfo orderInfo = queues == null ? null : queues.get(queueId);
+        return orderInfo != null && popTime > 0 && popTime == 
orderInfo.getPopTime();
+    }
+
+    /**
+     * Release the unacked lease of an attempt whose response was lost, 
without committing offset. The negative pop
+     * time invalidates its receipt handles: a renewal gets NO_MESSAGE, an ack 
gets success without committing offset.
+     */
+    public boolean releaseQueue(String topic, String group, int queueId, 
String attemptId) {
+        ConcurrentHashMap<Integer, OrderInfo> orderInfoMap = 
this.getTable().get(buildKey(topic, group));
+        OrderInfo orderInfo = orderInfoMap == null ? null : 
orderInfoMap.get(queueId);
+        if (null == orderInfo || null == orderInfo.getOffsetList()
+            || !Objects.equals(attemptId, orderInfo.getAttemptId()) || 
orderInfo.getPopTime() <= 0
+            || IntStream.range(0, 
orderInfo.getOffsetList().size()).noneMatch(orderInfo::isNotAck)) {
+            return false;
+        }
+        orderInfo.setPopTime(-orderInfo.getPopTime());
+        orderInfo.setInvisibleTime(1L);
+        orderInfo.setOffsetNextVisibleTime(null);
+        updateLockFreeTimestamp(topic, group, queueId, orderInfo);
+        return true;
+    }
+
     @Override
     public void persist() {
         // MemoryConsumerOrderInfoManager persist, do nothing.
diff --git 
a/broker/src/main/java/org/apache/rocketmq/broker/processor/ChangeInvisibleTimeProcessor.java
 
b/broker/src/main/java/org/apache/rocketmq/broker/processor/ChangeInvisibleTimeProcessor.java
index fce4a74bb6..bbdbfb16ad 100644
--- 
a/broker/src/main/java/org/apache/rocketmq/broker/processor/ChangeInvisibleTimeProcessor.java
+++ 
b/broker/src/main/java/org/apache/rocketmq/broker/processor/ChangeInvisibleTimeProcessor.java
@@ -394,6 +394,11 @@ public class ChangeInvisibleTimeProcessor implements 
NettyRequestProcessor {
             if (requestHeader.getOffset() < oldOffset) {
                 return CompletableFuture.completedFuture(response);
             }
+            if (!consumerOrderInfoManager.isPopTimeMatched(lmqName, group, 0, 
popTime)) {
+                response.setCode(ResponseCode.NO_MESSAGE);
+                response.setRemark("The lite receipt handle belongs to an 
expired lease");
+                return CompletableFuture.completedFuture(response);
+            }
             long visibilityTimeout = System.currentTimeMillis() + 
requestHeader.getInvisibleTime();
             if (requestHeader.isSuspend()) {
                 consumerOrderInfoManager.suspendQueue(lmqName, group, 0, 
popTime, visibilityTimeout);
diff --git 
a/broker/src/main/java/org/apache/rocketmq/broker/processor/PopLiteMessageProcessor.java
 
b/broker/src/main/java/org/apache/rocketmq/broker/processor/PopLiteMessageProcessor.java
index acf158026b..1c4a6a7a23 100644
--- 
a/broker/src/main/java/org/apache/rocketmq/broker/processor/PopLiteMessageProcessor.java
+++ 
b/broker/src/main/java/org/apache/rocketmq/broker/processor/PopLiteMessageProcessor.java
@@ -20,6 +20,7 @@ import com.google.common.annotations.VisibleForTesting;
 import io.netty.channel.Channel;
 import io.netty.channel.ChannelHandlerContext;
 import io.opentelemetry.api.common.Attributes;
+import org.apache.commons.lang3.StringUtils;
 import org.apache.rocketmq.broker.BrokerController;
 import org.apache.rocketmq.broker.lite.LiteEventDispatcher;
 import org.apache.rocketmq.broker.lite.LiteMetadataUtil;
@@ -43,6 +44,7 @@ import org.apache.rocketmq.common.message.MessageConst;
 import org.apache.rocketmq.common.topic.TopicValidator;
 import org.apache.rocketmq.logging.org.slf4j.Logger;
 import org.apache.rocketmq.logging.org.slf4j.LoggerFactory;
+import org.apache.rocketmq.remoting.common.RemotingHelper;
 import org.apache.rocketmq.remoting.exception.RemotingCommandException;
 import org.apache.rocketmq.remoting.netty.NettyRemotingAbstract;
 import org.apache.rocketmq.remoting.netty.NettyRequestProcessor;
@@ -61,10 +63,13 @@ import java.util.Collections;
 import java.util.HashSet;
 import java.util.Iterator;
 import java.util.List;
+import java.util.Map;
 import java.util.Objects;
 import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.locks.LockSupport;
 
 import static 
org.apache.rocketmq.broker.metrics.BrokerMetricsConstant.LABEL_CONSUMER_GROUP;
 import static 
org.apache.rocketmq.broker.metrics.BrokerMetricsConstant.LABEL_IS_RETRY;
@@ -79,13 +84,21 @@ import static 
org.apache.rocketmq.broker.metrics.BrokerMetricsConstant.LABEL_TOP
 public class PopLiteMessageProcessor implements NettyRequestProcessor {
     private static final Logger LOGGER = 
LoggerFactory.getLogger(LoggerName.ROCKETMQ_POP_LITE_LOGGER_NAME);
     private static final String BORN_TIME = "bornTime";
+    private static final String ARRIVE_TIME = "liteArriveTime";
+    // idle time before the record of a client is cleaned
+    @VisibleForTesting
+    static final long ATTEMPT_TTL = TimeUnit.MINUTES.toNanos(3);
+    // max time a retry waits for queue locks to release its leases
+    private static final long RELEASE_LOCK_TIMEOUT = 
TimeUnit.MILLISECONDS.toNanos(200);
 
     private final BrokerController brokerController;
     private final PopLiteLongPollingService popLiteLongPollingService;
     private final PopConsumerLockService lockService;
     private final LiteEventDispatcher liteEventDispatcher;
-    private final ConsumerOrderInfoManager consumerOrderInfoManager;
+    private final MemoryConsumerOrderInfoManager consumerOrderInfoManager;
     private final PopLiteLockManager popLiteLockManager;
+    // clientId -> the latest request of the client, assuming at most one pop 
with an attemptId in flight per client
+    private final Map<String, Attempt> attempts = new ConcurrentHashMap<>();
 
     public PopLiteMessageProcessor(final BrokerController brokerController, 
LiteEventDispatcher liteEventDispatcher) {
         this.brokerController = brokerController;
@@ -120,12 +133,34 @@ public class PopLiteMessageProcessor implements 
NettyRequestProcessor {
         String clientId = requestHeader.getClientId();
         String group = requestHeader.getConsumerGroup();
         String parentTopic = requestHeader.getTopic();
-        int maxNum = requestHeader.getMaxMsgNum();
-        long popTime = System.currentTimeMillis();
         long invisibleTime = requestHeader.getInvisibleTime();
 
+        String attemptId = requestHeader.getAttemptId();
+        long arriveTime = Long.MAX_VALUE;
+        if (StringUtils.isNotEmpty(attemptId)) {
+            if (request.isSuspended()) {
+                arriveTime = 
Long.parseLong(request.getExtFields().get(ARRIVE_TIME));
+                if (hasNewerRequest(clientId, arriveTime)) {
+                    // the client has given up this request, pass the wake-up 
on to its latest one
+                    popLiteLongPollingService.notifyMessageArriving(clientId, 
true, -1, group);
+                    response.setCode(ResponseCode.POLLING_TIMEOUT);
+                    
response.setRemark(GetMessageStatus.NO_MESSAGE_IN_QUEUE.name());
+                    return response;
+                }
+            } else {
+                // overwrite any value carried in by the request
+                arriveTime = System.nanoTime();
+                request.addExtField(ARRIVE_TIME, String.valueOf(arriveTime));
+                if (!onArrival(group, clientId, attemptId, arriveTime)) {
+                    response.setCode(ResponseCode.SYSTEM_BUSY);
+                    response.setRemark("Lite attempt lease recovery is 
incomplete or superseded");
+                    return response;
+                }
+            }
+        }
+        long popTime = System.currentTimeMillis();
         Pair<StringBuilder, GetMessageResult> rst = 
popByClientId(channel.remoteAddress().toString(), parentTopic,
-            group, clientId, popTime, invisibleTime, maxNum, 
requestHeader.getAttemptId());
+            group, clientId, popTime, invisibleTime, 
requestHeader.getMaxMsgNum(), attemptId, arriveTime);
 
         final GetMessageResult getMessageResult = rst.getObject2();
         if (getMessageResult != null && getMessageResult.getMessageCount() > 
0) {
@@ -187,7 +222,8 @@ public class PopLiteMessageProcessor implements 
NettyRequestProcessor {
 
         TopicConfig topicConfig = 
brokerController.getTopicConfigManager().selectTopicConfig(requestHeader.getTopic());
         if (null == topicConfig) {
-            LOGGER.error("The parentTopic {} not exist, consumer: {} ", 
requestHeader.getTopic());
+            LOGGER.error("The parentTopic {} not exist, consumer: {} ", 
requestHeader.getTopic(),
+                RemotingHelper.parseChannelRemoteAddr(ctx.channel()));
             response.setCode(ResponseCode.TOPIC_NOT_EXIST);
             response.setRemark(String.format("topic [%s] not exist, apply 
first please! %s", requestHeader.getTopic(),
                 FAQUrl.suggestTodo(FAQUrl.APPLY_TOPIC_URL)));
@@ -196,7 +232,7 @@ public class PopLiteMessageProcessor implements 
NettyRequestProcessor {
 
         if (!PermName.isReadable(topicConfig.getPerm())) {
             response.setCode(ResponseCode.NO_PERMISSION);
-            response.setRemark(String.format("the topic [%s] peeking message 
is forbidden", requestHeader.getTopic()));
+            response.setRemark(String.format("the topic [%s] pop message is 
forbidden", requestHeader.getTopic()));
             return response;
         }
 
@@ -243,8 +279,9 @@ public class PopLiteMessageProcessor implements 
NettyRequestProcessor {
         return byteBuffer.array();
     }
 
-    public Pair<StringBuilder, GetMessageResult> popByClientId(String 
clientHost, String parentTopic, String group,
-        String clientId, long popTime, long invisibleTime, int maxNum, String 
attemptId) {
+    @VisibleForTesting
+    Pair<StringBuilder, GetMessageResult> popByClientId(String clientHost, 
String parentTopic, String group,
+        String clientId, long popTime, long invisibleTime, int maxNum, String 
attemptId, long arriveTime) {
         GetMessageResult getMessageResult = new GetMessageResult();
         StringBuilder orderCountInfoAll = new StringBuilder();
         AtomicLong total = new AtomicLong(0);
@@ -257,6 +294,11 @@ public class PopLiteMessageProcessor implements 
NettyRequestProcessor {
             if (null == lmqName) {
                 break;
             }
+            if (hasNewerRequest(clientId, arriveTime)) {
+                // may be an event re-dispatched by the newer request, so it 
is passed on rather than dropped
+                redispatch(group, lmqName);
+                break;
+            }
             if (processed.contains(lmqName)) {
                 // Already read in this pop; skip the duplicate. A 
FIFO-blocked or empty-read lmq is never marked
                 // by popLiteTopic, so its later re-dispatch (ack-unblock or 
CQ commit) is retried, not deduped away.
@@ -268,7 +310,7 @@ public class PopLiteMessageProcessor implements 
NettyRequestProcessor {
                 continue;
             }
             Pair<StringBuilder, GetMessageResult> pair = 
popLiteTopic(parentTopic, clientHost, group, lmqName,
-                maxNum - total.get(), popTime, invisibleTime, attemptId, 
processed);
+                maxNum - total.get(), popTime, invisibleTime, attemptId, 
processed, clientId, arriveTime);
             if (null == pair || pair.getObject2().getMessageCount() <= 0) {
                 continue;
             }
@@ -283,33 +325,187 @@ public class PopLiteMessageProcessor implements 
NettyRequestProcessor {
             orderCountInfoAll.append(pair.getObject1());
             collectLiteConsumerLagMetrics(group, parentTopic, lmqName, 
singleResult, maxNum, total);
         }
+
         return new Pair<>(orderCountInfoAll, getMessageResult);
     }
 
+    /**
+     * Record a request as the latest of its client. A retry of the recorded 
attempt proves its response was lost, so
+     * the leases it took are released first.
+     */
+    @VisibleForTesting
+    boolean onArrival(String group, String clientId, String attemptId, long 
arriveTime) {
+        Attempt[] retried = new Attempt[1];
+        attempts.compute(clientId, (key, old) -> {
+            if (old != null && old.arriveTime > arriveTime) {
+                return old;
+            }
+            Attempt latest = new Attempt(group, attemptId, arriveTime);
+            if (old != null && attemptId.equals(old.attemptId) && 
group.equals(old.group)) {
+                // take over the leases left by an unfinished release
+                latest.lmqNames.addAll(old.lmqNames);
+                old.takenOver = true;
+                retried[0] = latest;
+            }
+            return latest;
+        });
+        if (retried[0] != null && !releaseAttempt(retried[0], clientId)) {
+            return false;
+        }
+        return !hasNewerRequest(clientId, arriveTime);
+    }
+
+    @VisibleForTesting
+    boolean hasNewerRequest(String clientId, long arriveTime) {
+        Attempt latest = attempts.get(clientId);
+        return latest != null && latest.arriveTime > arriveTime;
+    }
+
+    /**
+     * Called under the queue lock of the lease just taken.
+     *
+     * @return true if a newer request of the client has arrived, so the 
caller releases the lease itself
+     */
+    private boolean registerAttempt(String clientId, String group, String 
attemptId, String lmqName,
+        long arriveTime) {
+        Attempt latest = attempts.computeIfPresent(clientId, (key, attempt) -> 
{
+            if (attemptId.equals(attempt.attemptId) && 
group.equals(attempt.group)
+                && attempt.arriveTime <= arriveTime) {
+                attempt.lmqNames.add(lmqName);
+            }
+            return attempt;
+        });
+        return latest != null && latest.arriveTime > arriveTime;
+    }
+
+    /**
+     * Release the leases of an attempt and re-dispatch them. It stops once a 
newer retry of the same attempt takes
+     * over, or a queue lock is not taken in time, leaving the rest recorded.
+     */
+    private boolean releaseAttempt(Attempt attempt, String clientId) {
+        long deadline = System.nanoTime() + RELEASE_LOCK_TIMEOUT;
+        for (String lmqName : attempt.lmqNames) {
+            String lockKey = KeyBuilder.buildPopLiteLockKey(attempt.group, 
lmqName);
+            if (!lockUntil(lockKey, deadline)) {
+                break;
+            }
+            boolean released;
+            try {
+                // the newer retry may already have re-taken this lease
+                if (attempt.takenOver) {
+                    break;
+                }
+                released = consumerOrderInfoManager.releaseQueue(lmqName, 
attempt.group, 0, attempt.attemptId);
+                attempt.lmqNames.remove(lmqName);
+            } finally {
+                lockService.unlock(lockKey);
+            }
+            LOGGER.info("lite attempt release lease. clientId={}, group={}, 
attemptId={}, lmqName={}, released={}",
+                clientId, attempt.group, attempt.attemptId, lmqName, released);
+            if (released) {
+                redispatch(attempt.group, lmqName);
+            }
+        }
+        if (!attempt.lmqNames.isEmpty()) {
+            LOGGER.info("lite attempt release stopped. clientId={}, group={}, 
attemptId={}, takenOver={}, remaining={}",
+                clientId, attempt.group, attempt.attemptId, attempt.takenOver, 
attempt.lmqNames);
+        }
+        return !attempt.takenOver && attempt.lmqNames.isEmpty();
+    }
+
+    private boolean lockUntil(String lockKey, long deadline) {
+        while (!lockService.tryLock(lockKey)) {
+            if (System.nanoTime() - deadline > 0) {
+                return false;
+            }
+            LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(1));
+        }
+        return true;
+    }
+
+    // a failed notification must not fail the pop that has read messages
+    private void redispatch(String group, String lmqName) {
+        try {
+            liteEventDispatcher.dispatch(group, lmqName, 0, -1, -1);
+        } catch (Exception e) {
+            LOGGER.error("lite redispatch error. group={}, lmqName={}", group, 
lmqName, e);
+        }
+    }
+
+    /**
+     * Only the records are cleaned, the leases are left to ack or expiry as 
the batch may still be consumed.
+     */
+    @VisibleForTesting
+    void cleanAttempts(long now) {
+        attempts.forEach((clientId, attempt) -> {
+            if (now - attempt.arriveTime > ATTEMPT_TTL) {
+                attempts.remove(clientId, attempt);
+            }
+        });
+    }
+
+    private static final class Attempt {
+        private final String group;
+        private final String attemptId;
+        private final long arriveTime;
+        // leases taken and not released yet
+        private final Set<String> lmqNames = ConcurrentHashMap.newKeySet();
+        // set once a newer retry of the same attempt inherits the leases
+        private volatile boolean takenOver;
+
+        private Attempt(String group, String attemptId, long arriveTime) {
+            this.group = group;
+            this.attemptId = attemptId;
+            this.arriveTime = arriveTime;
+        }
+    }
+
     @VisibleForTesting
     Pair<StringBuilder, GetMessageResult> popLiteTopic(String parentTopic, 
String clientHost, String group,
-        String lmqName, long maxNum, long popTime, long invisibleTime, String 
attemptId, Set<String> processed) {
+        String lmqName, long maxNum, long popTime, long invisibleTime, String 
attemptId, Set<String> processed,
+        String clientId, long arriveTime) {
         String lockKey = KeyBuilder.buildPopLiteLockKey(group, lmqName);
         if (!lockService.tryLock(lockKey)) {
             return null;
         }
+        boolean redispatch = false;
+        GetMessageResult result = null;
         try {
+            if (hasNewerRequest(clientId, arriveTime)) {
+                // the newer request may already hold this lease
+                redispatch = true;
+                return null;
+            }
             if (isFifoBlocked(attemptId, group, lmqName, invisibleTime)) {
                 // Leave this lmq unmarked so a later ack-unblock re-dispatch 
is retried, not deduped away.
                 return null;
             }
             final long consumeOffset = getPopOffset(group, lmqName);
-            GetMessageResult result = getMessage(clientHost, group, lmqName, 
consumeOffset, (int) maxNum);
+            result = getMessage(clientHost, group, lmqName, consumeOffset, 
(int) maxNum);
             if (result != null && result.getMessageCount() > 0) {
                 // Mark only after messages are read: an empty read (e.g. CQ 
entry not yet committed) must not
                 // dedup away a later re-dispatch of this lmq within the same 
pop.
                 processed.add(lmqName);
             }
-            return handleGetMessageResult(result, parentTopic, group, lmqName, 
popTime, invisibleTime, attemptId);
+            Pair<StringBuilder, GetMessageResult> pair =
+                handleGetMessageResult(result, parentTopic, group, lmqName, 
popTime, invisibleTime, attemptId);
+            if (null != pair && pair.getObject2().getMessageCount() > 0 && 
StringUtils.isNotEmpty(attemptId)
+                && registerAttempt(clientId, group, attemptId, lmqName, 
arriveTime)) {
+                // the queue lock proves the lease is still the one just taken
+                redispatch = true;
+                consumerOrderInfoManager.releaseQueue(lmqName, group, 0, 
attemptId);
+            }
+            return pair;
         } catch (Throwable e) {
             LOGGER.error("popLiteTopic error. {}, {}", group, lmqName, e);
+            if (result != null) {
+                result.release();
+            }
         } finally {
             lockService.unlock(lockKey);
+            if (redispatch) {
+                redispatch(group, lmqName);
+            }
         }
         return null;
     }
@@ -465,8 +661,9 @@ public class PopLiteMessageProcessor implements 
NettyRequestProcessor {
                 try {
                     waitForRunning(60000);
                     lockService.removeTimeout();
+                    cleanAttempts(System.nanoTime());
                     if (System.currentTimeMillis() - lastCleanTime >= 
AUTO_CLEAN_INTERVAL) {
-                        ((MemoryConsumerOrderInfoManager) 
consumerOrderInfoManager).autoClean();
+                        consumerOrderInfoManager.autoClean();
                         lastCleanTime = System.currentTimeMillis();
                     }
                 } catch (Exception ignored) {
diff --git 
a/broker/src/test/java/org/apache/rocketmq/broker/processor/PopLiteAttemptRecoveryTest.java
 
b/broker/src/test/java/org/apache/rocketmq/broker/processor/PopLiteAttemptRecoveryTest.java
new file mode 100644
index 0000000000..9b5af871fe
--- /dev/null
+++ 
b/broker/src/test/java/org/apache/rocketmq/broker/processor/PopLiteAttemptRecoveryTest.java
@@ -0,0 +1,571 @@
+/*
+ * 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.broker.processor;
+
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelHandlerContext;
+import java.io.File;
+import java.net.InetSocketAddress;
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.function.BooleanSupplier;
+import org.apache.rocketmq.broker.BrokerController;
+import org.apache.rocketmq.broker.lite.AbstractLiteLifecycleManager;
+import org.apache.rocketmq.broker.lite.LiteEventDispatcher;
+import org.apache.rocketmq.broker.lite.LiteSubscriptionRegistry;
+import org.apache.rocketmq.broker.lite.LiteTestUtil;
+import org.apache.rocketmq.broker.longpolling.NotifyMessageArrivingListener;
+import org.apache.rocketmq.broker.longpolling.PullRequestHoldService;
+import org.apache.rocketmq.broker.metrics.BrokerMetricsManager;
+import org.apache.rocketmq.broker.offset.ConsumerOffsetManager;
+import org.apache.rocketmq.broker.subscription.SubscriptionGroupManager;
+import org.apache.rocketmq.broker.topic.TopicConfigManager;
+import org.apache.rocketmq.common.BrokerConfig;
+import org.apache.rocketmq.common.KeyBuilder;
+import org.apache.rocketmq.common.TopicConfig;
+import org.apache.rocketmq.common.UtilAll;
+import org.apache.rocketmq.common.attribute.TopicMessageType;
+import org.apache.rocketmq.common.entity.ClientGroup;
+import org.apache.rocketmq.common.lite.LiteUtil;
+import org.apache.rocketmq.common.message.MessageConst;
+import org.apache.rocketmq.common.message.MessageDecoder;
+import org.apache.rocketmq.common.message.MessageExt;
+import org.apache.rocketmq.remoting.protocol.RemotingCommand;
+import org.apache.rocketmq.remoting.protocol.RequestCode;
+import org.apache.rocketmq.remoting.protocol.ResponseCode;
+import org.apache.rocketmq.remoting.protocol.header.AckMessageRequestHeader;
+import 
org.apache.rocketmq.remoting.protocol.header.ChangeInvisibleTimeRequestHeader;
+import org.apache.rocketmq.remoting.protocol.header.ExtraInfoUtil;
+import 
org.apache.rocketmq.remoting.protocol.header.PopLiteMessageRequestHeader;
+import 
org.apache.rocketmq.remoting.protocol.header.PopLiteMessageResponseHeader;
+import 
org.apache.rocketmq.remoting.protocol.subscription.SubscriptionGroupConfig;
+import org.apache.rocketmq.store.MessageArrivingListener;
+import org.apache.rocketmq.store.MessageStore;
+import org.apache.rocketmq.store.stats.BrokerStatsManager;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+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.junit.Assert.fail;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * Recovery of a lost lite pop by its attemptId, driven through the request 
path a proxy uses.
+ *
+ * <p>The broker side is real: message store with lmq dispatch, consumer 
offsets, lite event dispatcher,
+ * {@link PopLiteMessageProcessor} with its long polling, order info and lock 
service, and the ack and renewal
+ * processors. A response is lost by simply not reading it. Only metadata 
lookups (topic, group, subscribers)
+ * and stats are mocked, and the channel just records the written responses. 
The store is shared by the tests,
+ * each of them using its own lite topics.
+ */
+public class PopLiteAttemptRecoveryTest {
+    private static final String PARENT = "LiteAttemptParent";
+    private static final String GROUP = "LiteAttemptGroup";
+    private static final String C1 = "client-1";
+    private static final String C2 = "client-2";
+    private static final long INVISIBLE = 60_000L;
+    private static final long WAIT = 5_000L;
+
+    private static final Map<String, Long> ARRIVED = new 
ConcurrentHashMap<>(); // lmq -> logic offset notified
+    private static volatile MessageArrivingListener notifier; // of the 
running test
+    private static String storePath;
+    private static MessageStore store;
+
+    private final BrokerConfig brokerConfig = new BrokerConfig();
+    private final BrokerController broker = mock(BrokerController.class);
+    private final Map<String, List<String>> subscribers = new 
ConcurrentHashMap<>(); // lmq -> client ids
+    private final Set<String> tombstones = ConcurrentHashMap.newKeySet(); // 
clientId@lmq evicted in exclusive mode
+    private final Map<Integer, RemotingCommand> responses = new 
ConcurrentHashMap<>(); // opaque -> response
+    private String lt1;
+    private String lt2;
+    private String lmq1;
+    private String lmq2;
+    private SubscriptionGroupConfig groupConfig;
+    private ConsumerOffsetManager offsets;
+    private PopLiteMessageProcessor processor;
+    private AckMessageProcessor ackProcessor;
+    private ChangeInvisibleTimeProcessor renewProcessor;
+    private ExecutorService pullExecutor;
+    private Channel channel;
+    private ChannelHandlerContext ctx;
+
+    @BeforeClass
+    public static void startStore() throws Exception {
+        storePath = System.getProperty("java.io.tmpdir") + File.separator + 
"store-liteAttempt-" + UUID.randomUUID();
+        MessageArrivingListener listener = (topic, queueId, logicOffset, 
tagsCode, storeTime, bitMap, properties) -> {
+            MessageArrivingListener current = notifier;
+            if (current != null) {
+                current.arriving(topic, queueId, logicOffset, tagsCode, 
storeTime, bitMap, properties);
+            }
+            ARRIVED.put(topic, logicOffset);
+        };
+        store = LiteTestUtil.buildMessageStore(storePath, new BrokerConfig(), 
new ConcurrentHashMap<>(), false, listener);
+        assertTrue(store.load());
+        store.start();
+    }
+
+    @AfterClass
+    public static void stopStore() {
+        store.shutdown();
+        store.destroy();
+        UtilAll.deleteFile(new File(storePath));
+    }
+
+    @Before
+    public void setUp() throws Exception {
+        String suffix = UUID.randomUUID().toString().substring(0, 8);
+        lt1 = "lt1-" + suffix;
+        lt2 = "lt2-" + suffix;
+        lmq1 = LiteUtil.toLmqName(PARENT, lt1);
+        lmq2 = LiteUtil.toLmqName(PARENT, lt2);
+        when(broker.getBrokerConfig()).thenReturn(brokerConfig);
+
+        groupConfig = new SubscriptionGroupConfig();
+        groupConfig.setGroupName(GROUP);
+        groupConfig.setLiteBindTopic(PARENT);
+        SubscriptionGroupManager groupManager = 
mock(SubscriptionGroupManager.class);
+        
when(groupManager.findSubscriptionGroupConfig(GROUP)).thenReturn(groupConfig);
+        when(broker.getSubscriptionGroupManager()).thenReturn(groupManager);
+
+        TopicConfig topicConfig = new TopicConfig(PARENT, 1, 1);
+        topicConfig.setTopicMessageType(TopicMessageType.LITE);
+        TopicConfigManager topicManager = mock(TopicConfigManager.class);
+        when(topicManager.selectTopicConfig(PARENT)).thenReturn(topicConfig);
+        when(broker.getTopicConfigManager()).thenReturn(topicManager);
+
+        LiteSubscriptionRegistry registry = 
mock(LiteSubscriptionRegistry.class);
+        when(registry.getAllSubscribers(any(), 
anyString())).thenAnswer(invocation -> {
+            List<ClientGroup> clients = new ArrayList<>();
+            for (String clientId : 
subscribers.getOrDefault(invocation.<String>getArgument(1), 
Collections.emptyList())) {
+                clients.add(new ClientGroup(clientId, GROUP));
+            }
+            return clients.isEmpty() ? Collections.emptyMap() : 
Collections.singletonMap(GROUP, clients);
+        });
+        when(registry.hasExclusiveEvictionTombstone(anyString(), 
anyString())).thenAnswer(invocation ->
+            tombstones.contains(invocation.getArgument(0) + "@" + 
invocation.getArgument(1)));
+        when(broker.getLiteSubscriptionRegistry()).thenReturn(registry);
+
+        AbstractLiteLifecycleManager lifecycle = 
mock(AbstractLiteLifecycleManager.class);
+        when(lifecycle.getMaxOffsetInQueue(anyString()))
+            .thenAnswer(invocation -> 
store.getMaxOffsetInQueue(invocation.getArgument(0), 0));
+        when(broker.getLiteLifecycleManager()).thenReturn(lifecycle);
+
+        offsets = new ConsumerOffsetManager(broker);
+        when(broker.getConsumerOffsetManager()).thenReturn(offsets);
+        
when(broker.getPopMessageProcessor()).thenReturn(mock(PopMessageProcessor.class));
+        
when(broker.getBrokerStatsManager()).thenReturn(mock(BrokerStatsManager.class));
+        pullExecutor = Executors.newFixedThreadPool(4);
+        when(broker.getPullMessageExecutor()).thenReturn(pullExecutor);
+
+        LiteEventDispatcher dispatcher = new LiteEventDispatcher(broker, 
registry, lifecycle);
+        when(broker.getLiteEventDispatcher()).thenReturn(dispatcher);
+        notifier = new 
NotifyMessageArrivingListener(mock(PullRequestHoldService.class),
+            mock(PopMessageProcessor.class), 
mock(NotificationProcessor.class), dispatcher);
+        when(broker.getMessageStore()).thenReturn(store);
+        BrokerMetricsManager metricsManager = new BrokerMetricsManager(broker);
+        when(broker.getBrokerMetricsManager()).thenReturn(metricsManager);
+
+        processor = new PopLiteMessageProcessor(broker, dispatcher);
+        when(broker.getPopLiteMessageProcessor()).thenReturn(processor);
+        NotificationProcessor notificationProcessor = new 
NotificationProcessor(broker);
+        
when(broker.getNotificationProcessor()).thenReturn(notificationProcessor);
+        processor.getPopLiteLongPollingService().start();
+        ackProcessor = new AckMessageProcessor(broker);
+        renewProcessor = new ChangeInvisibleTimeProcessor(broker);
+
+        channel = mock(Channel.class);
+        when(channel.isActive()).thenReturn(true);
+        when(channel.remoteAddress()).thenReturn(new 
InetSocketAddress("127.0.0.1", 10911));
+        ChannelFuture writeFuture = mock(ChannelFuture.class);
+        when(writeFuture.addListener(any())).thenReturn(writeFuture);
+        when(channel.writeAndFlush(any())).thenAnswer(invocation -> {
+            RemotingCommand response = invocation.getArgument(0);
+            responses.put(response.getOpaque(), response);
+            return writeFuture;
+        });
+        ctx = mock(ChannelHandlerContext.class);
+        when(ctx.channel()).thenReturn(channel);
+    }
+
+    @After
+    public void tearDown() {
+        notifier = null;
+        processor.getPopLiteLongPollingService().shutdown();
+        processor.getConsumerOrderInfoManager().shutdown();
+        pullExecutor.shutdownNow();
+    }
+
+    @Test
+    public void 
testRetryAfterLostResponseRedeliversTheBatchWithoutMovingOffsets() throws 
Exception {
+        subscribe(C1, lmq1, lmq2);
+        send(lt1, 2);
+        send(lt2, 1);
+        Batch lost = await(pop(C1, "A", 3, 0));
+        assertEquals(Arrays.asList(lt1 + "@0", lt1 + "@1", lt2 + "@0"), 
lost.messages);
+
+        // while the response is lost, a new message arrives on lt1
+        send(lt1, 1);
+        nextMillis();
+        Batch retry = await(pop(C1, "A", 3, 0));
+
+        // a normal pop composes the batch: lt1 fills the budget, the same 
attempt does not count a reconsume
+        assertEquals(Arrays.asList(lt1 + "@0", lt1 + "@1", lt1 + "@2"), 
retry.messages);
+        assertEquals(Arrays.asList(0, 0, 0), retry.reconsumeTimes);
+        assertEquals(0, offsets.queryOffset(GROUP, lmq1, 0));
+        assertEquals(0, offsets.queryOffset(GROUP, lmq2, 0));
+
+        // lt2 is released as well, so the next request reads it although no 
new message arrived
+        assertEquals(Collections.singletonList(lt2 + "@0"), await(pop(C1, "B", 
3, 0)).messages);
+    }
+
+    @Test
+    public void testReceiptOfReleasedLeaseCannotAckOrRenew() throws Exception {
+        subscribe(C1, lmq1);
+        send(lt1, 1);
+        Batch lost = await(pop(C1, "A", 32, 0));
+        nextMillis();
+        Batch retry = await(pop(C1, "A", 32, 0));
+        assertEquals(lost.messages, retry.messages);
+
+        assertEquals(ResponseCode.NO_MESSAGE, renew(lost.popTime, lt1, 0));
+        assertEquals(ResponseCode.NO_MESSAGE, renew(lost.popTime, lt1, 0, 
true));
+        ack(lost.popTime, lt1, 0);
+        assertEquals(0, offsets.queryOffset(GROUP, lmq1, 0));
+
+        assertEquals(ResponseCode.SUCCESS, renew(retry.popTime, lt1, 0));
+        ack(retry.popTime, lt1, 0);
+        assertEquals(1, offsets.queryOffset(GROUP, lmq1, 0));
+    }
+
+    @Test
+    public void testRetryReleasesLeaseForTakeoverByAnotherClient() throws 
Exception {
+        subscribe(C1, lmq1);
+        send(lt1, 2);
+        Batch lost = await(pop(C1, "A", 32, 0));
+        assertEquals(Arrays.asList(lt1 + "@0", lt1 + "@1"), lost.messages);
+
+        // lt1 moves to C2 while C1 still holds the lease, C2 waits in long 
polling
+        subscribers.put(lmq1, Collections.singletonList(C2));
+        int takeover = pop(C2, "X", 32, WAIT);
+        assertPending(takeover);
+
+        // the retry of C1 releases the lease, and the re-dispatched event 
wakes C2
+        assertTrue(await(pop(C1, "A", 32, 0)).messages.isEmpty());
+        Batch taken = await(takeover);
+        assertEquals(Arrays.asList(lt1 + "@0", lt1 + "@1"), taken.messages);
+        assertEquals(Arrays.asList(1, 1), taken.reconsumeTimes);
+        assertEquals(0, offsets.queryOffset(GROUP, lmq1, 0));
+    }
+
+    @Test
+    public void testTimeoutOfAbandonedRequestKeepsTheBatchOfItsRetry() throws 
Exception {
+        subscribe(C1, lmq1);
+        // R1 waits in long polling, the client gives up and retries A with a 
shorter poll, so R2 is woken first
+        int r1 = pop(C1, "A", 32, 1_500);
+        assertPending(r1);
+        int r2 = pop(C1, "A", 32, 500);
+        assertPending(r2);
+
+        send(lt1, 1);
+        Batch delivered = await(r2);
+        assertEquals(Collections.singletonList(lt1 + "@0"), 
delivered.messages);
+
+        // R1 times out while the batch of R2 is being consumed
+        Batch stale = await(r1);
+        assertEquals(ResponseCode.POLLING_TIMEOUT, stale.code);
+        assertEquals(ResponseCode.SUCCESS, renew(delivered.popTime, lt1, 0));
+        ack(delivered.popTime, lt1, 0);
+        assertEquals(1, offsets.queryOffset(GROUP, lmq1, 0));
+    }
+
+    @Test
+    public void testConsecutiveLostResponsesOfOneAttemptStillRecover() throws 
Exception {
+        subscribe(C1, lmq1);
+        send(lt1, 2);
+        Batch lost1 = await(pop(C1, "A", 32, 0));
+        nextMillis();
+        Batch lost2 = await(pop(C1, "A", 32, 0));
+        nextMillis();
+        Batch retry = await(pop(C1, "A", 32, 0));
+
+        assertEquals(Arrays.asList(lt1 + "@0", lt1 + "@1"), lost2.messages);
+        assertEquals(lost2.messages, retry.messages);
+        assertEquals(Arrays.asList(0, 0), retry.reconsumeTimes);
+        assertEquals(ResponseCode.NO_MESSAGE, renew(lost1.popTime, lt1, 0));
+        assertEquals(ResponseCode.NO_MESSAGE, renew(lost2.popTime, lt1, 0));
+        ack(retry.popTime, lt1, 0);
+        ack(retry.popTime, lt1, 1);
+        assertEquals(2, offsets.queryOffset(GROUP, lmq1, 0));
+    }
+
+    @Test
+    public void testClientWithoutAttemptIdKeepsTheLeaseUntilAck() throws 
Exception {
+        subscribe(C1, lmq1);
+        send(lt1, 1);
+        Batch first = await(pop(C1, null, 32, 0));
+        assertEquals(Collections.singletonList(lt1 + "@0"), first.messages);
+
+        // without an attemptId a pop cannot prove the loss, so the lease is 
not released
+        send(lt1, 1);
+        nextMillis();
+        assertTrue(await(pop(C1, null, 32, 0)).messages.isEmpty());
+        assertEquals(ResponseCode.SUCCESS, renew(first.popTime, lt1, 0));
+
+        // the ack unblocks lt1 and the next message is delivered as before
+        ack(first.popTime, lt1, 0);
+        assertEquals(1, offsets.queryOffset(GROUP, lmq1, 0));
+        assertEquals(Collections.singletonList(lt1 + "@1"), await(pop(C1, 
null, 32, 0)).messages);
+    }
+
+    @Test
+    public void testConcurrentRequestsWithoutAttemptIdEachPop() throws 
Exception {
+        subscribe(C1, lmq1, lmq2);
+        int r1 = pop(C1, null, 32, WAIT);
+        assertPending(r1);
+        nextMillis();
+        int r2 = pop(C1, null, 32, WAIT);
+        assertPending(r2);
+
+        // without an attemptId neither request is taken as abandoned, so the 
older one pops as well
+        send(lt1, 1);
+        assertEquals(Collections.singletonList(lt1 + "@0"), await(r1, WAIT / 
2).messages);
+        send(lt2, 1);
+        assertEquals(Collections.singletonList(lt2 + "@0"), await(r2, WAIT / 
2).messages);
+    }
+
+    @Test
+    public void testNotificationPassesThroughAChainOfAbandonedRequests() 
throws Exception {
+        subscribe(C1, lmq1);
+        int r1 = pop(C1, "A", 32, WAIT);
+        assertPending(r1);
+        nextMillis();
+        int r2 = pop(C1, "A", 32, WAIT);
+        assertPending(r2);
+        nextMillis();
+        int r3 = pop(C1, "A", 32, WAIT);
+        assertPending(r3);
+
+        send(lt1, 1);
+        // R3 gets the message long before any poll ends, so R1 and R2 must 
have passed the notification on
+        assertEquals(Collections.singletonList(lt1 + "@0"), await(r3, WAIT / 
2).messages);
+        assertEquals(ResponseCode.POLLING_TIMEOUT, await(r1, 500).code);
+        assertEquals(ResponseCode.POLLING_TIMEOUT, await(r2, 500).code);
+    }
+
+    @Test
+    public void testClientEvictedInExclusiveModeReleasesToTheNewOwner() throws 
Exception {
+        groupConfig.setLiteSubExclusive(true);
+        subscribe(C1, lmq1);
+        send(lt1, 1);
+        assertEquals(Collections.singletonList(lt1 + "@0"), await(pop(C1, "A", 
32, 0)).messages);
+        // a new message queues an lt1 event for C1 right before C2 takes lt1 
over
+        send(lt1, 1);
+        subscribers.put(lmq1, Collections.singletonList(C2));
+        tombstones.add(C1 + "@" + lmq1);
+        int owner = pop(C2, "X", 32, WAIT);
+        assertPending(owner);
+
+        // the retry of C1 still releases its lease, while its own lt1 event 
is rejected by the tombstone
+        assertTrue(await(pop(C1, "A", 32, 0)).messages.isEmpty());
+        assertEquals(Arrays.asList(lt1 + "@0", lt1 + "@1"), 
await(owner).messages);
+        assertEquals(0, offsets.queryOffset(GROUP, lmq1, 0));
+    }
+
+    @Test
+    public void testRequestWaitingWhileItsRecordIsCleanedStillPops() throws 
Exception {
+        subscribe(C1, lmq1);
+        int waiting = pop(C1, "A", 32, WAIT);
+        assertPending(waiting);
+        processor.cleanAttempts(System.nanoTime() + 
PopLiteMessageProcessor.ATTEMPT_TTL + TimeUnit.SECONDS.toNanos(1));
+
+        send(lt1, 1);
+        assertEquals(Collections.singletonList(lt1 + "@0"), await(waiting, 
WAIT / 2).messages);
+    }
+
+    @Test
+    public void testRetryAfterLeaseExpiredStillRedeliversWithoutMovingOffset() 
throws Exception {
+        // the expired lease no longer blocks its own attempt, so this guards 
releasing an expired lease rather than
+        // the release itself: the retry still gets the batch once and the 
offset stays
+        subscribe(C1, lmq1);
+        send(lt1, 1);
+        Batch lost = await(pop(C1, "A", 32, 0, 500));
+        Thread.sleep(800);
+
+        Batch retry = await(pop(C1, "A", 32, 0));
+        assertEquals(lost.messages, retry.messages);
+        assertEquals(0, offsets.queryOffset(GROUP, lmq1, 0));
+        ack(retry.popTime, lt1, 0);
+        assertEquals(1, offsets.queryOffset(GROUP, lmq1, 0));
+    }
+
+    private void subscribe(String clientId, String... lmqNames) {
+        for (String lmqName : lmqNames) {
+            subscribers.put(lmqName, Collections.singletonList(clientId));
+            offsets.commitOffset("init", GROUP, lmqName, 0, 0L);
+        }
+    }
+
+    private void send(String liteTopic, int count) throws Exception {
+        String lmqName = LiteUtil.toLmqName(PARENT, liteTopic);
+        long expected = store.getMaxOffsetInQueue(lmqName, 0) + count;
+        for (int i = 0; i < count; i++) {
+            store.putMessage(LiteTestUtil.buildMessage(PARENT, liteTopic));
+        }
+        // the lmq is readable and its arriving event is dispatched
+        awaitTrue(() -> ARRIVED.getOrDefault(lmqName, 0L) >= expected, 
"message arriving of " + lmqName);
+    }
+
+    // a pop request as sent by a proxy, returning its opaque to collect the 
response
+    private int pop(String clientId, String attemptId, int maxNum, long 
pollTime) throws Exception {
+        return pop(clientId, attemptId, maxNum, pollTime, INVISIBLE);
+    }
+
+    private int pop(String clientId, String attemptId, int maxNum, long 
pollTime, long invisibleTime)
+        throws Exception {
+        PopLiteMessageRequestHeader header = new PopLiteMessageRequestHeader();
+        header.setClientId(clientId);
+        header.setConsumerGroup(GROUP);
+        header.setTopic(PARENT);
+        header.setMaxMsgNum(maxNum);
+        header.setInvisibleTime(invisibleTime);
+        header.setPollTime(pollTime);
+        header.setBornTime(System.currentTimeMillis());
+        header.setAttemptId(attemptId);
+        RemotingCommand request = 
RemotingCommand.createRequestCommand(RequestCode.POP_LITE_MESSAGE, header);
+        request.makeCustomHeaderToNet();
+        processor.processRequest(ctx, request);
+        return request.getOpaque();
+    }
+
+    private void ack(long popTime, String liteTopic, long offset) throws 
Exception {
+        AckMessageRequestHeader header = new AckMessageRequestHeader();
+        header.setConsumerGroup(GROUP);
+        header.setTopic(PARENT);
+        header.setQueueId(0);
+        header.setOffset(offset);
+        header.setLiteTopic(liteTopic);
+        header.setExtraInfo(extraInfo(popTime, offset));
+        RemotingCommand request = 
RemotingCommand.createRequestCommand(RequestCode.ACK_MESSAGE, header);
+        request.makeCustomHeaderToNet();
+        assertEquals(ResponseCode.SUCCESS, ackProcessor.processRequest(ctx, 
request).getCode());
+    }
+
+    private int renew(long popTime, String liteTopic, long offset) throws 
Exception {
+        return renew(popTime, liteTopic, offset, false);
+    }
+
+    private int renew(long popTime, String liteTopic, long offset, boolean 
suspend) throws Exception {
+        ChangeInvisibleTimeRequestHeader header = new 
ChangeInvisibleTimeRequestHeader();
+        header.setConsumerGroup(GROUP);
+        header.setTopic(PARENT);
+        header.setQueueId(0);
+        header.setOffset(offset);
+        header.setLiteTopic(liteTopic);
+        header.setInvisibleTime(INVISIBLE);
+        header.setSuspend(suspend);
+        header.setExtraInfo(extraInfo(popTime, offset));
+        RemotingCommand request = 
RemotingCommand.createRequestCommand(RequestCode.CHANGE_MESSAGE_INVISIBLETIME, 
header);
+        request.makeCustomHeaderToNet();
+        return renewProcessor.processRequestAsync(channel, request, 
true).join().getCode();
+    }
+
+    // the receipt handle built by a lite consumer from the pop response
+    private static String extraInfo(long popTime, long offset) {
+        return ExtraInfoUtil.buildExtraInfo(0, popTime, INVISIBLE, 
KeyBuilder.POP_ORDER_REVIVE_QUEUE, PARENT,
+            "broker", 0, offset);
+    }
+
+    private Batch await(int opaque) throws Exception {
+        return await(opaque, WAIT);
+    }
+
+    private Batch await(int opaque, long timeoutMillis) throws Exception {
+        long deadline = System.currentTimeMillis() + timeoutMillis;
+        while (System.currentTimeMillis() < deadline) {
+            RemotingCommand response = responses.get(opaque);
+            if (response != null) {
+                return new Batch(response);
+            }
+            Thread.sleep(5);
+        }
+        fail("no response of request " + opaque + " in " + timeoutMillis + 
"ms");
+        return null;
+    }
+
+    private void assertPending(int opaque) throws Exception {
+        Thread.sleep(50);
+        assertFalse("request " + opaque + " should wait in long polling", 
responses.containsKey(opaque));
+    }
+
+    private static void awaitTrue(BooleanSupplier condition, String what) 
throws Exception {
+        long deadline = System.currentTimeMillis() + WAIT;
+        while (!condition.getAsBoolean()) {
+            if (System.currentTimeMillis() > deadline) {
+                fail("timeout waiting for " + what);
+            }
+            Thread.sleep(5);
+        }
+    }
+
+    // pop time identifies a lease in milliseconds, so a retry in the same 
millisecond would reuse it
+    private static void nextMillis() throws Exception {
+        Thread.sleep(2);
+    }
+
+    private static final class Batch {
+        private final int code;
+        private final long popTime;
+        private final List<String> messages = new ArrayList<>(); // 
liteTopic@offset
+        private final List<Integer> reconsumeTimes = new ArrayList<>();
+
+        private Batch(RemotingCommand response) {
+            PopLiteMessageResponseHeader header = 
(PopLiteMessageResponseHeader) response.readCustomHeader();
+            this.code = response.getCode();
+            this.popTime = header.getPopTime();
+            if (code != ResponseCode.SUCCESS) {
+                return;
+            }
+            List<MessageExt> found = 
MessageDecoder.decodesBatch(ByteBuffer.wrap(response.getBody()), true, false, 
true);
+            List<Integer> counts = 
ExtraInfoUtil.parseLiteOrderCountInfo(header.getOrderCountInfo(), found.size());
+            for (int i = 0; i < found.size(); i++) {
+                MessageExt message = found.get(i);
+                
messages.add(LiteUtil.getLiteTopic(message.getProperty(MessageConst.PROPERTY_INNER_MULTI_DISPATCH))
+                    + "@" + 
message.getProperty(MessageConst.PROPERTY_INNER_MULTI_QUEUE_OFFSET));
+                reconsumeTimes.add(counts == null ? 0 : counts.get(i));
+            }
+        }
+    }
+}
diff --git 
a/broker/src/test/java/org/apache/rocketmq/broker/processor/PopLiteMessageProcessorAttemptReleaseTest.java
 
b/broker/src/test/java/org/apache/rocketmq/broker/processor/PopLiteMessageProcessorAttemptReleaseTest.java
new file mode 100644
index 0000000000..be633b50db
--- /dev/null
+++ 
b/broker/src/test/java/org/apache/rocketmq/broker/processor/PopLiteMessageProcessorAttemptReleaseTest.java
@@ -0,0 +1,762 @@
+/*
+ * 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.broker.processor;
+
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelHandlerContext;
+import java.net.InetSocketAddress;
+import java.nio.ByteBuffer;
+import java.util.ArrayDeque;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BooleanSupplier;
+import org.apache.commons.lang3.reflect.FieldUtils;
+import org.apache.rocketmq.broker.BrokerController;
+import org.apache.rocketmq.broker.lite.LiteEventDispatcher;
+import org.apache.rocketmq.broker.lite.LiteSubscriptionRegistry;
+import org.apache.rocketmq.broker.longpolling.PollingResult;
+import org.apache.rocketmq.broker.longpolling.PopLiteLongPollingService;
+import org.apache.rocketmq.broker.metrics.BrokerMetricsManager;
+import org.apache.rocketmq.broker.offset.ConsumerOffsetManager;
+import org.apache.rocketmq.broker.offset.MemoryConsumerOrderInfoManager;
+import org.apache.rocketmq.broker.pop.PopConsumerLockService;
+import 
org.apache.rocketmq.broker.pop.orderly.QueueLevelConsumerManager.OrderInfo;
+import org.apache.rocketmq.broker.subscription.SubscriptionGroupManager;
+import org.apache.rocketmq.common.BrokerConfig;
+import org.apache.rocketmq.common.KeyBuilder;
+import org.apache.rocketmq.common.Pair;
+import org.apache.rocketmq.common.lite.LiteUtil;
+import org.apache.rocketmq.remoting.protocol.RemotingCommand;
+import org.apache.rocketmq.remoting.protocol.RequestCode;
+import org.apache.rocketmq.remoting.protocol.ResponseCode;
+import 
org.apache.rocketmq.remoting.protocol.header.PopLiteMessageRequestHeader;
+import org.apache.rocketmq.store.GetMessageResult;
+import org.apache.rocketmq.store.GetMessageStatus;
+import org.apache.rocketmq.store.MessageStore;
+import org.apache.rocketmq.store.SelectMappedBufferResult;
+import org.apache.rocketmq.store.stats.BrokerStatsManager;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.clearInvocations;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * Attempt index and lease state of a same-attemptId lite pop retry, at the 
points a real request flow cannot pin
+ * down: exact lease state after a release, and pops of one attempt 
interleaved at a chosen point. Events and
+ * messages are stubbed here; the recovery scenarios through real components 
are in
+ * {@link PopLiteAttemptRecoveryTest}.
+ */
+public class PopLiteMessageProcessorAttemptReleaseTest {
+    private static final String GROUP = "group";
+    private static final String CLIENT = "client";
+    private static final String LMQ1 = LiteUtil.toLmqName("parent", "one");
+    private static final String LMQ2 = LiteUtil.toLmqName("parent", "two");
+    private static final long INVISIBLE = 600000;
+    private final long firstPopTime = System.currentTimeMillis() - 1000;
+    private final BrokerController broker = mock(BrokerController.class);
+    private final ConsumerOffsetManager offsets = 
mock(ConsumerOffsetManager.class);
+    private final LiteSubscriptionRegistry registry = 
mock(LiteSubscriptionRegistry.class);
+    private final LiteEventDispatcher dispatcher = 
mock(LiteEventDispatcher.class);
+    private final Map<String, Deque<String>> events = new HashMap<>();
+    private final Map<String, Integer> available = new HashMap<>();
+    private PopLiteMessageProcessor processor;
+    private MemoryConsumerOrderInfoManager manager;
+    private String dispatchClient = CLIENT;
+    // the first read of this lmq waits on readResume, to interleave two pops 
of one client
+    private volatile String blockedLmq;
+    private final CountDownLatch readEntered = new CountDownLatch(1);
+    private final CountDownLatch readResume = new CountDownLatch(1);
+    private final Map<Integer, RemotingCommand> responses = new 
ConcurrentHashMap<>();
+    private ChannelHandlerContext requestContext;
+    private PopLiteLongPollingService polling;
+
+    @Before
+    public void setUp() {
+        BrokerConfig config = new BrokerConfig();
+        config.setEnableNotifyAfterPopOrderLockRelease(false);
+        when(broker.getBrokerConfig()).thenReturn(config);
+        when(broker.getConsumerOffsetManager()).thenReturn(offsets);
+        
when(broker.getSubscriptionGroupManager()).thenReturn(mock(SubscriptionGroupManager.class));
+        when(broker.getLiteSubscriptionRegistry()).thenReturn(registry);
+        // no pending offset reset, otherwise the mock returns 0 and the pop 
takes the reset branch
+        when(offsets.queryThenEraseResetOffset(anyString(), anyString(), 
anyInt())).thenReturn(null);
+        when(dispatcher.getEventIterator(anyString())).thenAnswer(invocation 
-> {
+            Deque<String> queue = queue(invocation.getArgument(0));
+            return new Iterator<String>() {
+                public boolean hasNext() {
+                    return !queue.isEmpty();
+                }
+
+                public String next() {
+                    return queue.poll();
+                }
+            };
+        });
+        processor = spy(new PopLiteMessageProcessor(broker, dispatcher));
+        manager = (MemoryConsumerOrderInfoManager) 
processor.getConsumerOrderInfoManager();
+        doNothing().when(processor).recordPopLiteMetrics(any(), anyString(), 
anyString());
+        doAnswer(invocation -> {
+            String lmq = invocation.getArgument(1);
+            String key = KeyBuilder.buildPopLiteLockKey(GROUP, lmq);
+            // the event is dispatched after the queue lock is released
+            assertTrue(processor.getLockService().tryLock(key));
+            processor.getLockService().unlock(key);
+            queue(dispatchClient).add(lmq);
+            return null;
+        }).when(dispatcher).dispatch(anyString(), anyString(), anyInt(), 
anyLong(), anyLong());
+        MessageStore store = mock(MessageStore.class);
+        when(broker.getMessageStore()).thenReturn(store);
+        when(store.getMessage(anyString(), anyString(), anyInt(), anyLong(), 
anyInt(), any()))
+            .thenAnswer(invocation -> {
+                String lmq = invocation.getArgument(1);
+                if (lmq.equals(blockedLmq)) {
+                    blockedLmq = null;
+                    readEntered.countDown();
+                    assertTrue(readResume.await(5, TimeUnit.SECONDS));
+                }
+                long offset = invocation.getArgument(3);
+                int count = Math.min((Integer) invocation.getArgument(4), 
Math.max(0, available.getOrDefault(lmq, 0) - (int) offset));
+                GetMessageResult result = new GetMessageResult();
+                result.setStatus(count > 0 ? GetMessageStatus.FOUND : 
GetMessageStatus.NO_MESSAGE_IN_QUEUE);
+                for (int i = 0; i < count; i++) {
+                    result.addMessage(new SelectMappedBufferResult(0, 
ByteBuffer.wrap(new byte[] {1}), 1, null));
+                    result.getMessageQueueOffset().add(offset + i);
+                }
+                result.setNextBeginOffset(offset + count);
+                return result;
+            });
+        available.put(LMQ1, 2);
+        available.put(LMQ2, 1);
+    }
+
+    @After
+    public void tearDown() {
+        manager.shutdown();
+    }
+
+    private Deque<String> queue(String client) {
+        return events.computeIfAbsent(client, key -> new ArrayDeque<>());
+    }
+
+    private OrderInfo order(String lmq) {
+        return manager.getTable().get(lmq + "@" + GROUP).get(0);
+    }
+
+    private int attemptRecordCount() {
+        return ((Map<?, ?>) readField(processor, "attempts")).size();
+    }
+
+    private int attemptLeaseCount(String clientId) {
+        Map<?, ?> attempts = (Map<?, ?>) readField(processor, "attempts");
+        Object attempt = attempts.get(clientId);
+        return attempt == null ? -1 : ((Set<?>) readField(attempt, 
"lmqNames")).size();
+    }
+
+    private static Object readField(Object target, String fieldName) {
+        try {
+            return FieldUtils.readField(target, fieldName, true);
+        } catch (IllegalAccessException e) {
+            throw new AssertionError(e);
+        }
+    }
+
+    // a newly arrived request, which releases the leases of its lost attempt 
before popping
+    private Pair<StringBuilder, GetMessageResult> pop(String client, String 
attempt, long time, int maxNum) {
+        return arrive(System.nanoTime(), client, attempt, time, maxNum);
+    }
+
+    private Pair<StringBuilder, GetMessageResult> arrive(long arriveTime, 
String client, String attempt, long time,
+        int maxNum) {
+        if (attempt != null) {
+            processor.onArrival(GROUP, client, attempt, arriveTime);
+        }
+        return processor.popByClientId("host", "parent", GROUP, client, time, 
INVISIBLE, maxNum, attempt, arriveTime);
+    }
+
+    // a request woken from long polling, which pops only while it is still 
the latest request of the client
+    private Pair<StringBuilder, GetMessageResult> wake(long arriveTime, String 
client, String attempt, long time,
+        int maxNum) {
+        if (processor.hasNewerRequest(client, arriveTime)) {
+            return new Pair<>(new StringBuilder(), new GetMessageResult());
+        }
+        return processor.popByClientId("host", "parent", GROUP, client, time, 
INVISIBLE, maxNum, attempt, arriveTime);
+    }
+
+    // attempt A pops [0, 1] from LMQ1 and [0] from LMQ2, consuming both events
+    private void firstBatch() {
+        queue(CLIENT).addAll(Arrays.asList(LMQ1, LMQ2));
+        assertEquals(3, pop(CLIENT, "A", firstPopTime, 
3).getObject2().getMessageCount());
+        assertTrue(queue(CLIENT).isEmpty());
+    }
+
+    private void prepareRequestFlow() throws Exception {
+        doReturn(null).when(processor).preCheck(any(), any(), any());
+        
when(broker.getBrokerStatsManager()).thenReturn(mock(BrokerStatsManager.class));
+        
when(broker.getBrokerMetricsManager()).thenReturn(mock(BrokerMetricsManager.class));
+        polling = mock(PopLiteLongPollingService.class);
+        when(polling.polling(any(), any(), anyLong(), anyLong(), anyString(), 
anyString()))
+            .thenReturn(PollingResult.POLLING_TIMEOUT);
+        FieldUtils.writeField(processor, "popLiteLongPollingService", polling, 
true);
+        Channel channel = mock(Channel.class);
+        when(channel.remoteAddress()).thenReturn(new 
InetSocketAddress("127.0.0.1", 10911));
+        ChannelFuture written = mock(ChannelFuture.class);
+        when(written.addListener(any())).thenReturn(written);
+        when(channel.writeAndFlush(any())).thenAnswer(invocation -> {
+            RemotingCommand response = invocation.getArgument(0);
+            responses.put(response.getOpaque(), response);
+            return written;
+        });
+        requestContext = mock(ChannelHandlerContext.class);
+        when(requestContext.channel()).thenReturn(channel);
+        clearInvocations(processor, dispatcher);
+    }
+
+    private RemotingCommand processRetry() throws Exception {
+        PopLiteMessageRequestHeader header = new PopLiteMessageRequestHeader();
+        header.setClientId(CLIENT);
+        header.setConsumerGroup(GROUP);
+        header.setTopic("parent");
+        header.setAttemptId("A");
+        header.setMaxMsgNum(3);
+        header.setInvisibleTime(INVISIBLE);
+        header.setBornTime(System.currentTimeMillis());
+        header.setPollTime(20000L);
+        RemotingCommand request = 
RemotingCommand.createRequestCommand(RequestCode.POP_LITE_MESSAGE, header);
+        request.makeCustomHeaderToNet();
+        RemotingCommand response = processor.processRequest(requestContext, 
request);
+        return response != null ? response : 
responses.remove(request.getOpaque());
+    }
+
+    private String lockLastLease() {
+        Map<?, ?> attempts = (Map<?, ?>) readField(processor, "attempts");
+        Set<?> leases = (Set<?>) readField(attempts.get(CLIENT), "lmqNames");
+        Iterator<?> iterator = leases.iterator();
+        iterator.next();
+        String last = (String) iterator.next();
+        
assertTrue(processor.getLockService().tryLock(KeyBuilder.buildPopLiteLockKey(GROUP,
 last)));
+        return last;
+    }
+
+    @Test
+    public void testIncompleteReleaseReturnsBusyWithoutPopping() throws 
Exception {
+        firstBatch();
+        prepareRequestFlow();
+        String pending = lockLastLease();
+        try {
+            RemotingCommand response = processRetry();
+            assertNotNull(response);
+            assertEquals(ResponseCode.SYSTEM_BUSY, response.getCode());
+            assertNull(response.getBody());
+            assertEquals(1, attemptLeaseCount(CLIENT));
+            assertEquals(firstPopTime, order(pending).getPopTime());
+            String released = pending.equals(LMQ1) ? LMQ2 : LMQ1;
+            assertEquals(-firstPopTime, order(released).getPopTime());
+            assertEquals(Collections.singletonList(released), 
Arrays.asList(queue(CLIENT).toArray()));
+            verify(dispatcher, never()).getEventIterator(anyString());
+            verify(polling, never()).polling(any(), any(), anyLong(), 
anyLong(), anyString(), anyString());
+        } finally {
+            
processor.getLockService().unlock(KeyBuilder.buildPopLiteLockKey(GROUP, 
pending));
+        }
+    }
+
+    @Test
+    public void testSameAttemptRetryCompletesReleaseAfterLockRecovers() throws 
Exception {
+        firstBatch();
+        prepareRequestFlow();
+        String pending = lockLastLease();
+        RemotingCommand incomplete;
+        try {
+            incomplete = processRetry();
+            assertEquals(firstPopTime, order(pending).getPopTime());
+        } finally {
+            
processor.getLockService().unlock(KeyBuilder.buildPopLiteLockKey(GROUP, 
pending));
+        }
+        RemotingCommand recovered = processRetry();
+        assertNotNull(recovered);
+        assertEquals(ResponseCode.SUCCESS, recovered.getCode());
+        assertEquals(3, recovered.getBody().length);
+        assertEquals(2, attemptLeaseCount(CLIENT));
+        assertEquals(order(LMQ1).getPopTime(), order(LMQ2).getPopTime());
+        assertTrue(queue(CLIENT).isEmpty());
+        assertNotNull(incomplete);
+        assertEquals(ResponseCode.SYSTEM_BUSY, incomplete.getCode());
+        assertNull(incomplete.getBody());
+        verify(dispatcher, times(1)).getEventIterator(CLIENT);
+    }
+
+    @Test
+    public void testSupersededRecoveryReturnsBusyAndKeepsNewLeases() throws 
Exception {
+        firstBatch();
+        prepareRequestFlow();
+        CountDownLatch beforeLock = new CountDownLatch(1);
+        CountDownLatch resume = new CountDownLatch(1);
+        AtomicBoolean pause = new AtomicBoolean(true);
+        PopConsumerLockService locks = spy(processor.getLockService());
+        FieldUtils.writeField(processor, "lockService", locks, true);
+        doAnswer(invocation -> {
+            if (pause.compareAndSet(true, false)) {
+                beforeLock.countDown();
+                assertTrue(resume.await(5, TimeUnit.SECONDS));
+            }
+            return invocation.callRealMethod();
+        }).when(locks).tryLock(anyString());
+        ExecutorService executor = Executors.newSingleThreadExecutor();
+        Future<RemotingCommand> stale = executor.submit(this::processRetry);
+        try {
+            assertTrue(beforeLock.await(5, TimeUnit.SECONDS));
+            RemotingCommand latest = processRetry();
+            assertNotNull(latest);
+            assertEquals(ResponseCode.SUCCESS, latest.getCode());
+            assertEquals(3, latest.getBody().length);
+            long latestPopTime = order(LMQ1).getPopTime();
+            assertTrue(latestPopTime > firstPopTime);
+            resume.countDown();
+            RemotingCommand superseded = stale.get(5, TimeUnit.SECONDS);
+            assertEquals(latestPopTime, order(LMQ1).getPopTime());
+            assertEquals(latestPopTime, order(LMQ2).getPopTime());
+            assertEquals(2, attemptLeaseCount(CLIENT));
+            assertNotNull(superseded);
+            assertEquals(ResponseCode.SYSTEM_BUSY, superseded.getCode());
+            assertNull(superseded.getBody());
+            verify(dispatcher, times(1)).getEventIterator(CLIENT);
+            verify(polling, never()).polling(any(), any(), anyLong(), 
anyLong(), anyString(), anyString());
+        } finally {
+            resume.countDown();
+            executor.shutdownNow();
+            assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS));
+        }
+    }
+
+    @Test
+    public void testNewAttemptAndOtherClientCannotReleaseOldLeases() {
+        firstBatch();
+        assertEquals(0, pop(CLIENT, "B", System.currentTimeMillis(), 
3).getObject2().getMessageCount());
+        assertEquals(0, pop("other", "A", System.currentTimeMillis(), 
3).getObject2().getMessageCount());
+        assertEquals(firstPopTime, order(LMQ1).getPopTime());
+        assertTrue(manager.checkBlock("C", LMQ1, GROUP, 0, INVISIBLE));
+    }
+
+    @Test
+    public void testReleasePreservesStateAndRejectsOldAckRenewAndSuspend() {
+        firstBatch();
+        OrderInfo old = order(LMQ1);
+        old.setCommitOffsetBit(1);
+        old.setOffsetConsumedCount(Collections.singletonMap(1L, 4));
+        manager.updateNextVisibleTime(LMQ1, GROUP, 0, 1, firstPopTime, 
System.currentTimeMillis() + INVISIBLE * 10);
+
+        assertTrue(manager.releaseQueue(LMQ1, GROUP, 0, "A"));
+        assertSame(old, order(LMQ1));
+        assertNull(old.getOffsetNextVisibleTime());
+        assertEquals(1, old.getCommitOffsetBit());
+        assertEquals(Integer.valueOf(4), old.getOffsetConsumedCount().get(1L));
+
+        assertEquals(-2, manager.commitAndNext(LMQ1, GROUP, 0, 1, 
firstPopTime));
+        manager.updateNextVisibleTime(LMQ1, GROUP, 0, 1, firstPopTime, 
System.currentTimeMillis() + INVISIBLE * 20);
+        manager.suspendQueue(LMQ1, GROUP, 0, firstPopTime, 
System.currentTimeMillis() + INVISIBLE * 20);
+        assertNull(old.getOffsetNextVisibleTime());
+        assertFalse(manager.checkBlock("B", LMQ1, GROUP, 0, INVISIBLE));
+        assertFalse(manager.releaseQueue(LMQ1, GROUP, 0, "A"));
+        assertEquals(firstPopTime, -old.getPopTime());
+    }
+
+    @Test
+    public void testRetryReleasesLeaseRenewedBySameAttemptInOverlappingPop() {
+        firstBatch();
+        // a stale request of the same attempt re-pops LMQ1 later, so its 
lease is newer than the recorded batch
+        long stalePopTime = firstPopTime + 500;
+        manager.update("A", false, LMQ1, GROUP, 0, stalePopTime, INVISIBLE, 
Arrays.asList(0L, 1L), new StringBuilder());
+
+        long retryTime = System.currentTimeMillis();
+        assertEquals(3, pop(CLIENT, "A", retryTime, 
3).getObject2().getMessageCount());
+        assertEquals(retryTime, order(LMQ1).getPopTime());
+        assertEquals(-2, manager.commitAndNext(LMQ1, GROUP, 0, 0, 
stalePopTime));
+    }
+
+    @Test
+    public void testRecoveryDoesNotReleaseLeaseTakenOverByAnotherAttempt() {
+        firstBatch();
+        long newer = System.currentTimeMillis();
+        manager.update("B", false, LMQ1, GROUP, 0, newer, INVISIBLE, 
Arrays.asList(0L, 1L), new StringBuilder());
+        pop(CLIENT, "A", newer + 1, 3);
+        assertEquals(newer, order(LMQ1).getPopTime());
+        assertEquals("B", order(LMQ1).getAttemptId());
+    }
+
+    @Test
+    public void testFullyAcknowledgedQueuesAreNotReleasedOrDispatched() {
+        firstBatch();
+        order(LMQ1).setCommitOffsetBit(3);
+        order(LMQ2).setCommitOffsetBit(1);
+        assertEquals(0, pop(CLIENT, "A", System.currentTimeMillis(), 
3).getObject2().getMessageCount());
+        assertEquals(firstPopTime, order(LMQ1).getPopTime());
+        assertTrue(queue(CLIENT).isEmpty());
+    }
+
+    @Test
+    public void testOverlappingSameAttemptPopsKeepAllQueuesReleasable() throws 
Exception {
+        // R1 is woken while still the latest request, reads LMQ1 and pauses 
before recording its attempt
+        long r1 = System.nanoTime();
+        assertEquals(0, arrive(r1, CLIENT, "A", firstPopTime, 
3).getObject2().getMessageCount());
+        blockedLmq = LMQ1;
+        queue(CLIENT).add(LMQ1);
+        AtomicInteger staleCount = new AtomicInteger(-1);
+        Thread stale = new Thread(() ->
+            staleCount.set(wake(r1, CLIENT, "A", firstPopTime, 
3).getObject2().getMessageCount()));
+        stale.start();
+        assertTrue(readEntered.await(5, TimeUnit.SECONDS));
+
+        // meanwhile the retry R2 of the same attempt reads LMQ2 and records 
it first
+        queue(CLIENT).add(LMQ2);
+        assertEquals(1, pop(CLIENT, "A", firstPopTime + 1, 
3).getObject2().getMessageCount());
+        readResume.countDown();
+        stale.join(5000);
+        assertEquals(2, staleCount.get());
+        // R1 recorded LMQ1 to the retry and re-dispatched it, which the long 
polling retry would take
+        assertEquals(LMQ1, queue(CLIENT).poll());
+
+        // both responses are lost, so retrying A must release the leases of 
both queues
+        dispatchClient = "other";
+        pop(CLIENT, "A", System.currentTimeMillis(), 3);
+        assertFalse(manager.checkBlock("other", LMQ1, GROUP, 0, INVISIBLE));
+        assertFalse(manager.checkBlock("other", LMQ2, GROUP, 0, INVISIBLE));
+    }
+
+    @Test
+    public void testRetryRepopsLeaseRecordedByPopInFlightAtItsArrival() throws 
Exception {
+        // R1 of attempt A reads LMQ1 and pauses before recording its lease
+        long r1 = System.nanoTime();
+        blockedLmq = LMQ1;
+        queue(CLIENT).add(LMQ1);
+        AtomicInteger staleCount = new AtomicInteger(-1);
+        Thread stale = new Thread(() ->
+            staleCount.set(arrive(r1, CLIENT, "A", firstPopTime, 
3).getObject2().getMessageCount()));
+        stale.start();
+        assertTrue(readEntered.await(5, TimeUnit.SECONDS));
+
+        // the response of R1 is lost, and its retry R2 arrives with nothing 
to release and nothing to pop
+        long r2 = System.nanoTime();
+        long retryTime = System.currentTimeMillis();
+        assertEquals(0, arrive(r2, CLIENT, "A", retryTime, 
3).getObject2().getMessageCount());
+        readResume.countDown();
+        stale.join(5000);
+        assertEquals(2, staleCount.get());
+
+        // R1 records its lease to R2 and re-dispatches LMQ1, so R2 woken from 
long polling re-pops the batch
+        assertEquals(Collections.singletonList(LMQ1), 
Arrays.asList(queue(CLIENT).toArray()));
+        assertEquals(2, wake(r2, CLIENT, "A", retryTime, 
3).getObject2().getMessageCount());
+        assertEquals(retryTime, order(LMQ1).getPopTime());
+        assertEquals(1, attemptLeaseCount(CLIENT));
+    }
+
+    @Test
+    public void testLeaseRecordedAfterRetryIsReleasedForAnotherClient() throws 
Exception {
+        // R1 of attempt A reads LMQ1 and pauses before recording its lease
+        long r1 = System.nanoTime();
+        blockedLmq = LMQ1;
+        queue(CLIENT).add(LMQ1);
+        AtomicInteger staleCount = new AtomicInteger(-1);
+        Thread stale = new Thread(() ->
+            staleCount.set(arrive(r1, CLIENT, "A", firstPopTime, 
3).getObject2().getMessageCount()));
+        stale.start();
+        assertTrue(readEntered.await(5, TimeUnit.SECONDS));
+
+        // the response of R1 is lost, and its retry R2 arrives with nothing 
to release and nothing to pop
+        assertEquals(0, arrive(System.nanoTime(), CLIENT, "A", 
System.currentTimeMillis(), 3)
+            .getObject2().getMessageCount());
+        // the event re-dispatched by R1 goes to another client of the group, 
as in shared consumption or migration
+        dispatchClient = "other";
+        readResume.countDown();
+        stale.join(5000);
+        assertEquals(2, staleCount.get());
+        assertEquals(Collections.singletonList(LMQ1), 
Arrays.asList(queue("other").toArray()));
+        // the lease released by R1 is not recorded to the retry
+        assertEquals(0, attemptLeaseCount(CLIENT));
+
+        // the lease of the lost R1 must not block the client taking the event
+        assertEquals(2, pop("other", "C", System.currentTimeMillis(), 
3).getObject2().getMessageCount());
+    }
+
+    @Test
+    public void testNewerRequestBeforeQueueLockKeepsRetryLease() throws 
Exception {
+        // R1 of attempt A takes the LMQ1 event and pauses before the queue 
lock
+        CountDownLatch beforeLock = new CountDownLatch(1);
+        CountDownLatch resume = new CountDownLatch(1);
+        AtomicBoolean pause = new AtomicBoolean(true);
+        doAnswer(invocation -> {
+            if (pause.compareAndSet(true, false)) {
+                beforeLock.countDown();
+                assertTrue(resume.await(5, TimeUnit.SECONDS));
+            }
+            return invocation.callRealMethod();
+        }).when(processor).popLiteTopic(anyString(), anyString(), anyString(), 
anyString(), anyLong(), anyLong(),
+            anyLong(), anyString(), any(), anyString(), anyLong());
+        queue(CLIENT).add(LMQ1);
+        AtomicInteger staleCount = new AtomicInteger(-1);
+        Thread stale = new Thread(() ->
+            staleCount.set(pop(CLIENT, "A", firstPopTime, 
3).getObject2().getMessageCount()));
+        stale.start();
+        assertTrue(beforeLock.await(5, TimeUnit.SECONDS));
+
+        // its retry R2 pops LMQ1 on another event, and its response is being 
delivered
+        long retryTime = System.currentTimeMillis();
+        queue(CLIENT).add(LMQ1);
+        assertEquals(2, pop(CLIENT, "A", retryTime, 
3).getObject2().getMessageCount());
+        resume.countDown();
+        stale.join(5000);
+
+        // R1 leaves the lease of R2 intact and passes its taken event on
+        assertEquals(0, staleCount.get());
+        assertEquals(retryTime, order(LMQ1).getPopTime());
+        assertTrue(manager.checkBlock("C", LMQ1, GROUP, 0, INVISIBLE));
+        assertEquals(Collections.singletonList(LMQ1), 
Arrays.asList(queue(CLIENT).toArray()));
+    }
+
+    @Test
+    public void testFailedRedispatchKeepsMessagesRead() throws Exception {
+        doThrow(new RejectedExecutionException("rejected"))
+            .when(dispatcher).dispatch(anyString(), anyString(), anyInt(), 
anyLong(), anyLong());
+        // R1 of attempt A reads LMQ1 and pauses before recording its lease
+        blockedLmq = LMQ1;
+        queue(CLIENT).add(LMQ1);
+        long r1 = System.nanoTime();
+        AtomicInteger staleCount = new AtomicInteger(-1);
+        Thread stale = new Thread(() ->
+            staleCount.set(arrive(r1, CLIENT, "A", firstPopTime, 
3).getObject2().getMessageCount()));
+        stale.start();
+        assertTrue(readEntered.await(5, TimeUnit.SECONDS));
+
+        // the retry makes R1 release and re-dispatch, and the re-dispatch 
fails
+        arrive(System.nanoTime(), CLIENT, "A", System.currentTimeMillis(), 3);
+        readResume.countDown();
+        stale.join(5000);
+        assertEquals(2, staleCount.get());
+    }
+
+    @Test
+    public void 
testReleaseWaitingForQueueLockIsNotInterruptedByAnotherAttempt() throws 
Exception {
+        firstBatch();
+        // hold both queue locks, so the release of retry R1 stalls before 
touching any lease
+        String lock1 = KeyBuilder.buildPopLiteLockKey(GROUP, LMQ1);
+        String lock2 = KeyBuilder.buildPopLiteLockKey(GROUP, LMQ2);
+        assertTrue(processor.getLockService().tryLock(lock1));
+        assertTrue(processor.getLockService().tryLock(lock2));
+        long r1 = System.nanoTime();
+        Thread retry = new Thread(() -> processor.onArrival(GROUP, CLIENT, 
"A", r1));
+        try {
+            retry.start();
+            awaitTrue(() -> processor.hasNewerRequest(CLIENT, r1 - 1));
+
+            // a new attempt inherits nothing, so giving way to it would leave 
the leases of A unreleased
+            processor.onArrival(GROUP, CLIENT, "B", System.nanoTime());
+            assertTrue(retry.isAlive());
+            processor.getLockService().unlock(lock1);
+            processor.getLockService().unlock(lock2);
+            retry.join(5000);
+        } finally {
+            processor.getLockService().unlock(lock1);
+            processor.getLockService().unlock(lock2);
+        }
+        assertFalse(retry.isAlive());
+
+        // R1 released both leases of A and re-dispatched them
+        assertFalse(manager.checkBlock("C", LMQ1, GROUP, 0, INVISIBLE));
+        assertFalse(manager.checkBlock("C", LMQ2, GROUP, 0, INVISIBLE));
+        assertEquals(2, queue(CLIENT).size());
+        assertTrue(queue(CLIENT).containsAll(Arrays.asList(LMQ1, LMQ2)));
+    }
+
+    @Test
+    public void testRecordsAreBoundedByClientsNotRequests() {
+        // every delivered batch is followed by a new attempt, which replaces 
the record of the client
+        for (int i = 0; i < 1000; i++) {
+            available.put(LMQ1, i + 1);
+            queue(CLIENT).add(LMQ1);
+            manager.clearBlock(LMQ1, GROUP, 0);
+            when(offsets.queryOffset(GROUP, LMQ1, 0)).thenReturn((long) i);
+            assertEquals(1, pop(CLIENT, "attempt-" + i, 
System.currentTimeMillis(), 1).getObject2().getMessageCount());
+            assertEquals(1, attemptLeaseCount(CLIENT));
+        }
+        pop("other", "X", System.currentTimeMillis(), 1);
+        // a request without an attemptId leaves no record
+        pop("third", null, System.currentTimeMillis(), 1);
+        assertEquals(2, attemptRecordCount());
+    }
+
+    @Test
+    public void testInterruptedReleaseIsTakenOverByNewerRetry() throws 
Exception {
+        firstBatch();
+        // the stalled R1 may hold a queue lock briefly while giving up, so 
the lock is not asserted on dispatch here
+        doAnswer(invocation -> 
queue(dispatchClient).add(invocation.getArgument(1)))
+            .when(dispatcher).dispatch(anyString(), anyString(), anyInt(), 
anyLong(), anyLong());
+        // hold both queue locks, so the release of retry R1 stalls before 
touching any lease
+        String lock1 = KeyBuilder.buildPopLiteLockKey(GROUP, LMQ1);
+        String lock2 = KeyBuilder.buildPopLiteLockKey(GROUP, LMQ2);
+        assertTrue(processor.getLockService().tryLock(lock1));
+        assertTrue(processor.getLockService().tryLock(lock2));
+        long r1 = System.nanoTime();
+        Thread stalled = new Thread(() -> processor.onArrival(GROUP, CLIENT, 
"A", r1));
+        stalled.start();
+        awaitTrue(() -> processor.hasNewerRequest(CLIENT, r1 - 1));
+
+        // retry R2 of the same attempt arrives meanwhile, takes over the 
release and re-pops the batch
+        long r2 = System.nanoTime();
+        long retryTime = System.currentTimeMillis();
+        AtomicInteger retryCount = new AtomicInteger(-1);
+        Thread retry = new Thread(() ->
+            retryCount.set(arrive(r2, CLIENT, "A", retryTime, 
3).getObject2().getMessageCount()));
+        retry.start();
+        awaitTrue(() -> processor.hasNewerRequest(CLIENT, r2 - 1));
+        processor.getLockService().unlock(lock1);
+        processor.getLockService().unlock(lock2);
+        stalled.join(5000);
+        retry.join(5000);
+
+        // R1 released nothing after R2 arrived, so the leases R2 re-took are 
intact
+        assertEquals(3, retryCount.get());
+        assertEquals(retryTime, order(LMQ1).getPopTime());
+        assertEquals(retryTime, order(LMQ2).getPopTime());
+        assertEquals(2, attemptLeaseCount(CLIENT));
+    }
+
+    @Test
+    public void testEventTakenAfterRetryArrivesIsPassedOnNotDeduped() {
+        // like the real dispatcher, an event of an lmq already queued for the 
client is merged
+        doAnswer(invocation -> {
+            String lmq = invocation.getArgument(1);
+            if (!queue(dispatchClient).contains(lmq)) {
+                queue(dispatchClient).add(lmq);
+            }
+            return null;
+        }).when(dispatcher).dispatch(anyString(), anyString(), anyInt(), 
anyLong(), anyLong());
+        // R1 of attempt A reads LMQ1, and a later notification of LMQ1 is 
queued behind
+        queue(CLIENT).addAll(Arrays.asList(LMQ1, LMQ1));
+        long r1 = System.nanoTime();
+        long r2 = r1 + 1;
+        AtomicInteger taken = new AtomicInteger();
+        when(dispatcher.getEventIterator(CLIENT)).thenAnswer(invocation -> new 
Iterator<String>() {
+            public boolean hasNext() {
+                return !queue(CLIENT).isEmpty();
+            }
+
+            public String next() {
+                if (taken.incrementAndGet() == 2) {
+                    // the retry R2 arrives right before R1 takes the event, 
and its re-dispatch is merged into it
+                    processor.onArrival(GROUP, CLIENT, "A", r2);
+                }
+                return queue(CLIENT).poll();
+            }
+        });
+        assertEquals(2, arrive(r1, CLIENT, "A", firstPopTime, 
3).getObject2().getMessageCount());
+
+        // R1 passes the event on, so R2 woken from long polling re-pops the 
released batch
+        assertEquals(Collections.singletonList(LMQ1), 
Arrays.asList(queue(CLIENT).toArray()));
+        long retryTime = System.currentTimeMillis();
+        assertEquals(2, wake(r2, CLIENT, "A", retryTime, 
3).getObject2().getMessageCount());
+        assertEquals(retryTime, order(LMQ1).getPopTime());
+    }
+
+    @Test
+    public void testExpiredRecordKeepsItsLeases() {
+        firstBatch();
+        // within the ttl a retry of the same attempt may still arrive, so the 
record stays
+        processor.cleanAttempts(System.nanoTime() + 
PopLiteMessageProcessor.ATTEMPT_TTL / 2);
+        assertEquals(2, attemptLeaseCount(CLIENT));
+
+        // past the ttl only the record is cleaned, the batch may still be 
consumed under its leases
+        processor.cleanAttempts(System.nanoTime() + 
PopLiteMessageProcessor.ATTEMPT_TTL + 1);
+        assertEquals(-1, attemptLeaseCount(CLIENT));
+        assertEquals(firstPopTime, order(LMQ1).getPopTime());
+        assertEquals(firstPopTime, order(LMQ2).getPopTime());
+        assertTrue(manager.checkBlock("C", LMQ1, GROUP, 0, INVISIBLE));
+        assertTrue(manager.checkBlock("C", LMQ2, GROUP, 0, INVISIBLE));
+        assertTrue(queue(CLIENT).isEmpty());
+    }
+
+    private static void awaitTrue(BooleanSupplier condition) throws 
InterruptedException {
+        long deadline = System.currentTimeMillis() + 5000;
+        while (!condition.getAsBoolean()) {
+            assertTrue(System.currentTimeMillis() < deadline);
+            Thread.sleep(1);
+        }
+    }
+
+    @Test
+    public void testLeaseRecordedAfterNewerAttemptIsReleasedForAnotherClient() 
throws Exception {
+        // R1 of attempt A reads LMQ1 and pauses before recording its attempt
+        blockedLmq = LMQ1;
+        queue(CLIENT).add(LMQ1);
+        AtomicInteger olderCount = new AtomicInteger(-1);
+        Thread older = new Thread(() ->
+            olderCount.set(pop(CLIENT, "A", firstPopTime, 
3).getObject2().getMessageCount()));
+        older.start();
+        assertTrue(readEntered.await(5, TimeUnit.SECONDS));
+
+        // meanwhile the newer R2 of attempt B reads LMQ2 and records it first
+        queue(CLIENT).add(LMQ2);
+        assertEquals(1, pop(CLIENT, "B", System.currentTimeMillis(), 
3).getObject2().getMessageCount());
+        dispatchClient = "other";
+        readResume.countDown();
+        older.join(5000);
+        assertEquals(2, olderCount.get());
+
+        // R1 releases its own lease and re-dispatches LMQ1, leaving the lease 
of B recorded
+        assertFalse(manager.checkBlock("other", LMQ1, GROUP, 0, INVISIBLE));
+        assertEquals(Collections.singletonList(LMQ1), 
Arrays.asList(queue("other").toArray()));
+        assertTrue(manager.checkBlock("other", LMQ2, GROUP, 0, INVISIBLE));
+        assertEquals(1, attemptLeaseCount(CLIENT));
+
+        // the response of B is lost, so retrying B releases its lease
+        pop(CLIENT, "B", System.currentTimeMillis(), 3);
+        assertFalse(manager.checkBlock("other", LMQ2, GROUP, 0, INVISIBLE));
+    }
+}
diff --git 
a/broker/src/test/java/org/apache/rocketmq/broker/processor/PopLiteMessageProcessorEventLossTest.java
 
b/broker/src/test/java/org/apache/rocketmq/broker/processor/PopLiteMessageProcessorEventLossTest.java
index 6d3d28d1df..5523cc8f1a 100644
--- 
a/broker/src/test/java/org/apache/rocketmq/broker/processor/PopLiteMessageProcessorEventLossTest.java
+++ 
b/broker/src/test/java/org/apache/rocketmq/broker/processor/PopLiteMessageProcessorEventLossTest.java
@@ -185,7 +185,7 @@ public class PopLiteMessageProcessorEventLossTest {
             }
             return real;
         }).when(popLiteMessageProcessor).popLiteTopic(anyString(), 
anyString(), anyString(), anyString(),
-            anyLong(), anyLong(), anyLong(), anyString(), any());
+            anyLong(), anyLong(), anyLong(), anyString(), any(), anyString(), 
anyLong());
     }
 
     @AfterClass
@@ -277,7 +277,7 @@ public class PopLiteMessageProcessorEventLossTest {
             LAST_POP_READS.clear();
         }
         popLiteMessageProcessor.popByClientId(CLIENT_HOST, PARENT_TOPIC, 
GROUP, CLIENT_ID,
-            popTime, INVISIBLE, MAX_NUM, UUID.randomUUID().toString());
+            popTime, INVISIBLE, MAX_NUM, UUID.randomUUID().toString(), 
System.nanoTime());
         synchronized (LAST_POP_READS) {
             Map<String, List<Long>> copy = new HashMap<>();
             for (Map.Entry<String, List<Long>> e : LAST_POP_READS.entrySet()) {
diff --git 
a/broker/src/test/java/org/apache/rocketmq/broker/processor/PopLiteMessageProcessorTest.java
 
b/broker/src/test/java/org/apache/rocketmq/broker/processor/PopLiteMessageProcessorTest.java
index 5ae6b46d8c..9c606d8e11 100644
--- 
a/broker/src/test/java/org/apache/rocketmq/broker/processor/PopLiteMessageProcessorTest.java
+++ 
b/broker/src/test/java/org/apache/rocketmq/broker/processor/PopLiteMessageProcessorTest.java
@@ -25,8 +25,8 @@ import org.apache.rocketmq.broker.lite.LiteEventDispatcher;
 import org.apache.rocketmq.broker.lite.LiteSubscriptionRegistry;
 import org.apache.rocketmq.broker.longpolling.PopLiteLongPollingService;
 import org.apache.rocketmq.broker.offset.ConsumerOffsetManager;
+import org.apache.rocketmq.broker.offset.MemoryConsumerOrderInfoManager;
 import org.apache.rocketmq.broker.pop.PopConsumerLockService;
-import org.apache.rocketmq.broker.pop.orderly.ConsumerOrderInfoManager;
 import org.apache.rocketmq.broker.subscription.SubscriptionGroupManager;
 import org.apache.rocketmq.broker.topic.TopicConfigManager;
 import org.apache.rocketmq.common.BrokerConfig;
@@ -91,7 +91,7 @@ public class PopLiteMessageProcessorTest {
     @Mock
     private PopConsumerLockService lockService;
     @Mock
-    private ConsumerOrderInfoManager consumerOrderInfoManager;
+    private MemoryConsumerOrderInfoManager consumerOrderInfoManager;
     @Mock
     private ConsumerOffsetManager consumerOffsetManager;
     @Mock
@@ -214,7 +214,7 @@ public class PopLiteMessageProcessorTest {
         
when(liteEventDispatcher.getEventIterator("clientId")).thenReturn(mockIterator);
 
         Pair<StringBuilder, GetMessageResult> result = 
popLiteMessageProcessor.popByClientId(
-            "clientHost", "parentTopic", "group", "clientId", 
System.currentTimeMillis(), 6000L, 32, "attemptId");
+            "clientHost", "parentTopic", "group", "clientId", 
System.currentTimeMillis(), 6000L, 32, "attemptId", System.nanoTime());
 
         assertEquals(0, result.getObject1().length());
         assertEquals(0, result.getObject2().getMessageCount());
@@ -235,14 +235,14 @@ public class PopLiteMessageProcessorTest {
         
when(liteEventDispatcher.getEventIterator("clientId")).thenReturn(mockIterator);
         doReturn(new Pair<>(new StringBuilder("0"), mockResult))
             .when(popLiteMessageProcessor)
-            .popLiteTopic(anyString(), anyString(), anyString(), anyString(), 
anyLong(), anyLong(), anyLong(), anyString(), anySet());
+            .popLiteTopic(anyString(), anyString(), anyString(), anyString(), 
anyLong(), anyLong(), anyLong(), anyString(), anySet(), anyString(), anyLong());
 
         Pair<StringBuilder, GetMessageResult> result = 
popLiteMessageProcessor.popByClientId(
-            "clientHost", "parentTopic", "group", "clientId", pollTime, 6000L, 
32, "attemptId");
+            "clientHost", "parentTopic", "group", "clientId", pollTime, 6000L, 
32, "attemptId", System.nanoTime());
 
         assertEquals(msgCount, result.getObject2().getMessageCount());
         verify(mockIterator, times(2)).hasNext();
-        verify(popLiteMessageProcessor).popLiteTopic(eq("parentTopic"), 
eq("clientHost"), eq("group"), eq(event), eq(32L), eq(pollTime), eq(6000L), 
eq("attemptId"), anySet());
+        verify(popLiteMessageProcessor).popLiteTopic(eq("parentTopic"), 
eq("clientHost"), eq("group"), eq(event), eq(32L), eq(pollTime), eq(6000L), 
eq("attemptId"), anySet(), eq("clientId"), anyLong());
     }
 
     @SuppressWarnings("unchecked")
@@ -260,16 +260,16 @@ public class PopLiteMessageProcessorTest {
         
when(liteEventDispatcher.getEventIterator("clientId")).thenReturn(mockIterator);
         doReturn(new Pair<>(new StringBuilder("0"), mockResult))
             .when(popLiteMessageProcessor)
-            .popLiteTopic(anyString(), anyString(), anyString(), anyString(), 
anyLong(), anyLong(), anyLong(), anyString(), anySet());
+            .popLiteTopic(anyString(), anyString(), anyString(), anyString(), 
anyLong(), anyLong(), anyLong(), anyString(), anySet(), anyString(), anyLong());
 
         Pair<StringBuilder, GetMessageResult> result = 
popLiteMessageProcessor.popByClientId(
-            "clientHost", "parentTopic", "group", "clientId", pollTime, 6000L, 
2, "attemptId");
+            "clientHost", "parentTopic", "group", "clientId", pollTime, 6000L, 
2, "attemptId", System.nanoTime());
 
         assertEquals(2, result.getObject2().getMessageCount());
         assertEquals("0;0", result.getObject1().toString());
         verify(mockIterator, times(2)).hasNext();
-        verify(popLiteMessageProcessor).popLiteTopic(eq("parentTopic"), 
eq("clientHost"), eq("group"), eq(event1), eq(2L), eq(pollTime), eq(6000L), 
eq("attemptId"), anySet());
-        verify(popLiteMessageProcessor).popLiteTopic(eq("parentTopic"), 
eq("clientHost"), eq("group"), eq(event2), eq(1L), eq(pollTime), eq(6000L), 
eq("attemptId"), anySet());
+        verify(popLiteMessageProcessor).popLiteTopic(eq("parentTopic"), 
eq("clientHost"), eq("group"), eq(event1), eq(2L), eq(pollTime), eq(6000L), 
eq("attemptId"), anySet(), eq("clientId"), anyLong());
+        verify(popLiteMessageProcessor).popLiteTopic(eq("parentTopic"), 
eq("clientHost"), eq("group"), eq(event2), eq(1L), eq(pollTime), eq(6000L), 
eq("attemptId"), anySet(), eq("clientId"), anyLong());
     }
 
     @SuppressWarnings("unchecked")
@@ -293,16 +293,16 @@ public class PopLiteMessageProcessorTest {
             processed.add(invocation.getArgument(3));
             return new Pair<>(new StringBuilder("0"), mockResult);
         }).when(popLiteMessageProcessor)
-            .popLiteTopic(anyString(), anyString(), anyString(), anyString(), 
anyLong(), anyLong(), anyLong(), anyString(), anySet());
+            .popLiteTopic(anyString(), anyString(), anyString(), anyString(), 
anyLong(), anyLong(), anyLong(), anyString(), anySet(), anyString(), anyLong());
 
         Pair<StringBuilder, GetMessageResult> result = 
popLiteMessageProcessor.popByClientId(
-            "clientHost", "parentTopic", "group", "clientId", pollTime, 6000L, 
32, "attemptId");
+            "clientHost", "parentTopic", "group", "clientId", pollTime, 6000L, 
32, "attemptId", System.nanoTime());
 
         assertEquals(2, result.getObject2().getMessageCount());
         assertEquals("0;0", result.getObject1().toString());
         verify(mockIterator, times(4)).hasNext();
-        verify(popLiteMessageProcessor).popLiteTopic(eq("parentTopic"), 
eq("clientHost"), eq("group"), eq(event1), eq(32L), eq(pollTime), eq(6000L), 
eq("attemptId"), anySet());
-        verify(popLiteMessageProcessor).popLiteTopic(eq("parentTopic"), 
eq("clientHost"), eq("group"), eq(event2), eq(31L), eq(pollTime), eq(6000L), 
eq("attemptId"), anySet());
+        verify(popLiteMessageProcessor).popLiteTopic(eq("parentTopic"), 
eq("clientHost"), eq("group"), eq(event1), eq(32L), eq(pollTime), eq(6000L), 
eq("attemptId"), anySet(), eq("clientId"), anyLong());
+        verify(popLiteMessageProcessor).popLiteTopic(eq("parentTopic"), 
eq("clientHost"), eq("group"), eq(event2), eq(31L), eq(pollTime), eq(6000L), 
eq("attemptId"), anySet(), eq("clientId"), anyLong());
     }
 
     @SuppressWarnings("unchecked")
@@ -324,7 +324,7 @@ public class PopLiteMessageProcessorTest {
         when(messageStore.getMessage("group", event, 0, 0, 32, 
null)).thenReturn(emptyResult, foundResult);
 
         Pair<StringBuilder, GetMessageResult> result = 
popLiteMessageProcessor.popByClientId(
-            "clientHost", "parentTopic", "group", "clientId", pollTime, 6000L, 
32, "attemptId");
+            "clientHost", "parentTopic", "group", "clientId", pollTime, 6000L, 
32, "attemptId", System.nanoTime());
 
         assertEquals(1, result.getObject2().getMessageCount());
         verify(messageStore, times(2)).getMessage("group", event, 0, 0, 32, 
null);
@@ -397,7 +397,7 @@ public class PopLiteMessageProcessorTest {
 
         Set<String> processed = new HashSet<>();
         Pair<StringBuilder, GetMessageResult> result = 
popLiteMessageProcessor.popLiteTopic("parentTopic",
-            "clientHost", "group", "lmqName", 32L, System.currentTimeMillis(), 
6000L, "attemptId", processed);
+            "clientHost", "group", "lmqName", 32L, System.currentTimeMillis(), 
6000L, "attemptId", processed, "clientId", 0L);
 
         assertNull(result);
         assertFalse(processed.contains("lmqName"));
@@ -413,7 +413,7 @@ public class PopLiteMessageProcessorTest {
 
         Set<String> processed = new HashSet<>();
         Pair<StringBuilder, GetMessageResult> result = 
popLiteMessageProcessor.popLiteTopic("parentTopic",
-            "clientHost", "group", "lmqName", 32L, System.currentTimeMillis(), 
6000L, "attemptId", processed);
+            "clientHost", "group", "lmqName", 32L, System.currentTimeMillis(), 
6000L, "attemptId", processed, "clientId", 0L);
 
         assertThat(result).isNull();
         assertFalse(processed.contains("lmqName"));
@@ -431,7 +431,7 @@ public class PopLiteMessageProcessorTest {
 
         Set<String> processed = new HashSet<>();
         Pair<StringBuilder, GetMessageResult> result = 
popLiteMessageProcessor.popLiteTopic("parentTopic",
-            "clientHost", "group", "lmqName", 32L, System.currentTimeMillis(), 
6000L, "attemptId", processed);
+            "clientHost", "group", "lmqName", 32L, System.currentTimeMillis(), 
6000L, "attemptId", processed, "clientId", 0L);
 
         assertEquals(mockResult, result.getObject2());
         assertTrue(processed.contains("lmqName"));
@@ -449,7 +449,7 @@ public class PopLiteMessageProcessorTest {
 
         Set<String> processed = new HashSet<>();
         Pair<StringBuilder, GetMessageResult> result = 
popLiteMessageProcessor.popLiteTopic("parentTopic",
-            "clientHost", "group", "lmqName", 32L, System.currentTimeMillis(), 
6000L, "attemptId", processed);
+            "clientHost", "group", "lmqName", 32L, System.currentTimeMillis(), 
6000L, "attemptId", processed, "clientId", 0L);
 
         assertEquals(0, result.getObject2().getMessageCount());
         assertFalse(processed.contains("lmqName"));
@@ -565,13 +565,13 @@ public class PopLiteMessageProcessorTest {
         
when(liteEventDispatcher.getEventIterator(clientId)).thenReturn(mockIterator);
 
         Pair<StringBuilder, GetMessageResult> result = 
popLiteMessageProcessor.popByClientId(
-            "clientHost", "parentTopic", group, clientId, 
System.currentTimeMillis(), 6000L, 32, "attemptId");
+            "clientHost", "parentTopic", group, clientId, 
System.currentTimeMillis(), 6000L, 32, "attemptId", System.nanoTime());
 
         // Should return empty result since tombstone blocks the pull
         assertEquals(0, result.getObject2().getMessageCount());
         // popLiteTopic should never be called for the tombstoned lmqName
         verify(popLiteMessageProcessor, never())
-            .popLiteTopic(anyString(), anyString(), anyString(), anyString(), 
anyLong(), anyLong(), anyLong(), anyString(), anySet());
+            .popLiteTopic(anyString(), anyString(), anyString(), anyString(), 
anyLong(), anyLong(), anyLong(), anyString(), anySet(), anyString(), anyLong());
     }
 
     @SuppressWarnings("unchecked")
@@ -599,13 +599,13 @@ public class PopLiteMessageProcessorTest {
         
when(liteEventDispatcher.getEventIterator(clientId)).thenReturn(mockIterator);
         doReturn(new Pair<>(new StringBuilder("0"), mockResult))
             .when(popLiteMessageProcessor)
-            .popLiteTopic(anyString(), anyString(), anyString(), anyString(), 
anyLong(), anyLong(), anyLong(), anyString(), anySet());
+            .popLiteTopic(anyString(), anyString(), anyString(), anyString(), 
anyLong(), anyLong(), anyLong(), anyString(), anySet(), anyString(), anyLong());
 
         Pair<StringBuilder, GetMessageResult> result = 
popLiteMessageProcessor.popByClientId(
-            "clientHost", "parentTopic", group, clientId, pollTime, 6000L, 32, 
"attemptId");
+            "clientHost", "parentTopic", group, clientId, pollTime, 6000L, 32, 
"attemptId", System.nanoTime());
 
         // Should return the message since no tombstone blocks
         assertEquals(msgCount, result.getObject2().getMessageCount());
-        verify(popLiteMessageProcessor).popLiteTopic(eq("parentTopic"), 
eq("clientHost"), eq(group), eq(lmqName), eq(32L), eq(pollTime), eq(6000L), 
eq("attemptId"), anySet());
+        verify(popLiteMessageProcessor).popLiteTopic(eq("parentTopic"), 
eq("clientHost"), eq(group), eq(lmqName), eq(32L), eq(pollTime), eq(6000L), 
eq("attemptId"), anySet(), eq("clientId"), anyLong());
     }
 }
diff --git 
a/proxy/src/main/java/org/apache/rocketmq/proxy/service/message/LocalMessageService.java
 
b/proxy/src/main/java/org/apache/rocketmq/proxy/service/message/LocalMessageService.java
index a14b09665e..9001b628bf 100644
--- 
a/proxy/src/main/java/org/apache/rocketmq/proxy/service/message/LocalMessageService.java
+++ 
b/proxy/src/main/java/org/apache/rocketmq/proxy/service/message/LocalMessageService.java
@@ -26,6 +26,7 @@ import java.util.List;
 import java.util.Map;
 import java.util.Set;
 import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionException;
 import org.apache.commons.lang3.NotImplementedException;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.rocketmq.broker.BrokerController;
@@ -34,6 +35,7 @@ import org.apache.rocketmq.client.consumer.AckStatus;
 import org.apache.rocketmq.client.consumer.PopResult;
 import org.apache.rocketmq.client.consumer.PopStatus;
 import org.apache.rocketmq.client.consumer.PullResult;
+import org.apache.rocketmq.client.exception.MQBrokerException;
 import org.apache.rocketmq.client.producer.SendResult;
 import org.apache.rocketmq.client.producer.SendStatus;
 import org.apache.rocketmq.common.constant.LoggerName;
@@ -235,6 +237,9 @@ public class LocalMessageService implements MessageService {
                 case ResponseCode.PULL_NOT_FOUND:
                     popStatus = PopStatus.POLLING_NOT_FOUND;
                     break;
+                case ResponseCode.SYSTEM_BUSY:
+                    // keep the code as the cluster mode does, so the client 
backs off and retries
+                    throw new CompletionException(new 
MQBrokerException(r.getCode(), r.getRemark()));
                 default:
                     throw new 
ProxyException(ProxyExceptionCode.INTERNAL_SERVER_ERROR, r.getRemark());
             }
diff --git 
a/proxy/src/test/java/org/apache/rocketmq/proxy/service/message/LocalMessageServiceTest.java
 
b/proxy/src/test/java/org/apache/rocketmq/proxy/service/message/LocalMessageServiceTest.java
index a0fe3b9c98..434d8b83e0 100644
--- 
a/proxy/src/test/java/org/apache/rocketmq/proxy/service/message/LocalMessageServiceTest.java
+++ 
b/proxy/src/test/java/org/apache/rocketmq/proxy/service/message/LocalMessageServiceTest.java
@@ -17,6 +17,7 @@
 
 package org.apache.rocketmq.proxy.service.message;
 
+import apache.rocketmq.v2.Code;
 import io.netty.channel.Channel;
 import java.net.InetSocketAddress;
 import java.nio.ByteBuffer;
@@ -41,6 +42,7 @@ import org.apache.rocketmq.client.consumer.AckResult;
 import org.apache.rocketmq.client.consumer.AckStatus;
 import org.apache.rocketmq.client.consumer.PopResult;
 import org.apache.rocketmq.client.consumer.PopStatus;
+import org.apache.rocketmq.client.exception.MQBrokerException;
 import org.apache.rocketmq.client.producer.SendResult;
 import org.apache.rocketmq.client.producer.SendStatus;
 import org.apache.rocketmq.common.BrokerConfig;
@@ -58,6 +60,7 @@ import org.apache.rocketmq.proxy.common.ProxyException;
 import org.apache.rocketmq.proxy.common.ProxyExceptionCode;
 import org.apache.rocketmq.proxy.config.ConfigurationManager;
 import org.apache.rocketmq.proxy.config.InitConfigTest;
+import org.apache.rocketmq.proxy.grpc.v2.common.ResponseBuilder;
 import org.apache.rocketmq.proxy.service.channel.ChannelManager;
 import org.apache.rocketmq.proxy.service.channel.SimpleChannelHandlerContext;
 import org.apache.rocketmq.proxy.service.route.AddressableMessageQueue;
@@ -402,6 +405,15 @@ public class LocalMessageServiceTest extends 
InitConfigTest {
         assertThat(exception.getCause()).hasMessage("lite failure");
     }
 
+    @Test
+    public void testPopLiteMessageSystemBusy() throws Exception {
+        ExecutionException exception = catchThrowableOfType(() -> 
invokeLiteResponse(
+            RemotingCommand.createResponseCommand(ResponseCode.SYSTEM_BUSY, 
"busy")), ExecutionException.class);
+        assertThat(exception.getCause()).isInstanceOf(MQBrokerException.class);
+        assertThat(((MQBrokerException) 
exception.getCause()).getResponseCode()).isEqualTo(ResponseCode.SYSTEM_BUSY);
+        
assertThat(ResponseBuilder.getInstance().buildStatus(exception.getCause()).getCode()).isEqualTo(Code.TOO_MANY_REQUESTS);
+    }
+
     @Test
     public void testPopLiteMessageProcessorException() throws Exception {
         RemotingCommandException failure = new RemotingCommandException("lite 
failure");

Reply via email to