You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pulsar.apache.org by "SongOf (via GitHub)" <gi...@apache.org> on 2026/09/11 17:40:10 UTC
[PR] [fix][client] Fix two producer buffer-ownership defects: oversized batches and non-persistent chunking [pulsar]
SongOf opened a new pull request, #26550:
URL: https://github.com/apache/pulsar/pull/26550
### Motivation
Two independent buffer-ownership defects on the producer send path. They are unrelated in cause, so they
are kept as separate commits, but both end in the same place: a pooled buffer released more often than it
was retained, which hands a live buffer back to the allocator.
**1. An oversized batch releases its payload twice.**
`BatchMessageContainerImpl` holds the batch payload in `batchedMessageMetadataAndPayload`. The ownership
rule is set by the success path: once the payload is handed to a `ByteBufPair`, that pair owns it, and
`clear()` only nulls the field instead of releasing it.
Both oversized branches of `createOpSendMsg` break that rule by letting two owners release the same buffer.
With compression and encryption off — the default — `getCompressedBatchMetadataAndPayload()` returns the
field itself and `encryptMessage` passes it straight through, so all three references are the same buffer:
```java
// single-message branch
if (op.getMessageHeaderAndPayloadSize() > getMaxMessageSize()) {
cmd.release(); // correct: the command owns the payload now
...
discard(...); // releases batchedMessageMetadataAndPayload — the same buffer, a second time
```
```java
// multi-message branch: no command exists yet, so the container still owns the payload
if (encryptedPayload.readableBytes() > getMaxMessageSize()) {
encryptedPayload.release();
...
discard(...); // releases it again
```
This is reached by the ordinary path: batching on (the default) and a message over the maximum message
size. If the buffer has already been handed out again by the pool, the second release frees memory that is
still in use.
The same file has a related dangling reference. `applyCompression` releases the buffer it is given and
returns a new one, but the field was never updated to follow it, so from that point on it pointed at freed
memory that `discard()` would release again and `resetPayloadAfterFailedPublishing()` would write into. The
non-client branch of `getCompressedBatchMetadataAndPayload(boolean)` has the same shape and is reached by
`RawBatchMessageContainerImpl`, which sets the compression type from the message being re-batched.
**2. Messages are "chunked" on non-persistent topics.**
Chunking has been guarded against non-persistent topics since it was introduced (PIP-37, #4400), but only
at the point where chunking is *performed*, not where it is *decided*:
```java
// how many chunks — no topic-type check
totalChunks = MathUtils.ceilDiv(Math.max(1, compressedPayload.readableBytes()), payloadChunkSize);
```
```java
// performing the chunking — guarded
if (totalChunks > 1 && TopicName.get(topic).isPersistent()) {
chunkPayload = compressedPayload.slice(readStartIndex, ...);
if (chunkId != totalChunks - 1) {
chunkPayload.retain();
}
msgMetadata.setChunkId(chunkId).setNumChunksFromMsg(totalChunks)...;
}
```
The send loop runs `totalChunks` times regardless. On a non-persistent topic the guarded block is skipped
while the loop still runs N times, so three things follow from that one skip:
- `chunkPayload` stays the *whole* payload, which is published N times;
- no chunk metadata is written, so the consumer cannot tell these are one message and delivers N duplicates
that deduplication cannot catch either;
- the compensating `retain()` lives inside the skipped block, so the payload is handed to N `ByteBufPair`s
while only one reference is held — N releases against a refcount of 1.
Nothing rejects the configuration: the builder only refuses chunking together with batching.
### Modifications
**Oversized batch release.** Give each buffer exactly one owner, and drop the stale reference whenever
ownership moves. The single-message branch keeps `cmd.release()` — the command does own the payload by then
— and nulls the field before `discard()` runs, mirroring what `clear()` does on the success path. The
multi-message branch releases `encryptedPayload` only when it really is a different buffer, which is the
case exactly when encryption produced one; otherwise `discard()` is the single owner. Both compression
branches now assign the new buffer back to the field.
**Chunking on non-persistent topics.** Move the topic-type check from where chunking is performed to where
it is decided, so the two agree: a non-persistent topic computes `totalChunks = 1` and takes the ordinary
single-message path. The check at the slicing site then becomes redundant and is reduced to `totalChunks >
1`, matching the sibling site in the same method that has always tested only the chunk count. The repeated
`TopicName.get(topic)` parse on the send path is replaced by a field computed once in the constructor.
Because the duplicate publishing and the refcount underflow are two symptoms of the same skipped block,
unifying the condition removes both; no separate accounting change is needed.
No wire format or API change. Applications sending large messages to a non-persistent topic with chunking
enabled now publish them once instead of N times; the message must still fit the maximum message size, as
it did before for every one of those N copies.
### Verifying this change
- [ ] Make sure that the change passes the CI checks.
This change added tests and can be verified as follows:
- *Added `BatchMessageContainerImplTest.testOversizedBatchReleasesItsPayloadExactlyOnce`: a recording
allocator hands out the batch buffer so the test can hold it without reflecting into private state; the
buffer is retained once to stand in for another holder, so an extra release is observable instead of
being swallowed by `ReferenceCountUtil.safeRelease`. It fails before the change with a reference count
of 0 where 1 is expected.*
- *Added `MessageChunkingTest.testLargeMessageOnNonPersistentTopicIsSentOnceWithoutChunking`: a payload
larger than `chunkMaxMessageSize` is sent to a non-persistent topic and must be delivered exactly once.
It fails before the change with "the payload was published more than once on a non-persistent topic".*
- *`BatchMessageContainerImplTest` (5), `MessageChunkingTest` (18) and `RawBatchMessageContainerImplTest`
(7) pass; the `pulsar-client` module suite shows no new failures and `./gradlew quickCheck` is clean.*
### Does this pull request potentially affect one of the following parts:
*If the box was checked, please highlight the changes*
- [ ] Dependencies (add or upgrade a dependency)
- [ ] The public API
- [ ] The schema
- [ ] The default values of configurations
- [ ] The threading model
- [ ] The binary protocol
- [ ] The REST endpoints
- [ ] The admin CLI options
- [ ] The metrics
- [ ] Anything that affects deployment
Chunking is now inert on non-persistent topics, where it never produced a message a consumer could
reassemble. The setting is still accepted.
--
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: commits-unsubscribe@pulsar.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [fix][client] Make chunking inert on non-persistent topics, including the message-size checks [pulsar]
Posted by "SongOf (via GitHub)" <gi...@apache.org>.
SongOf commented on code in PR #26550:
URL: https://github.com/apache/pulsar/pull/26550#discussion_r4064481073
##########
pulsar-client/src/main/java/org/apache/pulsar/client/impl/ProducerImpl.java:
##########
@@ -639,7 +642,9 @@ public void sendAsync(Message<?> message, SendCallback callback) {
// send in chunks
int totalChunks;
int payloadChunkSize;
- if (canAddToBatch(msg) || !conf.isChunkingEnabled()) {
+ // A non-persistent topic never chunks: the slicing below is skipped for it, so computing more than one
+ // chunk here would only make the send loop publish the whole payload once per chunk.
+ if (canAddToBatch(msg) || !conf.isChunkingEnabled() || !persistentTopic) {
Review Comment:
Fixed in 1ba0e84a97f. Both size checks were still gated on `conf.isChunkingEnabled()` alone, so on a non-persistent topic the chunk count was 1 while the checks still assumed the payload would be chunked.
There is now a single private `isChunkingEnabled()` on `ProducerImpl` that returns `conf.isChunkingEnabled() && persistentTopic`, and all three sites go through it: the chunk computation, the compressed-size check in `sendAsync()`, and `isMessageSizeExceeded()`.
Added `testLargeMessageOnNonPersistentTopicAboveBrokerLimitIsRejectedLocally`: a payload above the broker's `maxMessageSize` plus frame padding, sent to a non-persistent topic with chunking enabled, must fail locally with `InvalidMessageException`. Without the fix the test fails because the client does not reject the send. One detail differs from your repro: in the test harness the broker's frame decoder limit is fixed at startup, so the unfixed send completed instead of timing out, but the assertion is on the local rejection, so it discriminates either way.
##########
pulsar-client/src/main/java/org/apache/pulsar/client/impl/BatchMessageContainerImpl.java:
##########
@@ -209,6 +212,10 @@ protected ByteBuf getCompressedBatchMetadataAndPayload(boolean clientOperation)
} else {
compressedPayload = compressor.encode(batchedMessageMetadataAndPayload);
batchedMessageMetadataAndPayload.release();
+ // The codec returns a new buffer whenever it actually compresses, and the release above frees the
+ // old one, so the field has to follow it: otherwise it keeps pointing at freed memory that
+ // discard() would release again and resetPayloadAfterFailedPublishing() would write into.
+ batchedMessageMetadataAndPayload = compressedPayload;
Review Comment:
Confirmed on the branch as it was: after the field was transferred to the compressed buffer, the encryption-failure handler released it and `discard()` released it again.
After merging `master` this no longer applies. #26455 replaced the field-transfer approach with the `batchPayloadOwned` flag: compression clears the flag, `discard()` only releases the field when the flag is set, so the `compressedPayload.release()` in the failure handler is now the single release. #26455 also added `testToByteBufReleasesPayloadAndDiscardsWhenEncryptionFailsWithClientException` for exactly this path. This PR therefore no longer touches `BatchMessageContainerImpl` or `RawBatchMessageContainerImpl`; the diff against `master` is down to the chunking change in `ProducerImpl` plus tests. The PR title and description are updated accordingly.
##########
pulsar-client/src/test/java/org/apache/pulsar/client/impl/BatchMessageContainerImplTest.java:
##########
@@ -365,4 +368,94 @@ public void testKeyBasedContainerDropsTheTransactionIdentityOfAFailedFirstAdd()
}
}
+ /**
+ * With compression and encryption off — the default — {@code getCompressedBatchMetadataAndPayload()} returns
+ * the batch buffer itself and {@code encryptMessage} passes it straight through, so the buffer released in
+ * the oversized branch is the very one {@code discard()} releases again. A second release drops a live
+ * buffer to zero and returns it to the pool while it is still referenced.
+ */
+ @Test
+ public void testOversizedBatchReleasesItsPayloadExactlyOnce() throws Exception {
+ List<ByteBuf> allocated = new ArrayList<>();
+ ByteBufAllocator recordingAllocator = mock(ByteBufAllocator.class);
+ doAnswer(invocation -> {
+ ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer(invocation.getArgument(0));
+ allocated.add(buffer);
+ return buffer;
+ }).when(recordingAllocator).buffer(anyInt());
+
+ ProducerImpl<?> producer = createTestProducer();
+ // encryption disabled: the real implementation returns its input unchanged
+ when(producer.encryptMessage(any(), any())).thenAnswer(invocation -> invocation.getArgument(1));
+ ConnectionHandler connectionHandler = mock(ConnectionHandler.class);
+ when(connectionHandler.getMaxMessageSize()).thenReturn(1);
+ when(producer.getConnectionHandler()).thenReturn(connectionHandler);
+
+ BatchMessageContainerImpl container = new BatchMessageContainerImpl(recordingAllocator);
+ container.setProducer(producer);
+ container.add(newMessage(1L, null, null), null);
+ container.add(newMessage(2L, null, null), null);
+
+ assertEquals(allocated.size(), 1, "expected exactly one batch payload allocation");
+ ByteBuf payload = allocated.get(0);
+ // Stand in for anything else still holding the payload, so that an extra release is observable rather
+ // than being swallowed by ReferenceCountUtil.safeRelease.
+ payload.retain();
+
+ assertNull(container.createOpSendMsg(), "an oversized batch must not produce an op to send");
+
+ assertEquals(payload.refCnt(), 1, "the oversized batch payload was released more than once");
+ payload.release();
+ }
+
+ /**
+ * A successful encryption releases its input and returns a different buffer, so after it the container
+ * field points at freed memory unless it is transferred to the result. The identity check alone is not
+ * enough: it stops the encrypted output from being released twice, but {@code discard()} still releases the
+ * stale field.
+ */
+ @Test
+ public void testOversizedEncryptedBatchReleasesItsBuffersExactlyOnce() throws Exception {
+ List<ByteBuf> allocated = new ArrayList<>();
+ ByteBufAllocator recordingAllocator = mock(ByteBufAllocator.class);
+ doAnswer(invocation -> {
+ ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer(invocation.getArgument(0));
+ allocated.add(buffer);
+ return buffer;
+ }).when(recordingAllocator).buffer(anyInt());
+
+ ProducerImpl<?> producer = createTestProducer();
+ List<ByteBuf> encryptedBuffers = new ArrayList<>();
+ // Mirror a successful encryption: release the input and return a different buffer.
+ when(producer.encryptMessage(any(), any())).thenAnswer(invocation -> {
+ ByteBuf input = invocation.getArgument(1);
+ ByteBuf encrypted = ByteBufAllocator.DEFAULT.buffer(input.readableBytes());
+ encrypted.writeBytes(input.copy());
Review Comment:
Fixed in 1ba0e84a97f. The mock now uses `encrypted.writeBytes(input, input.readerIndex(), input.readableBytes())`, so there is no intermediate copy and the reader index is preserved. The retained-buffer cleanup in the oversized-batch tests is in a `finally` via `ReferenceCountUtil.safeRelease`, so a failed assertion no longer leaks the buffer.
--
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: commits-unsubscribe@pulsar.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [fix][client] Fix two producer buffer-ownership defects: oversized batches and non-persistent chunking [pulsar]
Posted by "SongOf (via GitHub)" <gi...@apache.org>.
SongOf commented on code in PR #26550:
URL: https://github.com/apache/pulsar/pull/26550#discussion_r3996077302
##########
pulsar-client/src/main/java/org/apache/pulsar/client/impl/BatchMessageContainerImpl.java:
##########
@@ -334,7 +345,11 @@ public OpSendMsg createOpSendMsg() throws IOException {
getCompressedBatchMetadataAndPayload());
updateAndReserveBatchAllocatedSize(encryptedPayload.capacity());
if (encryptedPayload.readableBytes() > getMaxMessageSize()) {
- encryptedPayload.release();
+ // With compression and encryption off this is the batch payload itself, which discard() releases
+ // below; releasing it here as well would drop a live buffer back into the pool.
+ if (encryptedPayload != batchedMessageMetadataAndPayload) {
+ encryptedPayload.release();
+ }
Review Comment:
Confirmed and fixed in 72bc03ecddd. You are right that the inequality branch only settled who releases the encrypted output, not the stale field: `encryptMessage` releases its input and returns a different buffer on success, so `batchedMessageMetadataAndPayload` pointed at freed memory that `discard()` released again.
The field now follows whatever encryption returns, at both call sites, exactly as it already does for compression — which is the line I should have extended one call further. That makes the inequality check redundant, so it is gone and the branch is simpler than before. All four exits of `encryptMessage` are covered: encryption disabled and the failure-with-SEND path return the input, so the assignment is a no-op; success transfers ownership to the new buffer; the failure-with-FAIL path throws before the assignment, leaving the field on the unreleased input for `resetPayloadAfterFailedPublishing`.
Added `testOversizedEncryptedBatchReleasesItsBuffersExactlyOnce`, which mocks encryption the way the real one behaves (release the input, return a new buffer). The load-bearing assertion is on the *pre-encryption* buffer, since the encrypted output was already released exactly once before this change. It fails without the fix with "the pre-encryption batch payload was released again after encryption had already released it".
`BatchMessageContainerImplTest` passes 6/6, the `pulsar-client` module suite (494 tests) shows no new failures, `RawBatchMessageContainerImplTest` (7) and `MessageChunkingTest` (18) pass, and `quickCheck` is clean.
--
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: commits-unsubscribe@pulsar.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [fix][client] Make chunking inert on non-persistent topics, including the message-size checks [pulsar]
Posted by "SongOf (via GitHub)" <gi...@apache.org>.
SongOf commented on code in PR #26550:
URL: https://github.com/apache/pulsar/pull/26550#discussion_r4280796129
##########
pulsar-client/src/test/java/org/apache/pulsar/client/impl/BatchMessageContainerImplTest.java:
##########
@@ -977,4 +977,149 @@ public void testKeyBasedContainerDropsTheTransactionIdentityOfAFailedFirstAdd()
}
}
+ /**
+ * Multi-message batch over the maximum message size, with compression and encryption off (the default): the
+ * batch buffer is still the one the container owns when the size check fails, so {@code discard()} is its
+ * only owner and the oversized branch must not release it as well. A second release would drop a live
+ * buffer to zero and return it to the pool while it is still referenced.
+ */
+ @Test
+ public void testOversizedBatchReleasesItsPayloadExactlyOnce() throws Exception {
+ List<ByteBuf> allocated = new ArrayList<>();
+ ByteBufAllocator recordingAllocator = mock(ByteBufAllocator.class);
+ doAnswer(invocation -> {
+ ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer(invocation.getArgument(0));
+ allocated.add(buffer);
+ return buffer;
+ }).when(recordingAllocator).buffer(anyInt());
+
+ ProducerImpl<?> producer = createTestProducer();
+ // encryption disabled: the real implementation returns its input unchanged
+ when(producer.encryptMessage(any(), any())).thenAnswer(invocation -> invocation.getArgument(1));
Review Comment:
Fixed in 3e043400c6a. All three overrides now use `doAnswer(...).when(producer).encryptMessage(any(), any())`. Comparing runs before and after, the leak reports for these three tests are gone. The remaining ones come from `testMessagesSize` and `testEntryBucketHashRangeIsStampedWhenCreatingSendOperation`, which leak on master as well. I also added `testNonPersistentMessageOverLimitOnlyWithMetadataIsRejectedLocally` in 20c180b6f79 for the final-size check. A body exactly at the limit plus a 400-byte property is rejected locally, and the next valid send is delivered. The test fails if `getMessageSizeError` goes back to `conf.isChunkingEnabled()`.
--
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: commits-unsubscribe@pulsar.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [fix][client] Make chunking inert on non-persistent topics, including the message-size checks [pulsar]
Posted by "codelipenghui (via GitHub)" <gi...@apache.org>.
codelipenghui merged PR #26550:
URL: https://github.com/apache/pulsar/pull/26550
--
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: commits-unsubscribe@pulsar.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [fix][client] Fix two producer buffer-ownership defects: oversized batches and non-persistent chunking [pulsar]
Posted by "lhotari (via GitHub)" <gi...@apache.org>.
lhotari commented on code in PR #26550:
URL: https://github.com/apache/pulsar/pull/26550#discussion_r3993261565
##########
pulsar-client/src/main/java/org/apache/pulsar/client/impl/BatchMessageContainerImpl.java:
##########
@@ -334,7 +345,11 @@ public OpSendMsg createOpSendMsg() throws IOException {
getCompressedBatchMetadataAndPayload());
updateAndReserveBatchAllocatedSize(encryptedPayload.capacity());
if (encryptedPayload.readableBytes() > getMaxMessageSize()) {
- encryptedPayload.release();
+ // With compression and encryption off this is the batch payload itself, which discard() releases
+ // below; releasing it here as well would drop a live buffer back into the pool.
+ if (encryptedPayload != batchedMessageMetadataAndPayload) {
+ encryptedPayload.release();
+ }
Review Comment:
**[BUG] Encrypted oversized batches still release the input buffer twice**
Could you also transfer the container field to the buffer returned by encryption and cover successful encryption in the regression test? With a multi-message batch whose encrypted payload exceeds the limit, `encryptMessage` has already released its input before returning a different buffer:
https://github.com/apache/pulsar/blob/8352e2968efa7fb943819f2ef9c0b360b23148c1/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ProducerImpl.java#L1012-L1014
The new inequality branch releases the encrypted output, but `discard()` still releases `batchedMessageMetadataAndPayload`, which points to that already-released input. This leaves the oversized-batch double release in place when encryption succeeds, both with and without compression. The current test mocks encryption as an identity operation, so it cannot exercise this 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: commits-unsubscribe@pulsar.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [fix][client] Make chunking inert on non-persistent topics, including the message-size checks [pulsar]
Posted by "lhotari (via GitHub)" <gi...@apache.org>.
lhotari commented on code in PR #26550:
URL: https://github.com/apache/pulsar/pull/26550#discussion_r4254864517
##########
pulsar-client/src/main/java/org/apache/pulsar/client/impl/BatchMessageContainerImpl.java:
##########
@@ -334,7 +345,11 @@ public OpSendMsg createOpSendMsg() throws IOException {
getCompressedBatchMetadataAndPayload());
updateAndReserveBatchAllocatedSize(encryptedPayload.capacity());
if (encryptedPayload.readableBytes() > getMaxMessageSize()) {
- encryptedPayload.release();
+ // With compression and encryption off this is the batch payload itself, which discard() releases
+ // below; releasing it here as well would drop a live buffer back into the pool.
+ if (encryptedPayload != batchedMessageMetadataAndPayload) {
+ encryptedPayload.release();
+ }
Review Comment:
Thanks for the fix and the test. After the merge of master, #26455 handles this case: [`BatchMessageContainerImpl.java:244-262`](https://github.com/apache/pulsar/blob/1eef14bb7c732152de76742728e605ed991cc151/pulsar-client/src/main/java/org/apache/pulsar/client/impl/BatchMessageContainerImpl.java#L244-L262) clears the ownership flag when encryption returns a new buffer, so the input is not released twice. I traced the oversized multi-message, single-message and compression-only paths and each buffer is released once. Keeping the encrypted-batch test is useful as a guard. Resolving this thread.
--
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: commits-unsubscribe@pulsar.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [fix][client] Make chunking inert on non-persistent topics, including the message-size checks [pulsar]
Posted by "codelipenghui (via GitHub)" <gi...@apache.org>.
codelipenghui commented on code in PR #26550:
URL: https://github.com/apache/pulsar/pull/26550#discussion_r4273979329
##########
pulsar-client/src/test/java/org/apache/pulsar/client/impl/BatchMessageContainerImplTest.java:
##########
@@ -977,4 +977,149 @@ public void testKeyBasedContainerDropsTheTransactionIdentityOfAFailedFirstAdd()
}
}
+ /**
+ * Multi-message batch over the maximum message size, with compression and encryption off (the default): the
+ * batch buffer is still the one the container owns when the size check fails, so {@code discard()} is its
+ * only owner and the oversized branch must not release it as well. A second release would drop a live
+ * buffer to zero and return it to the pool while it is still referenced.
+ */
+ @Test
+ public void testOversizedBatchReleasesItsPayloadExactlyOnce() throws Exception {
+ List<ByteBuf> allocated = new ArrayList<>();
+ ByteBufAllocator recordingAllocator = mock(ByteBufAllocator.class);
+ doAnswer(invocation -> {
+ ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer(invocation.getArgument(0));
+ allocated.add(buffer);
+ return buffer;
+ }).when(recordingAllocator).buffer(anyInt());
+
+ ProducerImpl<?> producer = createTestProducer();
+ // encryption disabled: the real implementation returns its input unchanged
+ when(producer.encryptMessage(any(), any())).thenAnswer(invocation -> invocation.getArgument(1));
Review Comment:
**[P2] Replace the encryption stub without executing its allocating answer**
`createTestProducer()` already stubs `encryptMessage()` with an answer that allocates a `ByteBuf` (lines 245–246). Evaluating `when(producer.encryptMessage(...))` invokes that existing answer before installing the replacement, so its returned buffer is discarded without being released. The same problem occurs in the new overrides at lines 1042 and 1095.
I reproduced Netty leak traces at all three locations even though the test assertions passed. Please use `doAnswer(...).when(producer).encryptMessage(any(), any())` for all three overrides; this installs the replacement without executing the old answer.
--
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: commits-unsubscribe@pulsar.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [fix][client] Fix two producer buffer-ownership defects: oversized batches and non-persistent chunking [pulsar]
Posted by "Denovo1998 (via GitHub)" <gi...@apache.org>.
Denovo1998 commented on code in PR #26550:
URL: https://github.com/apache/pulsar/pull/26550#discussion_r4046945889
##########
pulsar-client/src/main/java/org/apache/pulsar/client/impl/BatchMessageContainerImpl.java:
##########
@@ -209,6 +212,10 @@ protected ByteBuf getCompressedBatchMetadataAndPayload(boolean clientOperation)
} else {
compressedPayload = compressor.encode(batchedMessageMetadataAndPayload);
batchedMessageMetadataAndPayload.release();
+ // The codec returns a new buffer whenever it actually compresses, and the release above frees the
+ // old one, so the field has to follow it: otherwise it keeps pointing at freed memory that
+ // discard() would release again and resetPayloadAfterFailedPublishing() would write into.
+ batchedMessageMetadataAndPayload = compressedPayload;
Review Comment:
Should we also update RawBatchMessageContainerImpl.encrypt() during this ownership transfer? After the assignment, the container field points to compressedPayload, but the encryption-failure handler still invokes compressedPayload.release() and then discard(e), resulting in discard() releasing the same buffer again.
I reproduced this by injecting a CryptoException and keeping the compressed input retained once—its refcount ends at 0 instead of 1. Leaving the input release to discard() resolves that case.
##########
pulsar-client/src/main/java/org/apache/pulsar/client/impl/ProducerImpl.java:
##########
@@ -639,7 +642,9 @@ public void sendAsync(Message<?> message, SendCallback callback) {
// send in chunks
int totalChunks;
int payloadChunkSize;
- if (canAddToBatch(msg) || !conf.isChunkingEnabled()) {
+ // A non-persistent topic never chunks: the slicing below is skipped for it, so computing more than one
+ // chunk here would only make the send loop publish the whole payload once per chunk.
+ if (canAddToBatch(msg) || !conf.isChunkingEnabled() || !persistentTopic) {
Review Comment:
Can we update both message-size checks to apply the same effective chunking condition? For a non-persistent topic, totalChunks is currently set to 1, but both the payload-size check in sendAsync() and isMessageSizeExceeded() still skip validation when conf.isChunkingEnabled() returns true.
I reproduced this issue with a 1 KiB broker limit and a 32 KiB payload: the broker repeatedly reports TooLongFrameException, and the send eventually fails with a TimeoutException instead of a locally caught InvalidMessageException. A consistent check for both chunkingEnabled and persistentTopic should address this. Additionally, could we add a test above the broker limit? The current 500-byte test only exceeds the chunk size threshold.
##########
pulsar-client/src/test/java/org/apache/pulsar/client/impl/BatchMessageContainerImplTest.java:
##########
@@ -365,4 +368,94 @@ public void testKeyBasedContainerDropsTheTransactionIdentityOfAFailedFirstAdd()
}
}
+ /**
+ * With compression and encryption off — the default — {@code getCompressedBatchMetadataAndPayload()} returns
+ * the batch buffer itself and {@code encryptMessage} passes it straight through, so the buffer released in
+ * the oversized branch is the very one {@code discard()} releases again. A second release drops a live
+ * buffer to zero and returns it to the pool while it is still referenced.
+ */
+ @Test
+ public void testOversizedBatchReleasesItsPayloadExactlyOnce() throws Exception {
+ List<ByteBuf> allocated = new ArrayList<>();
+ ByteBufAllocator recordingAllocator = mock(ByteBufAllocator.class);
+ doAnswer(invocation -> {
+ ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer(invocation.getArgument(0));
+ allocated.add(buffer);
+ return buffer;
+ }).when(recordingAllocator).buffer(anyInt());
+
+ ProducerImpl<?> producer = createTestProducer();
+ // encryption disabled: the real implementation returns its input unchanged
+ when(producer.encryptMessage(any(), any())).thenAnswer(invocation -> invocation.getArgument(1));
+ ConnectionHandler connectionHandler = mock(ConnectionHandler.class);
+ when(connectionHandler.getMaxMessageSize()).thenReturn(1);
+ when(producer.getConnectionHandler()).thenReturn(connectionHandler);
+
+ BatchMessageContainerImpl container = new BatchMessageContainerImpl(recordingAllocator);
+ container.setProducer(producer);
+ container.add(newMessage(1L, null, null), null);
+ container.add(newMessage(2L, null, null), null);
+
+ assertEquals(allocated.size(), 1, "expected exactly one batch payload allocation");
+ ByteBuf payload = allocated.get(0);
+ // Stand in for anything else still holding the payload, so that an extra release is observable rather
+ // than being swallowed by ReferenceCountUtil.safeRelease.
+ payload.retain();
+
+ assertNull(container.createOpSendMsg(), "an oversized batch must not produce an op to send");
+
+ assertEquals(payload.refCnt(), 1, "the oversized batch payload was released more than once");
+ payload.release();
+ }
+
+ /**
+ * A successful encryption releases its input and returns a different buffer, so after it the container
+ * field points at freed memory unless it is transferred to the result. The identity check alone is not
+ * enough: it stops the encrypted output from being released twice, but {@code discard()} still releases the
+ * stale field.
+ */
+ @Test
+ public void testOversizedEncryptedBatchReleasesItsBuffersExactlyOnce() throws Exception {
+ List<ByteBuf> allocated = new ArrayList<>();
+ ByteBufAllocator recordingAllocator = mock(ByteBufAllocator.class);
+ doAnswer(invocation -> {
+ ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer(invocation.getArgument(0));
+ allocated.add(buffer);
+ return buffer;
+ }).when(recordingAllocator).buffer(anyInt());
+
+ ProducerImpl<?> producer = createTestProducer();
+ List<ByteBuf> encryptedBuffers = new ArrayList<>();
+ // Mirror a successful encryption: release the input and return a different buffer.
+ when(producer.encryptMessage(any(), any())).thenAnswer(invocation -> {
+ ByteBuf input = invocation.getArgument(1);
+ ByteBuf encrypted = ByteBufAllocator.DEFAULT.buffer(input.readableBytes());
+ encrypted.writeBytes(input.copy());
Review Comment:
Allocating a reference-counted buffer with `input.copy()` introduces a leak, as `writeBytes()` does not release it. This temporary copy is leaked even on a successful test.
Consider using `encrypted.writeBytes(input, input.readerIndex(), input.readableBytes())` instead. This avoids the extra allocation and preserves the reader index. Additionally, enclosing the retained-buffer cleanup in a `finally` block would prevent leaks from failed assertions.
--
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: commits-unsubscribe@pulsar.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org