GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

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

@lhotari lhotari commented Dec 20, 2023 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Member

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.

All reactions
@lhotari lhotari added type/bug The PR fixed a bug or issue reported a bug ready-to-test labels Dec 20, 2023
@lhotari lhotari added this to the 3.2.0 milestone Dec 20, 2023
@lhotari
lhotari requested review from Technoboy- and rdhabalia December 20, 2023 13:53
@lhotari lhotari self-assigned this Dec 20, 2023
@lhotari
lhotari requested a review from codelipenghui December 20, 2023 13:54
@github-actions github-actions Bot added the doc-not-needed Your PR changes do not impact docs label Dec 20, 2023
@lhotari
lhotari requested a review from poorbarcode December 20, 2023 13:54
@lhotari
lhotari force-pushed the lh-fix-memory-leak-clearIncomingMessages branch from 8e27b6c to 756a8fb Compare December 20, 2023 14:17
@lhotari
lhotari requested a review from merlimat December 20, 2023 18:39
@codecov-commenter

codecov-commenter commented Dec 20, 2023 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown

Codecov Report

❌ 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.

Files with missing lines Patch % Lines
...va/org/apache/pulsar/client/impl/ConsumerImpl.java 78.94% 3 Missing and 1 partial ⚠️
...ache/pulsar/client/impl/ZeroQueueConsumerImpl.java 50.00% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@             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     
Flag Coverage Δ
inttests 24.19% <34.37%> (+0.02%) ⬆️
systests 24.79% <34.37%> (+0.03%) ⬆️
unittests 72.69% <84.37%> (-0.05%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
...a/org/apache/pulsar/client/impl/RawReaderImpl.java 83.65% <100.00%> (ø)
...va/org/apache/pulsar/client/impl/ConsumerBase.java 73.83% <100.00%> (-0.30%) ⬇️
...he/pulsar/client/impl/MultiTopicsConsumerImpl.java 77.87% <100.00%> (-0.71%) ⬇️
...ache/pulsar/client/impl/ZeroQueueConsumerImpl.java 66.25% <50.00%> (+0.81%) ⬆️
...va/org/apache/pulsar/client/impl/ConsumerImpl.java 78.00% <78.94%> (-0.02%) ⬇️

... 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.
All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@codelipenghui

codelipenghui commented Dec 21, 2023

Copy link
Copy Markdown
Contributor

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.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@lhotari

lhotari commented Dec 22, 2023

Copy link
Copy Markdown
Member Author

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.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@lhotari
lhotari marked this pull request as draft December 22, 2023 06:04
@Technoboy- Technoboy- modified the milestones: 3.2.0, 3.3.0 Dec 22, 2023
@lhotari

lhotari commented Dec 22, 2023 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Member Author

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.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@lhotari

lhotari commented Dec 22, 2023

Copy link
Copy Markdown
Member Author

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?

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@coderzc coderzc modified the milestones: 3.3.0, 3.4.0 May 8, 2024
@lhotari lhotari mentioned this pull request Jun 3, 2024
[Bug] Acknowledgements lost on bookies and brokers restart resulting in messages not being delivered #22709
Closed
2 of 3 tasks
@lhotari lhotari mentioned this pull request Aug 9, 2024
[Bug] Bundle unload can cause shared consumer receive duplicate messages #23056
Open
2 of 3 tasks
@lhotari lhotari modified the milestones: 4.0.0, 4.1.0 Oct 11, 2024
@lhotari lhotari added release/4.0.1 triage/lhotari/important lhotari's triaging label for important issues or PRs labels Oct 11, 2024
@lhotari lhotari added release/4.0.2 and removed release/4.0.1 labels Dec 6, 2024
@lhotari lhotari added the release/4.0.3 label Jan 6, 2025
@lhotari lhotari added the release/4.0.11 label Apr 27, 2026
@lhotari lhotari modified the milestones: 4.2.0, 4.3.0 Apr 27, 2026
@lhotari lhotari added the release/4.2.2 label Apr 27, 2026
@lhotari lhotari added release/4.2.3 release/4.0.12 and removed release/4.2.2 release/4.0.11 labels Jun 8, 2026
@lhotari lhotari added release/4.2.4 release/4.0.13 and removed release/4.2.3 release/4.0.12 labels Jun 30, 2026
@lhotari lhotari added release/4.2.5 release/4.0.14 and removed release/4.2.4 release/4.0.13 labels Jul 27, 2026
@lhotari lhotari added release/4.0.15 release/4.2.6 and removed release/4.0.14 release/4.2.5 labels Oct 14, 2026
@lhotari
[fix][client] Fix message leaks and size accounting races when cleari…
f2fadb5
…ng the consumer's incoming queue

Assisted-by: Claude Code (claude-opus-5-5)
@lhotari
lhotari force-pushed the lh-fix-memory-leak-clearIncomingMessages branch from 7f4bd25 to f2fadb5 Compare October 20, 2026 09:07
@lhotari lhotari mentioned this pull request Oct 20, 2026
[improve][pip] PIP-491: Prevent Delivery Stalls by Making the Client Return Exactly the Permits Used by the Broker #26336
Open
3 of 12 tasks
Denovo1998
Denovo1998 approved these changes Oct 20, 2026
View reviewed changes

@Denovo1998 Denovo1998 left a comment

Copy link
Copy Markdown
Contributor

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.

All reactions
@lhotari lhotari mentioned this pull request Oct 20, 2026
[Bug][client] Multi-topic consumer with a message listener loses flow permits when redelivery clears its incoming queue #27016
Open
2 of 3 tasks
@lhotari

lhotari commented Oct 20, 2026

Copy link
Copy Markdown
Member Author

@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
All reactions
  • 👍 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

void-ptr974
void-ptr974 reviewed Oct 20, 2026
View reviewed changes

@void-ptr974 void-ptr974 left a comment •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Contributor

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.

All reactions
Comment thread pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerImpl.java Resolved

Uh oh!

There was an error while loading. Please reload this page.

@lhotari
Check and dequeue the head message atomically in batch receive
9715f99
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)
dao-jun
dao-jun approved these changes Oct 21, 2026
View reviewed changes

@dao-jun dao-jun left a comment

Copy link
Copy Markdown
Member

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.

All reactions
@merlimat merlimat mentioned this pull request Oct 23, 2026
[Bug][Java client] Possible race condition in consumer's clearIncomingMessages which causes a leak in memory limit controller and direct memory with pooled messages #18939
Closed
1 of 2 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

@dao-jun dao-jun dao-jun approved these changes
@Denovo1998 Denovo1998 Denovo1998 approved these changes
@rdhabalia rdhabalia Awaiting requested review from rdhabalia
@Technoboy- Technoboy- Awaiting requested review from Technoboy-
@codelipenghui codelipenghui Awaiting requested review from codelipenghui
@poorbarcode poorbarcode Awaiting requested review from poorbarcode
@merlimat merlimat Awaiting requested review from merlimat
@nodece nodece Awaiting requested review from nodece
+1 more reviewer
@void-ptr974 void-ptr974 void-ptr974 left review comments
Reviewers whose approvals may not affect merge requirements

Uh oh!

There was an error while loading. Please reload this page.

Assignees

@lhotari lhotari

Labels

cherry-picked/branch-4.0 cherry-picked/branch-4.2 cherry-picked/branch-5.0 doc-not-needed Your PR changes do not impact docs ready-to-test release/4.0.15 release/4.2.6 release/5.0.1 triage/lhotari/important lhotari's triaging label for important issues or PRs type/bug The PR fixed a bug or issue reported a bug

Projects

Apache Pulsar / Key_Shared and Acknowledgement reliability and usability improvements
Status: Done

Milestone

5.1.0

Development

Successfully merging this pull request may close these issues.

Uh oh!

There was an error while loading. Please reload this page.

8 participants

@lhotari @codecov-commenter @codelipenghui @dao-jun @Denovo1998 @void-ptr974 @Technoboy- @coderzc
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.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.