GeezerVison is showing github.com — [fix][client] Fix message leaks and size and permit accounting races when clearing the consumer's incoming queue by lhotari · Pull Request #21767 · apache/pulsar
Conversation
lhotari
commented
Dec 20, 2023
•
edited
Loading
Uh oh!
There was an error while loading. Please reload this page.
Motivation
ConsumerBase.clearIncomingMessages() clears the consumer's receiver queue with
incomingMessages.forEach(Message::release);
incomingMessages.clear();
resetIncomingMessageSize(); // getAndSet(0) + release that amount from the MemoryLimitController
This is only safe when nothing else touches the queue at the same time. For Shared and Key_Shared subscriptions,
incomingQueueLock is a no-op lock, so redeliverUnacknowledgedMessages() (called by the application, or for the
internal consumers of a multi-topics consumer) runs this while the IO thread enqueues new messages. Receiving
doesn't take that lock for any subscription type, so this also runs while the application receives messages, and
the same applies to the clear that runs after a successful seek:
- a message enqueued between
forEach and clear() is removed without being released (pooled buffer leak);
- a message that the application receives after
forEach has released it is handed to the application already
released;
- resetting the incoming message size to 0 races with the per-message increments and decrements, so the incoming
message size and the client's memory limit usage (with autoScaledReceiverQueueSizeEnabled) drift. When the
size that is reset is negative, MemoryLimitController.releaseMemory throws IllegalArgumentException out of
redeliverUnacknowledgedMessages(); the new concurrency test reproduces this against the old code;
ConsumerImpl.redeliverUnacknowledgedMessages() gives back incomingMessages.size() permits, read before the
queue is cleared. The broker doesn't add permits back when it handles the redelivery, so this count is the only
correction for the messages the client discards, and it can be wrong in either direction:
- a message that arrives between
size() and the clear is discarded, but no permit is returned for it, so the
permit is lost for good. The client only sends a flow command once its available permits reach half of the
receiver queue size, so once more than half of the receiver queue size has been lost over many redeliveries,
that never happens and the consumer stalls;
- a message that the application receives in that window gets its permit from
messageProcessed() and is also
counted in size(), so the broker gets an extra permit and can push more messages than the receiver queue
size.
The same area has more places where a message is removed from the queue without being released or without its
size being given back:
ConsumerImpl.clearReceiverQueue() (on reconnection) returns early when a seek is in progress and for Durable
subscriptions without releasing the drained messages, and also resets the size to 0;
- after
ConsumerImpl is closed, a message that arrives is released by the terminated queue, but its size and its
memory limit reservation are never given back;
MultiTopicsConsumerImpl never drains its own queue on close or unsubscribe, and its expired message handling
doesn't release the first non-expired message, which it removes from the queue to redeliver it;
ZeroQueueConsumerImpl clears its queue with incomingMessages.clear() without releasing the messages, and its
blocking receive neither releases a message from an old connection that it drops nor decreases the incoming
message size for the messages it takes.
Modifications
ConsumerBase.clearIncomingMessages() removes messages one at a time with poll() and returns how many it
removed. Each message is removed by exactly one of the clear loop, a receiver or the terminated queue, so it is
released exactly once and its size is given back exactly once.
- Add
ConsumerBase.discardIncomingMessage(Message), which decreases the incoming message size and the memory limit
usage and releases the message. Use it everywhere a message leaves the queue without reaching the application:
clearIncomingMessages(), ConsumerImpl.clearReceiverQueue() (now in every branch), the terminated queue's
handler for messages that arrive after close, and expired message removal in ConsumerImpl and
MultiTopicsConsumerImpl.
- Remove
resetIncomingMessageSize().
ConsumerImpl.redeliverUnacknowledgedMessages() gives back permits for the number of messages that
clearIncomingMessages() actually discarded. A message received concurrently gets its permit from
messageProcessed() only, and a message that arrives after the clear stays in the queue and gets its permit when
it is received.
MultiTopicsConsumerImpl clears its queue when it closes or unsubscribes.
ZeroQueueConsumerImpl uses clearIncomingMessages(), releases the messages from an old connection that it drops
in a blocking receive, and decreases the incoming message size for each message it takes.
RawReaderImpl is updated for the new int return type of clearIncomingMessages(). clearIncomingMessages()
and resetIncomingMessageSize() are protected methods of internal implementation classes, not public API.
This PR started in 2023 as a draft. It has been rewritten on top of the current master. The draft also removed
unAckedMessageTracker.clear() from redeliverUnacknowledgedMessages(), which was wrong (the tracker holds messages
that were already delivered to the application, and the redelivery covers them), so this version keeps it.
Verifying this change
- Make sure that the change passes the CI checks.
This change added tests and can be verified as follows:
ConsumerImplTest.testClearIncomingMessagesConcurrentWithEnqueueAndReceive: a Shared consumer with a memory limit,
where one thread enqueues 20000 messages, one receives and one calls clearIncomingMessages(). Every message must
be released exactly once, the counts returned by clearIncomingMessages() (which are the permits that redelivery
gives back) and the received messages must add up to the number of messages, and the incoming message size and
the memory limit usage must end at 0. With the old clearIncomingMessages() it
fails, with IllegalArgumentException: Try to reserve/release memory failed, the param memorySize is a negative value.
ConsumerImplTest.testClearReceiverQueueDiscardsQueuedMessages (Durable and NonDurable): with the old code the
Durable case doesn't release the messages.
ConsumerImplTest.testMessageEnqueuedAfterCloseIsDiscarded: with the old code the incoming message size stays at
the size of the message.
MultiTopicsConsumerImplTest.testCloseDiscardsQueuedMessages: with the old code the queued message isn't released.
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
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
❌ Patch coverage is 84.37500% with 5 lines in your changes missing coverage. Please review.
✅ Project coverage is 73.40%. Comparing base (69a45a1) to head (7f4bd25).
⚠️ Report is 2449 commits behind head on master.
Additional details and impacted files

@@ Coverage Diff @@
## master #21767 +/- ##
============================================
- Coverage 73.43% 73.40% -0.03%
+ Complexity 32798 32772 -26
============================================
Files 1897 1897
Lines 140647 140646 -1
Branches 15489 15491 +2
============================================
- Hits 103290 103248 -42
- Misses 29283 29316 +33
- Partials 8074 8082 +8
Flags with carried forward coverage won't be shown. Click here to find out more.
... and 53 files with indirect coverage changes
🚀 New features to boost your workflow:
- ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
- 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
Hi @lhotari, is it possible to reproduce the issue? Or is it possible to inject some delay to reproduce the issue with a test? So that we can avoid regression and easily understand what problem is fixed.
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Hi @lhotari, is it possible to reproduce the issue? Or is it possible to inject some delay to reproduce the issue with a test? So that we can avoid regression and easily understand what problem is fixed.
@codelipenghui I'll try to do that. However, it's pretty clear from the code that there are multiple race conditions that this PR would address.
One of the races is caused by the NoOpLock used for shared subscription.
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
lhotari
commented
Dec 22, 2023
•
edited
Loading
Uh oh!
There was an error while loading. Please reload this page.
|
One issue that I was able to reproduce, I haven't yet checked whether this PR fixes the problem. The repro app might be about a different issue.
A very messy repro app that does nasty things: https://github.com/lhotari/pulsar-playground/blob/lh-PR21767-investigation/src/main/java/com/github/lhotari/pulsar/playground/TestScenarioIssueRedeliveries.java
repro:
git clone -b lh-PR21767-investigation https://github.com/lhotari/pulsar-playground
cd pulsar-playground
./gradlew shadowJar
# start Pulsar in docker in the background
docker run --rm --name pulsar-standalone -d -p 8080:8080 -p 6650:6650 apachepulsar/pulsar:3.1.1 /pulsar/bin/pulsar standalone -nss -nfw
# wait a few seconds for Pulsar to start
sleep 5
# run the test app using the shadow jar with all dependencies
java -cp build/libs/pulsar-playground-all.jar com.github.lhotari.pulsar.playground.TestScenarioIssueRedeliveries
# stop and remove Pulsar in docker
docker stop pulsar-standalone
All messages should be eventually received. In the test case, about 5 to 15 out of 10000 are usually lost.
The test app prints how many are remaining (lost)
[main] INFO com.github.lhotari.pulsar.playground.TestScenarioIssueRedeliveries - Done receiving. Remaining: 10 duplicates: 8704 reconsumed: 985
[main] ERROR com.github.lhotari.pulsar.playground.TestScenarioIssueRedeliveries - Not all messages received. Remaining: 10
UPDATE: This issue reproduces even with the changes in this PR, so it's not fixed by this PR 21767.
I made changes to the test app build so that a shadow jar can be built with the locally built snapshot version of the Pulsar client.
# build the local version of Pulsar with this command before building the shadow jar:
# mvn -Pcore-modules,-main -T 1C clean install -DskipTests -Dspotbugs.skip=true`
# then build the shadow jar, check the previous instructions how to build
PULSAR_VERSION=3.2.0-SNAPSHOT ./gradlew shadowJar
UPDATE 2: The test case was bad. I had forgotten DLQ config with max redeliveries 5 and that caused the problem.
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
UPDATE 3 about the repro app:
When I increase the number of messages to 1M, the processing gets stuck in a loop where it's only the redelivered messages that keep on rotating. That is expected in many ways when there's a frequent call to consumer.redeliverUnacknowledgedMessages(). Calling that method is causing issues. I wonder how many Pulsar applications in the wild contain this type of mistake?
Could we improve the documentation for redeliverUnacknowledgedMessages to reduce confusion? What is a valid use case to use this method? Is it really needed in the user level API?
Since failover/shared subscription types are essentially calling consumer.redeliverUnacknowledgedMessages() under the covers, it's possible that a Pulsar application gets into this vicious cycle where the number of failed messages is very high and very little progress, or in worst case no progress, will be made between the redelivery calls. There is the consumer epoch solution to help with the problem, but I could see how it doesn't help prevent the situation when there's a large amount of messages that are in redelivery and it keeps the loop between the client and the broker busy.
It seems that such a problem could be detected from the relivery counters in topic stats, but that's something that isn't visible in Grafana / Prometheus metrics directly, IIRC.
In most cases the situation would get resolved after a while, but only after burning a lot of CPU cycles and transferred bytes across the network. I wonder if there's a better way to deal with high error rates in Pulsar?
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
…ng the consumer's incoming queue
Assisted-by: Claude Code (claude-opus-5-5)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
LGTM. One thing I noticed is a possible permit leak in the multi-topic listener path: when redelivery clears messages from the parent queue, the child consumers haven’t returned those permits yet, and the messages never reach callMessageListener(), where the permits would normally be returned. This looks like a pre-existing issue that might be worth a separate follow-up.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
@Denovo1998 Thanks for the review. I checked this and you're right. With a parent listener, ConsumerImpl.messageProcessed() skips giving back the permit (parentConsumerHasListener), and only ConsumerBase.callMessageListener() gives it back. When MultiTopicsConsumerImpl.redeliverUnacknowledgedMessages() clears the parent queue, each child gives back permits only for its own queue, so the permits for messages that were already in the parent queue are lost until the child reconnects. The Shared/Key_Shared removeExpiredMessagesFromQueue() path has the same problem. The issue was there before this PR, and this PR doesn't change it, so I've opened #27016 to fix it separately.
|
Denovo1998 reacted with thumbs up emoji
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
void-ptr974
left a comment
•
edited
Loading
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks for centralizing size accounting and message release in discardIncomingMessage(), and for basing permit updates on the actual discarded count. This makes the intended accounting rules much easier to follow across the different queue-clearing paths.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
A batch receive peeked the head message, checked that it fit in the batch,
and then polled it. A concurrent clear of the incoming queue, such as on
reconnection, could dequeue and release the peeked message in between, and
reading the size of a released pooled message throws a
NullPointerException, which left the batch receive future incomplete. The
poll could also return a different message than the one that was checked.
Assisted-by: Claude Code (claude-opus-5-5)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
LGTM, thanks for your work
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Development
Successfully merging this pull request may close these issues.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
|