GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing github.com — [fix][broker] Debit only credited permits when removing a Shared consumer by FlorentinDUBOIS · Pull Request #26417 · apache/pulsar Conversation
|
|
@lhotari @merlimat @nodece — you are the most recent committers on |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
|
Didn't take a look yet. Just reminds me of #26289. Is it related? |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
|
It could be, yes |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
| public synchronized void removeConsumer(Consumer consumer) throws BrokerServiceException { | ||
| // decrement unack-message count for removed consumer | ||
| addUnAckedMessages(-consumer.getUnackedMessages()); | ||
| if (consumerSet.removeAll(consumer) == 1) { |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Please handle else logic, which should re-compute unacked message.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Thanks for the review! I did consider recomputing in the else branch and concluded the counter must not be touched there.
totalUnackedMessages is maintained in lockstep with the per-consumer counters: every mutation goes through Consumer#addAndGetUnAckedMsgs (Consumer.java:1298) or Consumer#clearUnAckedMsgs (Consumer.java:1314), each applying the same delta to the consumer's counter and to subscription.addUnAckedMessages(...). The one place the subscription counter moves without the consumer counter is the debit in removeConsumer, which settles the departing consumer exactly once, at unregistration.
The else branch fires only when consumerSet.removeAll(consumer) == 0. Since addConsumer always inserts into both collections and consumerSet is an ObjectHashSet (AbstractDispatcherMultipleConsumers.java:35), the #22270 mismatch can only be a leftover consumerList duplicate whose contribution the first removal already debited. Debiting again there is exactly the double-accounting on master this PR fixes, and a recompute would be a guaranteed no-op.
A recompute is also not safely expressible for this counter, unlike permits: every delta must flow through addUnAckedMessages, which forwards it to the broker-level aggregate (line 1242) and drives the blocked-dispatcher hysteresis, so the field cannot be set directly; and summing consumerList would count duplicates twice and re-add the departed consumer's stale, never-zeroed counter. Permits need recomputeTotalAvailablePermits() only because their lockstep is intentionally broken — internalConsumerFlow drops flow from unregistered consumers — while the unacked lockstep is fenced by the closed pendingAcks map.
I can add a short comment in the else branch documenting this invariant if you think it helps — happy to discuss further.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Thanks for this, and especially for the writeup in #26416 — it's the most careful treatment of this accounting path I've seen, and the observation that a negative aggregate no longer stalls dispatch on master is exactly right and is something the other reports missed.
To answer my own earlier question about #26289: yes, the permit half is the same defect. I spent some time comparing the two rather than guessing, and I want to share what I found, because the conclusion isn't "yours is a duplicate" — you've found something #26289 does not fix.
I ran each PR's test file against the other PR's production code locally.
Your tests against #26289's fix — the permit tests pass:
[PASS] testRemovingConsumerDoesNotDebitPermitsThatWereNeverCredited 5.6s
[PASS] testSubscriptionAvailablePermitsNeverNegativeUnderConsumerChurn 63.6s
[FAIL] testRemovingSameConsumerTwiceDebitsUnackedMessagesOnce
expected [0] but found [-10]
So your permit invariant — including the churn scenario — is already satisfied by #26289. The one failure is a different bug, which I'll come back to.
#26289's tests against your fix — every classic=true variant fails:
[FAIL] testFlowCommandRaceWithConsumerRemovalDoesNotLosePermits[2](true, Shared) expected: 10 but was: -990
[FAIL] testFlowCommandRaceWithConsumerRemovalDoesNotLosePermits[6](true, Key_Shared) expected: 10 but was: -990
[FAIL] testBlockedFlowCommandRaceWithConsumerRemovalDoesNotLosePermits[2](true) expected: 10 but was: -990
-990 is the unpatched arithmetic. git diff master <this branch> -- .../PersistentDispatcherMultipleConsumersClassic.java is empty — PersistentDispatcherMultipleConsumersClassic still has totalAvailablePermits -= consumer.getAvailablePermits() at :247. You note this is deliberate, and I understand the minimalism argument, but because recomputeTotalAvailablePermits() is private on a sibling class under AbstractPersistentDispatcherMultipleConsumers (each with its own totalAvailablePermits), the recompute can't reach it — closing the gap means a second hand-written copy. subscriptionSharedUseClassicPersistentImplementation is dynamic = true and is the documented PIP-379 rollback path, so it's live for exactly the churn-heavy operators who hit this.
| Dimension | #26289 | #26417 (this PR) |
|---|---|---|
| Invariant | Exact: totalAvailablePermits == Σ(messagePermits_i − pending_i); removal debits precisely what was credited |
Approximate: recomputed from survivors' raw getAvailablePermits() |
| Residual error | None — survivors are untouched by a removal | Positive over-credit: a survivor's in-flight Flow is counted once by the recompute and again when its deferred internalConsumerFlow reaches :349 |
| Dispatcher coverage | Modern and Classic, Shared and Key_Shared | Modern only |
| Backport shape (4.0/4.2) | Ports as a complete fix; Classic is identically defective on both branches | Needs a second recompute for Classic to reach parity |
| Un-acked messages fix | Absent | Present (modern dispatcher) |
| Removal-path cost | Two uncontended monitor enters per Flow | O(n) scan of consumerList under the dispatcher monitor — measured at parity with the CopyOnWriteArrayList.remove already in that block, so not a real cost |
| New surface | New field, leaf lock and three methods on Consumer |
No new state, no new lock |
On simplicity this PR genuinely wins, and I don't want to wave that away. But the residual is the thing I keep coming back to. The PR describes it as erased by the next removal — that's true, and it means the error can't accumulate. What it doesn't cover is the case where there is no next removal: a single scale-down to a stable consumer set leaves the over-credit in place for the dispatcher's lifetime. The javadoc at :298 says the recompute "debits exactly what was credited", and for survivors holding a queued Flow that isn't so. It's bounded and it degrades rather than wedges, but it's an approximation where #26289 keeps an exact identity.
Moving addUnAckedMessages(-consumer.getUnackedMessages()) inside the consumerSet.removeAll(consumer) == 1 guard is a real, independent second defect, and I'd like it merged. Master and #26289 both debit before the guard, so the #22270 defensive path subtracts the same unacked count a second time. Nothing resets it — clearComponentsAfterRemovedAllConsumers() resets permits but deliberately leaves this counter alone — so a negative value silently raises the effective maxUnackedMessagesOnSubscription for the life of the dispatcher, and since addUnAckedMessages also feeds the broker-wide counter, it isn't confined to one subscription.
Your reply to @nodece is correct on the merits: the else branch is reached only when the first removal already debited, so a second debit there is the bug, not the fix. Worth keeping a one-line comment in the else branch saying so — the next reader will ask the same question.
Two things if you carve this out into its own PR:
PersistentDispatcherMultipleConsumersClassic.java:232-234, which has the identical unguarded debit.testRemovingSameConsumerTwiceDebitsUnackedMessagesOnce verbatim — it's 2.2s and fails on master and on #26289, which is exactly what a regression test should do.I'd drop testSubscriptionAvailablePermitsNeverNegativeUnderConsumerChurn. I ran it on master, on #26289 and on this branch: green in all three, ~61s each. It costs about 16× your other two tests combined and buys no regression protection, while carrying the usual real-client integration flake surface. Its aggregate assertion is also one-sided (>= 0), so it's structurally blind to the over-credit direction.
-177300, and why the aggregate cannot explain the stallI don't think this PR fixes the incident in #26416, and I want to be explicit about why rather than let a merge quietly close it.
The issue opens with:
What happened. A
Sharedsubscription permanently stopped dispatching after a consumer-churn window (a cursor reset performed with consumers still attached, a 12→1 consumer scale-down, then an instance recycle mid-drain). The broker reportedavailablePermitsat -177300 whilemsgBacklogwas non-empty [...] Onlypulsar-admin topics unloadrecovered the subscription.
A negative aggregate cannot produce "permanently stopped dispatching" — and you already say so yourself, in observation 1 of the same issue:
Since #10417 (
3550f2e7c1),readMoreEntriestakesMath.max(totalAvailablePermits, firstAvailableConsumerPermits)(:366), so a negative aggregate alone no longer stalls dispatch on master.
I'm underlining it because it's the strongest argument that whichever permit PR lands, this issue should stay open. Spelling out what the aggregate actually does in the read loop:
int firstAvailableConsumerPermits = getFirstAvailableConsumerPermits(); int currentTotalAvailablePermits = Math.max(totalAvailablePermits, firstAvailableConsumerPermits); if (currentTotalAvailablePermits > 0 && firstAvailableConsumerPermits > 0) {
(PersistentDispatcherMultipleConsumers.java:365-367). When totalAvailablePermits is negative it simply loses the Math.max to firstAvailableConsumerPermits, so the loop keeps reading — each read is just sized by one consumer's window instead of the sum of all of them. That caps dispatch throughput; it cannot stop it. The gate that actually closes is firstAvailableConsumerPermits > 0 — the per-consumer counters, not the aggregate.
The reported figure points the same way. availablePermits exists only on ConsumerStatsImpl:65; there is no subscription-level availablePermits anywhere in the admin stats API. So -177300 cannot have been read from the dispatcher aggregate at all — it is a per-consumer counter.
One refinement to the per-consumer story, because I initially had it slightly wrong myself: a consumer balance going negative is normal and self-repairing. Dispatch works on indivisible entries, so getMaxEntriesInThisBatch ends with Math.max(maxEntriesInThisBatch, 1) (// pick at least one entry to dispatch, :921), and Consumer.java:434 then charges the whole batch — MESSAGE_PERMITS_UPDATER.addAndGet(this, ackedCount - totalMessages). A consumer holding one permit can receive a 100-message batch and land at -99. That is outstanding batch debt, and it is repaid in full the moment the client returns 100 permits.
It only becomes permanent when the client returns fewer permits than the broker charged. isConsumerAvailable requires consumer.getAvailablePermits() > 0 (:1130-1132), so once the accumulated shortfall exceeds anything the client will ever return, the dispatcher skips that consumer forever and only a topic unload rebuilds it. A repeated shortfall is exactly the shape of a number like -177300, and it matches every other detail you reported: healthy connection, non-empty backlog, clean unacked accounting, unload as the only recovery.
Which brings up one important detail missing from #26416: it doesn't say which Pulsar client implementation and version were involved in the incident. The issue is specific about the broker side (master @ 00a6badafc, OpenJDK 21) and mentions only that the consumers sat "behind a third-party client whose wire behaviour we ruled out first" — but if the wedge is a per-consumer permit shortfall, the client is the component that produces it, so its identity is the most load-bearing unknown in the report.
Two possibilities worth separating:
ack_set and num_messages_in_batch, and so returns fewer permits than the broker charged — the exact gap PIP-491 exists to close.P on the wire.Ruling out "the client is expressing a decrement" (which the protocol makes impossible) is not the same as ruling out "the client is under-returning", and the report only establishes the former. Could you add the client type and version? If it's one of the officially maintained clients, the under-return paths are enumerable and testable; if it's a third-party implementation, that shifts where the fix has to land, which matters for the scoping question below.
If you haven't seen it, PIP-491 (#26336) — by @void-ptr974, the same author as #26289 — is a design proposal for exactly this failure. Its premise is that the permit debit P for a CommandMessage is never stated on the wire; the client has to re-derive it from ack_set and num_messages_in_batch, and the equality of the broker's and the client's arithmetic is, in the PIP's words, "an implementation coincidence, not an explicit wire contract."
Its worked example is your incident's mechanism:
assume a Shared consumer grants 100 permits and the broker sends one native batch with
P = 100. If checksum verification fails before the client can parsenum_messages_in_batch, the current Java error path returns one permit. The broker consumer is left with one available permit instead of 100. Repeating the failure can exhaust its capacity and stall Shared dispatch.
The proposal has the broker finalize one P per command after pending-ack admission, carry it in a new CommandMessage.message_permits, and use that same value for the consumer debit, every dispatcher aggregate debit, and serialization — with the Java client treating P as a command-local budget that it must return in full. Its failure-mode table is a catalogue of the ways a client currently under-returns: checksum or metadata failure before B is readable, decompression failure, a partial batch parse returning D + K + 1, stale-epoch discard after an async handoff, credit crossing into a replacement consumer over a pooled ClientCnx, and post-selection admission rejection debiting for a command that is never sent.
Notably, the two workstreams are deliberately disjoint, and PIP-491 says so in Appendix B — it defers "asynchronous CommandFlow dispatcher updates racing with consumer removal" to #26288/#26289, and asks that implementations "account for merge order without combining its scope with this PIP's send-side command debt." So this PR, #26289 and PIP-491 are three pieces of one picture: the aggregate race (this PR / #26289) and the send-side debt (PIP-491), with the latter being the half that explains a permanent stall.
Two caveats before treating it as the answer to #26416:
pip/pip-491.md; the discussion and vote threads are still blank. Nothing lands from it in the near term.CommandFlow values — "a client that returns too little eventually stalls itself." #26416 says your consumers sit behind a third-party client. The new wire field would give that client everything it needs to return exactly P, but it would have to adopt it; the broker-side half alone will not rescue an under-returning third-party client.Given that, I'd suggest #26416 is better placed as a motivating incident on PIP-491 than as an issue either permit PR closes — and worth cross-linking to #24926 as well. Your in-tree probe and the accounting analysis are worth keeping visible regardless of which patch lands.
Concretely, I'd suggest closing this PR in favour of #26289, and opening a new PR for the consumerSet.removeAll(consumer) == 1 guard fix, since that's a separate fix.
The reasoning for each half:
addUnAckedMessages(-consumer.getUnackedMessages()) inside the consumerSet.removeAll(consumer) == 1 guard has nothing to do with the Flow-vs-removal race; it's a distinct double-debit of a different counter, it fails independently of the permit fix, and it deserves its own title, its own review and its own backport decision. Please include PersistentDispatcherMultipleConsumersClassic.java:232-234 and keep testRemovingSameConsumerTwiceDebitsUnackedMessagesOnce.I know closing a PR you've put real work into is not a satisfying outcome, so to be clear about what I think happened here: you and @void-ptr974 independently found the same defect within two weeks, and your analysis in #26416 is the better explanation of it even though #26289 is the better patch. The un-acked guard is yours alone, and I'd like it in the codebase.
One note for the new PR, since it will touch the same method: if #26289 merges first, the guard move lands cleanly on top, but the removal debit line must stay as #26289 wrote it — getAvailablePermitsForDispatcherRemoval(), not a recompute over raw getAvailablePermits(). A recompute layered on top would reinstate the over-credit with a green build: #26289's tests drain the broker executor before each removal, so no survivor holds a pending Flow and the two expressions return the same number in every one of its scenarios.
Whatever happens to this PR, could you update the issue with the Pulsar client type and version from the environment where the incident actually happened?
I'm asking because the in-tree reproduction and the incident are most likely not the same failure. testRemovingConsumerDoesNotDebitPermitsThatWereNeverCredited reproduces the aggregate accounting asymmetry — real, worth fixing, and fixed by #26289. But the incident was a subscription that permanently stopped dispatching, and by your own observation 1 the aggregate cannot do that. The churn test, which is the one that exercises real clients end to end, passes on master — so nothing in the issue currently reproduces the production wedge. The probe demonstrates a defect that was found while investigating the incident, not the incident itself.
That gap is exactly why the client matters. If the wedge is a per-consumer permit shortfall, the shortfall was produced by whatever client was attached, and right now the issue records the broker build in detail while the client is only "a third-party client." Without it, there's no way to tell whether this is a PIP-491-shaped under-return, a leak specific to that client, or something else again — and no way to know whether a fix in Pulsar would have prevented it at all.
The environment section already has the right shape for the broker side; if you can add the client implementation and version (and, if it's available, the topic's receiverQueueSize and whether batching was enabled on the producers), that would make the issue actionable independently of the accounting work.
Thanks again for the depth here — the analysis in #26416 stands on its own regardless of which patch lands.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
|
Examples of past client-side issues and fixes in pulsar-client-go:
|
Sorry, something went wrong.
There was an error while loading. Please reload this page.
|
Thanks you @lhotari for the review, the time you pass and the quality of your message and comments, it is really appreciated. I will do as you suggested and keep updated the issue as well. |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
|
Closing as agreed in the review above:
Thanks @lhotari for the cross-testing and the depth of the review — comparing both patches against each other's test suites is exactly what settled this. |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
Successfully merging this pull request may close these issues.
[Bug] Shared dispatcher leaks negative aggregate availablePermits on consumer removal: deferred flow credit is discarded while the full consumer counter is debited
There was an error while loading. Please reload this page.