rocketmq icon indicating copy to clipboard operation
rocketmq copied to clipboard

[Bug] Broker may persist remoting frames from independent connections in a message body

Open caojiaqiang opened this issue 3 months ago • 4 comments

Before Creating the Bug Report

  • [x] I found a bug, not just asking a question, which should be created in GitHub Discussions.
  • [x] I have searched the GitHub Issues and GitHub 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: Linux
  • Multiple independent producers and consumers connect directly to the Broker. There is no proxy or load balancer on this path.
  • serverPooledByteBufAllocatorEnable=true
  • The incident occurred during normal concurrent SEND_MESSAGE and long-poll PULL_MESSAGE traffic.

RocketMQ version

  • Branch: 4.9.8
  • Version: based on Apache RocketMQ 4.9.8
  • Netty: 4.1.65.Final

This has not yet been reproduced on an unmodified official RocketMQ release. We are also auditing distribution-specific changes.

JDK Version

  • Compiler/runtime: JDK 8

Describe the Bug

A rare Broker-side data corruption was observed. A persisted business message body starts with the expected JSON, but from byte offset 457 it contains multiple RocketMQ RemotingCommand frames, including request code 11 (PULL_MESSAGE), request code 38, and binary total-length/header-length prefixes.

The embedded requests contain metadata from unrelated consumers running in different processes on different hosts. The producer and those consumers only share the same Broker connection endpoint; they do not share a client process or sending path.

The CommitLog record was read directly and its BODYCRC was independently verified:

total message record size: 2310
body length: 2063
stored BODYCRC: 348336256 (0x14c33080)
CRC32 recalculated from the stored body: 348336256
BODYCRC_MATCH=true

Therefore, the unexpected bytes were already part of the message body when the Broker calculated BODYCRC. This excludes query-tool decoding and post-write disk corruption.

During the exact incident second, Broker remoting logs also show a burst of decoder errors across independent remote connections, mainly TooLongFrameException and JSON header parse failures. A sanitized consumer request found in one decoder failure matches the request metadata embedded in the persisted business body. A separate producer connection also shows a SEND_MESSAGE header interrupted by a binary frame prefix and the start of a PULL_MESSAGE header.

This suggests corruption in the Broker remoting receive/decode path, but the exact root cause is not yet proven. Possible areas include pooled ByteBuf ownership/lifetime, interaction with the codec DefaultEventExecutorGroup, or a distribution-specific modification.

Steps to Reproduce

There is no deterministic reproduction yet because the event is rare. The following steps reproduce the forensic verification of the observed record:

  1. Run a Broker with the pooled server allocator enabled and multiple independent clients concurrently sending messages and issuing long-poll pull requests.
  2. When a corrupted message is detected, resolve its physical CommitLog offset and read the message record directly from the mapped CommitLog file.
  3. Parse TOTALSIZE, BODYCRC, SYSFLAG, and BODYLEN, then extract exactly BODYLEN bytes from the record.
  4. Recalculate CRC32 over those body bytes and compare it with the stored BODYCRC.
  5. Search the extracted body for RocketMQ RemotingCommand headers and binary frame prefixes.
  6. Correlate the embedded request metadata with Broker decoder errors from other remote connections at the same timestamp.

For the observed 2063-byte body, foreign request markers occurred at these offsets:

code 11: 457, 859, 905, 1663, 1801
code 38: 1353

All production IP addresses, message IDs, topics, consumer groups, and raw logs are omitted from this public report.

What Did You Expect to See?

Each channel decoder should only observe bytes received from that channel. The body persisted for a SEND_MESSAGE request should match the producer's request body. A malformed frame on one connection should be rejected or close only that connection and must not affect another connection's request.

What Did You See Instead?

Remoting request bytes associated with independent consumer connections appeared inside another producer's persisted business message body. Because the body was still structurally acceptable to the decoded SEND_MESSAGE request, the Broker stored it with a matching BODYCRC instead of rejecting it.

Some mixed frames caused decoder exceptions and connection closures, while this body-only corruption passed decoding and was persisted silently.

Additional Context

The closest issues found were:

  • #8086 and #6784: gRPC clients connecting to classic Remoting ports, causing protocol mismatch.
  • #3292: a TLS and transferMsgByHeap=false issue on the client response path.

None of them reports frames from independent connections appearing in a persisted message body with a matching BODYCRC.

Relevant 4.9.8 code path:

  • NettyRemotingServer uses DefaultEventExecutorGroup for the pipeline and optionally configures PooledByteBufAllocator.DEFAULT.
  • Each channel receives a new NettyDecoder extending LengthFieldBasedFrameDecoder.
  • NettyDecoder calls RemotingCommand.decode(frame) and releases the extracted frame in finally.
  • RemotingCommand.decode(ByteBuf) copies the remaining body into a new byte[].

Questions for maintainers:

  1. Is there a known issue in this 4.9.8 pipeline that can cause receive-buffer data to be observed across independent channels?
  2. Was a related fix made in a later RocketMQ or Netty version?
  3. Are disabling the pooled server allocator, keeping decoding on the channel EventLoop, and enabling Netty leak detection appropriate diagnostic mitigations?

caojiaqiang avatar Aug 12 '26 03:08 caojiaqiang

Issue Evaluation

Category: bug | Status: Confirmed — Needs Investigation

Thank you for the exceptionally detailed report. The evidence you have gathered is compelling:

  • BODYCRC match confirms the corruption occurred before persistence (not a disk or read-tool issue)
  • Cross-connection frame embedding (PULL_MESSAGE frames inside a SEND_MESSAGE body) points to a problem in the Broker's Netty receive/decode pipeline
  • Temporal correlation with TooLongFrameException bursts across independent connections strengthens the decode-path hypothesis

Key areas to investigate in the codebase:

  1. RemotingDecoder / NettyDecoder — whether cumulator (ByteToMessageDecoder) can leak or share ByteBuf references across connections when serverPooledByteBufAllocatorEnable=true
  2. NettyRemotingServer channel pipeline — whether pooled direct buffers are correctly isolated per-channel under high concurrency with mixed SEND/PULL traffic
  3. Broker2Client response path — whether callback frames from internal broker-to-broker or broker-to-client paths can bleed into the user-data write path

Severity: High — silent data corruption in persisted messages is a data integrity issue. Reproducibility: Not yet reproduced on unmodified 4.9.8, which makes this harder to triage. The distribution-specific audit you mentioned is important.

This warrants a deep code review of the remoting layer, particularly the interaction between pooled ByteBuf allocators and the frame decoder under concurrent heterogeneous traffic.


Automated evaluation by RockteMQ-AI

RockteMQ-AI avatar Aug 12 '26 04:08 RockteMQ-AI

Additional production evidence for the incident is provided below. Production identifiers have been replaced with stable aliases while preserving the correlations relevant to the investigation.

Important correlation boundary:

  • The persisted corrupted message is AC1A...557A, with UNIQ_KEY=AC11...e110, born at 2026-08-10 01:54:35.168 from producer-host-A:47870.
  • The producer-side decoder exception shown later is from the same producer host but another TCP connection, producer-host-A:48252. It contains the adjacent request UNIQ_KEY=AC11...e109, born at 01:54:35.167, one millisecond earlier.
  • Therefore, the decoder exception is not claimed to be the target message itself. It shows that the Broker receive/decode stream for the same producer host was already interleaved with a PULL_MESSAGE frame immediately before the target message was persisted with a corrupted body.

1. Target message metadata

Command:

sh mqadmin queryMsgById \
  -n '<redacted-nameserver>' \
  -i 'AC1A...557A'

Output:

Topic:               business-topic-order-flags
Tags:                [null]
Keys:                [null]
Queue ID:            6
Queue Offset:        197168851
CommitLog Offset:    1463990167229818
Reconsume Times:     0
Born Timestamp:      2026-08-10 01:54:35,168
Store Timestamp:     2026-08-10 01:54:35,282
Born Host:           producer-host-A:47870
Store Host:          broker-host-A:10915
System Flag:         0
Properties:          {TRACE_ON=true, SHARDING_KEY=<redacted>, MSG_REGION=DefaultRegion, UNIQ_KEY=AC11...e110, CLUSTER=<redacted-cluster>}
Message Body Path:   /tmp/rocketmq/msgbodys/AC1A...557A

MessageTrack [consumerGroup=target-consumer-group-A, trackType=SUBSCRIBED_BUT_PULL, exceptionDesc=null]
MessageTrack [consumerGroup=target-consumer-group-B, trackType=UNKNOW_EXCEPTION, exceptionDesc=MQBrokerException: CODE: 206 DESC: consumer group not online]

2. Stored message body

The following is the body returned by the message query, with business identifiers and values redacted.

The � characters are the terminal representation of non-text/binary frame-prefix bytes. The body was also extracted directly from CommitLog as exactly 2063 bytes; its calculated CRC32 matches the stored BODYCRC as described in the issue body.

{"eventType":"UPDATE","executeTime":1786298074,"indicator":0,"lastIndicator":0,"schema":"business_schema","tableName":"business_table","inboundIndex":0,"subscribeType":"","rowData":[{"business_id":{"v":"<redacted>"},"flag_a":{"v":0},"flag_b":{"v":0},"flag_c":{"v":1},"flag_d":{"v":0��{"code":11,"extFields":{"queueId":"7","maxMsgNums":"32","sysFlag":"4","suspendTimeoutMillis":"20000","commitOffset":"0","topic":"consumer-topic-A","queueOffset":"0","subscription":"*","clientLogicIdc":"logic-idc-A","subVersion":"0","consumerGroup":"consumer-group-A"},"flag":0,"language":"JAVA","opaque":308838062,"version":190}��{"code":11,"extFields":{"queueId":"0",��{"code":11,"extFields":{"queueId":"0","maxMsgNums":"32","sysFlag":"4","suspendTimeoutMillis":"20000","commitOffset":"0","topic":"consumer-topic-B","queueOffset":"692","subscription":"*","clientLogicIdc":"logic-idc-A","subVersion":"0","consumerGroup":"consumer-group-B"},"flag":0,"language":"JAVA","opaque":265700666,"version":190}MsgNums":"32","sysFlag":"4","suspendTimeou��{"code":38,"extFields":{"consumerGroup":"consumer-group-C"},"flag":0,"language":"JAVA","opaque":358602024,"version":190}...��{"code":11,"extFields":{"queueId":"2","maxMsgNums":"32","sysFlag":"4","suspendTimeoutMillis":"20000","commitOffset":"0","topic":"consumer-topic-D"...��{"code":11,"extFields":{"queueId":"4","maxMsgNums":"32","sysFlag":"4","suspendTimeoutMillis":"20000","commitOffset":"0","topic":"consumer-topic-E","queueOffset":"0","subscription":"*","clientLogicIdc":"logic-idc-A","subVersion":"0","consumerGroup":"consumer-group-E"...

This body contains complete or partial PULL_MESSAGE (code=11) and GET_CONSUMER_LIST_BY_GROUP (code=38) request headers belonging to unrelated consumers.

3. Initial decoder-error burst at 01:54:30

Log analysis for the first incident second gives:


2026-08-10 01:54:30 ERROR NettyServerCodecThread_1 - decode exception, ip:45700
io.netty.handler.codec.TooLongFrameException: Adjusted frame length exceeds 16777216: 3886452713 - discarded
	at io.netty.handler.codec.LengthFieldBasedFrameDecoder.fail(LengthFieldBasedFrameDecoder.java:503)
	at io.netty.handler.codec.LengthFieldBasedFrameDecoder.failIfNecessary(LengthFieldBasedFrameDecoder.java:489)
	at io.netty.handler.codec.LengthFieldBasedFrameDecoder.exceededFrameLength(LengthFieldBasedFrameDecoder.java:376)
	at io.netty.handler.codec.LengthFieldBasedFrameDecoder.decode(LengthFieldBasedFrameDecoder.java:419)
	at org.apache.rocketmq.remoting.netty.NettyDecoder.decode(NettyDecoder.java:42)
	at io.netty.handler.codec.LengthFieldBasedFrameDecoder.decode(LengthFieldBasedFrameDecoder.java:332)
	at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:507)
	at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:446)
	at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:276)
	at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
	at io.netty.channel.AbstractChannelHandlerContext.access$600(AbstractChannelHandlerContext.java:61)
	at io.netty.channel.AbstractChannelHandlerContext$7.run(AbstractChannelHandlerContext.java:370)
	at io.netty.util.concurrent.DefaultEventExecutor.run(DefaultEventExecutor.java:66)
	at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989)
	at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
	at java.lang.Thread.run(Thread.java:745)
2026-08-10 01:54:30 ERROR NettyServerCodecThread_1 - decode exception, ip:54306
io.netty.handler.codec.TooLongFrameException: Adjusted frame length exceeds 16777216: 1981954598 - discarded
	at io.netty.handler.codec.LengthFieldBasedFrameDecoder.fail(LengthFieldBasedFrameDecoder.java:503)
	at io.netty.handler.codec.LengthFieldBasedFrameDecoder.failIfNecessary(LengthFieldBasedFrameDecoder.java:489)
	at io.netty.handler.codec.LengthFieldBasedFrameDecoder.exceededFrameLength(LengthFieldBasedFrameDecoder.java:376)
	at io.netty.handler.codec.LengthFieldBasedFrameDecoder.decode(LengthFieldBasedFrameDecoder.java:419)
	at org.apache.rocketmq.remoting.netty.NettyDecoder.decode(NettyDecoder.java:42)
	at io.netty.handler.codec.LengthFieldBasedFrameDecoder.decode(LengthFieldBasedFrameDecoder.java:332)
	at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:507)
	at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:446)
	at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:276)
	at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
	at io.netty.channel.AbstractChannelHandlerContext.access$600(AbstractChannelHandlerContext.java:61)
	at io.netty.channel.AbstractChannelHandlerContext$7.run(AbstractChannelHandlerContext.java:370)
	at io.netty.util.concurrent.DefaultEventExecutor.run(DefaultEventExecutor.java:66)
	at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989)
	at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
	at java.lang.Thread.run(Thread.java:745)
2026-08-10 01:54:30:
  decode exception count: 76
  distinct remote connections: 76
  TooLongFrameException count: 76

2026-08-10 01:54:30 through 01:54:35:
  decode exception count: 258

The first exception was:

2026-08-10 01:54:30 ERROR NettyServerCodecThread_1 - decode exception, consumer-host-A:45700
io.netty.handler.codec.TooLongFrameException: Adjusted frame length exceeds 16777216: 3886452713 - discarded
	at io.netty.handler.codec.LengthFieldBasedFrameDecoder.fail(LengthFieldBasedFrameDecoder.java:503)
	at io.netty.handler.codec.LengthFieldBasedFrameDecoder.failIfNecessary(LengthFieldBasedFrameDecoder.java:489)
	at io.netty.handler.codec.LengthFieldBasedFrameDecoder.exceededFrameLength(LengthFieldBasedFrameDecoder.java:376)
	at io.netty.handler.codec.LengthFieldBasedFrameDecoder.decode(LengthFieldBasedFrameDecoder.java:419)
	at org.apache.rocketmq.remoting.netty.NettyDecoder.decode(NettyDecoder.java:42)
	at io.netty.handler.codec.LengthFieldBasedFrameDecoder.decode(LengthFieldBasedFrameDecoder.java:332)
	at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:507)
	at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:446)
	at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:276)
	at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
	at io.netty.channel.AbstractChannelHandlerContext.access$600(AbstractChannelHandlerContext.java:61)
	at io.netty.channel.AbstractChannelHandlerContext$7.run(AbstractChannelHandlerContext.java:370)
	at io.netty.util.concurrent.DefaultEventExecutor.run(DefaultEventExecutor.java:66)
	at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989)
	at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
	at java.lang.Thread.run(Thread.java:745)

4. Producer-host decoder exception at 01:54:35

This is the key exception from producer-host-A. The JSON starts as a valid SEND_MESSAGE (code=10) header, then after unitMode=false it contains binary frame-prefix bytes followed by the beginning of a PULL_MESSAGE (code=11) header:

2026-08-10 01:54:35 ERROR NettyServerCodecThread_6 - decode exception, producer-host-A:48252
com.alibaba.fastjson.JSONException: illegal identifier : <NUL> pos 444, line 1, column 445
{"code":10,"language":"GO","version":317,"opaque":268771467,"flag":0,"remark":"","extFields":{"defaultTopic":"TBW102","defaultTopicQueueNums":"4","bornTimestamp":"1786298075167","flag":"0","reconsumeTimes":"0","batch":"false","properties":"SHARDING_KEY\u0001<redacted>\u0002UNIQ_KEY\u0001AC11...e109\u0002","producerGroup":"producer-group-A","topic":"business-topic-base-info","queueId":"0","sysFlag":"0","unitMode":"false"<binary frame prefix>{"code":11,"extFie
	at com.alibaba.fastjson.parser.JSONLexerBase.scanSymbolUnQuoted(JSONLexerBase.java:831)
	at com.alibaba.fastjson.parser.deserializer.MapDeserializer.parseMap(MapDeserializer.java:145)
	at com.alibaba.fastjson.parser.deserializer.JavaBeanDeserializer.deserialze(JavaBeanDeserializer.java:866)
	at com.alibaba.fastjson.parser.DefaultJSONParser.parseObject(DefaultJSONParser.java:688)
	at com.alibaba.fastjson.JSON.parseObject(JSON.java:396)
	at org.apache.rocketmq.remoting.protocol.RemotingSerializable.fromJson(RemotingSerializable.java:46)
	at org.apache.rocketmq.remoting.protocol.RemotingCommand.headerDecode(RemotingCommand.java:190)
	at org.apache.rocketmq.remoting.protocol.RemotingCommand.decode(RemotingCommand.java:168)
	at org.apache.rocketmq.remoting.netty.NettyDecoder.decode(NettyDecoder.java:46)
	at io.netty.handler.codec.LengthFieldBasedFrameDecoder.decode(LengthFieldBasedFrameDecoder.java:332)
	at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:507)
	at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:446)
	at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:276)
	at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
	at io.netty.channel.AbstractChannelHandlerContext$7.run(AbstractChannelHandlerContext.java:370)
	at io.netty.util.concurrent.DefaultEventExecutor.run(DefaultEventExecutor.java:66)
	at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989)
	at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
	at java.lang.Thread.run(Thread.java:745)
2026-08-10 01:54:35 INFO NettyServerNIOSelector_4_1 - closeChannel: close the connection to remote address[producer-host-A:48252] result: true

5. Matching consumer request on another connection

The target body contains the request for aliased consumer-topic-B, queue 0, offset 692, and consumer-group-B. The same request appears in a decoder exception on a different remote connection during the same second:

2026-08-10 01:54:35 ERROR NettyServerCodecThread_5 - decode exception, consumer-host-B:40412
com.alibaba.fastjson.JSONException: illegal identifier : <NUL> pos 38, line 1, column 39
{"code":11,"extFields":{"queueId":"0",<binary frame prefix>{"code":11,"extFields":{"queueId":"0","maxMsgNums":"32","sysFlag":"4","suspendTimeoutMillis":"20000","commitOffset":"0","topic":"consumer-topic-B","queueOffset":"692","subscription":"*","clientLogicIdc":"logic-idc-A","subVersion":"0","consumerGroup":"consumer-group-B"},"flag":0,

This provides a concrete correlation between bytes persisted in the target business body and a malformed remoting stream observed on another TCP client connection at the same timestamp.

caojiaqiang avatar Aug 12 '26 04:08 caojiaqiang

Issue Evaluation

Category: bug | Status: Confirmed — Needs Deep Investigation

Thank you for the thorough forensic analysis. The evidence strongly suggests a real corruption issue in the Broker remoting receive/decode path:

  • BODYCRC match confirms corruption happened before write
  • Cross-connection frame embedding rules out disk corruption
  • Concurrent decoder errors on independent connections during the incident second

Assessment: This is a serious data integrity issue. The analysis points to a potential ByteBuf lifecycle / ownership problem in the Netty codec pipeline, possibly related to pooled buffer reuse when serverPooledByteBufAllocatorEnable=true.

Note: The issue is reported on branch 4.9.8 with Netty 4.1.65.Final. The current develop branch uses a newer Netty version, so the first step would be to verify whether the issue still exists on the latest codebase.

Recommended next steps:

  1. Verify reproducibility on the latest develop branch
  2. Audit the RemotingCommand.decode() path for ByteBuf ownership assumptions
  3. Check if the DefaultEventExecutorGroup in the codec pipeline could cause cross-thread buffer access
  4. Consider adding a defensive copy in the decode path if pooled buffers are shared across pipeline stages

This issue warrants maintainer attention. An automated investigation of the decode path on the current develop branch can be initiated if desired.


Automated evaluation by github-manager

RockteMQ-AI avatar Aug 12 '26 14:08 RockteMQ-AI

We ran a bounded follow-up against the official RocketMQ develop source at commit 9ea2ccdc2b41445aee5e177e14e501d606f5a1ed, with rocketmq-apis fixed at 3e60073c6dab3430feaec443824802e23ecda681.

The test used three isolated, non-production Broker runs:

  • C0: serverNettyWorkerGroupEnable=true, serverPooledByteBufAllocatorEnable=true
  • C1: worker group disabled, pooled allocator enabled
  • C2: worker group enabled, pooled allocator disabled

Each run accepted and read back 451 messages. Across the three runs, 1,353 / 1,353 sent message bodies matched the corresponding parsed CommitLog bodies by SHA-256, and the RocketMQ-style 31-bit BODYCRC values also matched 1,353 / 1,353. We did not observe any candidate body containing markers attributable to the independent pull connections used by the test.

So the bounded result is:

NOT_REPRODUCED_IN_THIS_BOUNDED_RUN

A few important limitations:

  • this was a short bounded run, not a long-duration stress test;
  • it used current official develop, not the historical customized 4.9.8 environment described in this issue;
  • raw on-disk CommitLog bytes were not independently preserved for a second disk-level forensic pass;
  • this result does not prove that the historical defect did not exist or that it has been fixed.

We are sharing this only as an additional data point for the issue.

BenRobinson-hub avatar Oct 10 '26 15:10 BenRobinson-hub