frotmo opened a new issue, #11572:
URL: https://github.com/apache/rocketmq/issues/11572

   ### Before Creating the Bug Report
   
   - [x] I found a bug, not just asking a question, which should be created in 
[GitHub Discussions](https://github.com/apache/rocketmq/discussions).
   
   - [x] I have searched the [GitHub 
Issues](https://github.com/apache/rocketmq/issues) and [GitHub 
Discussions](https://github.com/apache/rocketmq/discussions)  of this 
repository and believe that this is not a duplicate.
   
   - [x] I have confirmed that this bug belongs to the current repository, not 
other repositories of RocketMQ.
   
   
   ### Runtime platform environment
   
   OS: Ubuntu 24.04 on WSL2 (kernel 6.6.87.2-microsoft-standard-WSL2).
   The bug is platform-independent: it is a Java long-to-int narrowing issue in 
the tools module.
   
   ### RocketMQ version
   
   branch: develop
   version: 5.5.1
   Git commit id: 3a94083574a564421e98730371e526de492d22ec
   
   ### JDK Version
   
   Compiler/Runtime: OpenJDK 1.8.0_514.
   The bug is JDK-version-independent.
   
   ### Describe the Bug
   
   
   `mqadmin consumeMessage` can pass a negative `maxNums` to the pull client 
when the remaining message count in one queue exceeds `Integer.MAX_VALUE`.
    
   In 
`tools/src/main/java/org/apache/rocketmq/tools/command/message/ConsumeMessageCommand.java`,
 `pullMessageByQueue` computes:
    
   ```java
   pullResult = defaultMQPullConsumer.pull(mq, "*", offset, (int) (maxOffset - 
offset + 1));
   ```
    
   `offset` and `maxOffset` are long queue offsets. `maxOffset - offset + 1` is 
a long, and the cast silently wraps when the remaining count is greater than 
`Integer.MAX_VALUE`:
    
   - `2_147_483_648` -> `-2_147_483_648`
   - `3_000_000_001` -> `-1_294_967_295`
   - `4_294_967_296` -> `0`
    
   `messageCount` is a `long` instance field with default `128`, parsed from 
the `-c/--MessageNumber` option. The only validation is `messageCount > 0`, so 
a user can pass a very large `-c`.
    
   When the cast yields a value <= 0, `DefaultMQPullConsumerImpl.pullSyncImpl` 
throws `MQClientException("maxNums <= 0")` before sending anything to the 
broker. `pullMessageByQueue` catches the exception, prints the stack trace, and 
returns, so the current queue stops. In DEFAULT mode, other queues may still be 
processed, producing partial output.
    
   This is an edge case, not a data-loss issue: it requires a queue with at 
least `2^31` messages and `-c >= 2^31`. The default `-c=128` is safe. I 
understand this may be considered low priority.
    
   
   ### Steps to Reproduce
   
   #### A. Deterministic mock test (recommended)
    
   I added the following JUnit/Mockito test under 
`tools/src/test/java/org/apache/rocketmq/tools/command/message/` and ran it 
against commit `3a940835`:
    
   ```java
   package org.apache.rocketmq.tools.command.message;
    
   import java.lang.reflect.Field;
   import java.lang.reflect.Method;
   import java.util.Collections;
   import java.util.concurrent.atomic.AtomicInteger;
   import org.apache.rocketmq.client.consumer.DefaultMQPullConsumer;
   import org.apache.rocketmq.client.consumer.PullResult;
   import org.apache.rocketmq.client.consumer.PullStatus;
   import org.apache.rocketmq.common.message.MessageQueue;
   import org.junit.Assert;
   import org.junit.Test;
    
   import static org.mockito.ArgumentMatchers.anyInt;
   import static org.mockito.ArgumentMatchers.anyLong;
   import static org.mockito.ArgumentMatchers.eq;
   import static org.mockito.Mockito.mock;
   import static org.mockito.Mockito.when;
    
   public class ConsumeMessageCommandOverflowTest {
    
       @Test
       public void testPullMaxNumsOverflow() throws Exception {
           ConsumeMessageCommand command = new ConsumeMessageCommand();
           DefaultMQPullConsumer consumer = mock(DefaultMQPullConsumer.class);
           MessageQueue mq = new MessageQueue("test-topic", "broker-a", 0);
    
           
when(consumer.fetchSubscribeMessageQueues("test-topic")).thenReturn(Collections.singleton(mq));
           when(consumer.minOffset(mq)).thenReturn(0L);
           when(consumer.maxOffset(mq)).thenReturn(3_000_000_000L);
    
           setField(command, "defaultMQPullConsumer", consumer);
           setField(command, "topic", "test-topic");
           setField(command, "messageCount", 3_000_000_000L);
    
           AtomicInteger capturedMaxNums = new AtomicInteger();
           when(consumer.pull(eq(mq), eq("*"), anyLong(), 
anyInt())).thenAnswer(invocation -> {
               capturedMaxNums.set(invocation.getArgument(3));
               return new PullResult(PullStatus.NO_NEW_MSG, 3_000_000_000L, 0L,
                   3_000_000_000L, Collections.emptyList());
           });
    
           Method executeDefault = ConsumeMessageCommand.class
               .getDeclaredMethod("executeDefault", long.class, long.class);
           executeDefault.setAccessible(true);
           executeDefault.invoke(command, 0L, 0L);
    
           Assert.assertEquals(-1_294_967_295, capturedMaxNums.get());
       }
    
       private static void setField(Object target, String name, Object value) 
throws Exception {
           Field field = target.getClass().getDeclaredField(name);
           field.setAccessible(true);
           field.set(target, value);
       }
   }
   ```
    
   Run:
    
   ```bash
   mvn -pl tools -Dtest=ConsumeMessageCommandOverflowTest test
   ```
    
   Observed: the test passes and captures `maxNums = -1294967295` on the 
current develop. This test documents the current behavior; a regression test 
for the fix should assert that the pull batch size stays within a safe bound.
    
   #### B. Real cluster
    
   A real reproduction requires a single queue with at least `2^31` messages. 
As a rough estimate, at 1 KB per message this is about 2.1 TB of commitlog; at 
200 B per message it is about 430 GB.
    
   ```bash
   mqadmin consumeMessage \
     -n <namesrv-address> \
     -t BigTopic \
     -b broker-a \
     -i 0 \
     -c 3000000000
   ```
    
   Current behavior: the queue aborts with `MQClientException: maxNums <= 0`. 
Building such a queue is expensive, so the mock test is the practical 
reproduction.
    
   
   ### What Did You Expect to See?
   
   The command should never compute an invalid batch size. For example:
    
   - pull in bounded chunks (for example 32 messages per RPC, as 
`PrintMessageByQueueCommand` and `PrintMessageSubCommand` do), while still 
honoring the total `-c`;
   - or validate/cap `-c` and print a clear user-facing error instead of 
letting the cast wrap.
   
   ### What Did You See Instead?
   
   `(int) 3_000_000_001` becomes `-1294967295`; the pull client rejects it and 
the current queue stops with a stack trace.
    
   
   ### Additional Context
   
   - **Scope check**: I initially also suspected `maxOffset = minOffset + 
countLeft - 1` could overflow long. I checked the branch condition: to enter 
it, `countLeft < maxOffset - minOffset`, so `minOffset + countLeft - 1 < 
maxOffset <= Long.MAX_VALUE`. It is not a long overflow. I am not claiming it; 
the issue is only the int cast at line 220.
   - **Client guard**: negative/zero `maxNums` never reaches the broker; 
`DefaultMQPullConsumerImpl.pullSyncImpl` throws before sending. So the impact 
is CLI behavior (queue abort/partial output), not broker-side data corruption.
   - **History**: the command was introduced in 2018 (`b75af6b0c`, 
`[ROCKETMQ-353] Add sendMessageCommand and consumeMessageCommand`, #332) and 
the cast has been present since then. `#11415` (2026-10-15) fixed message-count 
accounting but did not touch this cast. `#11306`/`#11274` fixed similar 
long-to-int truncation in tools comparators, so there is precedent for this 
class of fix.
   - **Related items**: I found #11415 (count accounting), #11410 (option 
declaration mismatch), and #11202 (sorting overflow); none of them covers this 
cast.
   - **Possible fix directions**:
     1. Chunk the pull loop (for example 32 messages per RPC) and keep `-c` as 
the total count.
     2. Validate `-c` with an upper bound and a clear error message.
     3. At minimum, use `Math.min(remaining, Integer.MAX_VALUE)` before the 
cast, though a single huge pull is still undesirable.
   - I am happy to submit a small PR with the regression test if maintainers 
think it is worth fixing. Otherwise I am fine with closing this as a 
low-priority edge case.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to