Repository navigation
[fix][client] Fix message leaks and size and permit accounting races when clearing the consumer's incoming queue - #21767
Conversation
8e27b6c to
756a8fb
Compare
Codecov Report❌ Patch coverage is 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.
🚀 New features to boost your workflow:
|
|
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 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: 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) 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. UPDATE 2: The test case was bad. I had forgotten DLQ config with max redeliveries 5 and that caused the problem. |
|
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 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? |
…ng the consumer's incoming queue Assisted-by: Claude Code (claude-opus-5-5)
7f4bd25 to
f2fadb5
Compare
Denovo1998
left a comment
There was a problem hiding this comment.
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.
|
@Denovo1998 Thanks for the review. I checked this and you're right. With a parent listener, |
There was a problem hiding this comment.
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.
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)
Motivation
ConsumerBase.clearIncomingMessages()clears the consumer's receiver queue withThis is only safe when nothing else touches the queue at the same time. For Shared and Key_Shared subscriptions,
incomingQueueLockis a no-op lock, soredeliverUnacknowledgedMessages()(called by the application, or for theinternal 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:
forEachandclear()is removed without being released (pooled buffer leak);forEachhas released it is handed to the application alreadyreleased;
message size and the client's memory limit usage (with
autoScaledReceiverQueueSizeEnabled) drift. When thesize that is reset is negative,
MemoryLimitController.releaseMemorythrowsIllegalArgumentExceptionout ofredeliverUnacknowledgedMessages(); the new concurrency test reproduces this against the old code;ConsumerImpl.redeliverUnacknowledgedMessages()gives backincomingMessages.size()permits, read before thequeue 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:
size()and the clear is discarded, but no permit is returned for it, so thepermit 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;
messageProcessed()and is alsocounted in
size(), so the broker gets an extra permit and can push more messages than the receiver queuesize.
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 Durablesubscriptions without releasing the drained messages, and also resets the size to 0;
ConsumerImplis closed, a message that arrives is released by the terminated queue, but its size and itsmemory limit reservation are never given back;
MultiTopicsConsumerImplnever drains its own queue on close or unsubscribe, and its expired message handlingdoesn't release the first non-expired message, which it removes from the queue to redeliver it;
ZeroQueueConsumerImplclears its queue withincomingMessages.clear()without releasing the messages, and itsblocking 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 withpoll()and returns how many itremoved. 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.
ConsumerBase.discardIncomingMessage(Message), which decreases the incoming message size and the memory limitusage 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'shandler for messages that arrive after close, and expired message removal in
ConsumerImplandMultiTopicsConsumerImpl.resetIncomingMessageSize().ConsumerImpl.redeliverUnacknowledgedMessages()gives back permits for the number of messages thatclearIncomingMessages()actually discarded. A message received concurrently gets its permit frommessageProcessed()only, and a message that arrives after the clear stays in the queue and gets its permit whenit is received.
MultiTopicsConsumerImplclears its queue when it closes or unsubscribes.ZeroQueueConsumerImplusesclearIncomingMessages(), releases the messages from an old connection that it dropsin a blocking receive, and decreases the incoming message size for each message it takes.
RawReaderImplis updated for the newintreturn type ofclearIncomingMessages().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()fromredeliverUnacknowledgedMessages(), which was wrong (the tracker holds messagesthat were already delivered to the application, and the redelivery covers them), so this version keeps it.
Verifying this change
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 mustbe released exactly once, the counts returned by
clearIncomingMessages()(which are the permits that redeliverygives 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()itfails, with
IllegalArgumentException: Try to reserve/release memory failed, the param memorySize is a negative value.ConsumerImplTest.testClearReceiverQueueDiscardsQueuedMessages(Durable and NonDurable): with the old code theDurable case doesn't release the messages.
ConsumerImplTest.testMessageEnqueuedAfterCloseIsDiscarded: with the old code the incoming message size stays atthe 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