You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pulsar.apache.org by "lhotari (via GitHub)" <gi...@apache.org> on 2026/08/24 17:59:58 UTC
[PR] [improve][pip] PIP-493: Key-ordered negative acknowledgement for Key_Shared subscriptions [pulsar]
lhotari opened a new pull request, #26418:
URL: https://github.com/apache/pulsar/pull/26418
### Motivation
I'd like to propose PIP-493, which makes negative acknowledgement
usable on Key_Shared subscriptions without breaking key ordering.
PIP-379 defined the Key_Shared ordering contract as an invariant, and
then carved negative acknowledgement out of it: messages scheduled for
redelivery by negativeAcknowledge "will get redelivered as soon as
possible", with "no ordering guarantee in these cases". PIP-493
replaces that carve-out with a guarantee.
The gap matters because negativeAcknowledge is the natural tool for
"try this again in a moment" after a transient downstream failure --
an HTTP 503, a database failover, a rate limit -- and on a Key_Shared
subscription it silently reorders the key. Later messages for that key
are already in the consumer's receiver queue and get processed while
the nacked one waits out its retry delay. The alternatives are worse:
a dead letter topic leaves a permanent gap in the key's sequence, and
blocking the consumer thread stalls every other key that consumer
handles. An application cannot fix this on its own, because only the
broker can stop dispatching messages for a key.
The design has two halves, because at the moment of the nack the
messages that must not reach the application are in two places.
On the broker, a new CommandNegativeAck is sent at nack time and marks
the message's sticky key hash "retrying". While a hash is retrying,
only the earliest negatively acknowledged position of that hash may be
dispatched -- that position is the retry itself -- and the rule is
applied at all three existing dispatch gates. The command carries no
delay: the retry timer, RedeliveryBackoff and the acknowledgement
grouping window all stay on the client exactly as they are today, so
the broker gains no scheduler and the nacked message stays inside the
existing unacknowledged-message accounting.
On the client, messages for the guarded key that are already inside
the consumer are returned to the broker rather than held, and their
redelivery count is not incremented because the application never saw
them. Holding them instead would leave them in that consumer's pending
acknowledgements, so a hash reassignment would make PIP-379 mark the
hash draining until they are acknowledged, while the client refuses to
hand them over until the nacked message is acknowledged -- a circular
wait broken only by an acknowledgement timeout, which is disabled by
default.
The client API additions are opt-in. OrderedNegativeAckMode lets an
application that depends on the guarantee fail fast against a broker
that does not advertise support, while the default preserves today's
silent fallback. Consumer#acquireForOrderedProcessing serves
applications that keep several messages in flight behind per-key
queues, so the library rather than the application decides whether a
queued message may still be processed. A client-side broad-failure
delivery pause answers the common case where the downstream is failing
for every key rather than for one, by stopping flow permits instead of
opening as many concurrent retry cycles as there are active keys.
Nothing is persisted, no metadata or serialized format changes, and
the protocol change is additive. Old clients are unaffected; new
clients against an old broker fall back to today's behaviour.
The full proposal can be found at: __PR_URL__
Rendered PIP document:
https://github.com/lhotari/pulsar/blob/lh-pip-493-keyshared-nack-ordering/pip/pip-493.md
I welcome your feedback and discussion on this proposal. Please share
your thoughts, concerns, or suggestions.
### Documentation
<!-- DO NOT REMOVE THIS SECTION. CHECK THE PROPER BOX ONLY. -->
- [x] `doc` <!-- Your PR contains doc changes. -->
- [ ] `doc-required` <!-- Your PR changes impact docs and you will update later -->
- [ ] `doc-not-needed` <!-- Your PR changes do not impact docs -->
- [ ] `doc-complete` <!-- Docs have been already added -->
--
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] [improve][pip] PIP-493: Key-ordered negative acknowledgement for Key_Shared subscriptions [pulsar]
Posted by "void-ptr974 (via GitHub)" <gi...@apache.org>.
void-ptr974 commented on code in PR #26418:
URL: https://github.com/apache/pulsar/pull/26418#discussion_r4177238232
##########
pip/pip-493.md:
##########
@@ -0,0 +1,2320 @@
+# PIP-493: Key-ordered negative acknowledgement for Key_Shared subscriptions
+
+# Background knowledge
+
+## Key_Shared subscriptions and the ordering contract
+
+A Key_Shared subscription allows multiple consumers to consume from one subscription in parallel while
+messages that share the same key are processed in order. The broker maps each message's *sticky key*
+(the ordering key, or the partition key when no ordering key is set — `Commands#resolveStickyKey`) to a
+16-bit *sticky key hash*, and maps hash ranges to consumers.
+
+[PIP-379](pip-379.md) (Pulsar 4.0) defined the ordering contract as an invariant:
+
+> In Key_Shared subscriptions, messages with the same key are delivered and allowed to be in an
+> unacknowledged state to only one consumer at a time.
+
+PIP-379 also documented an explicit carve-out, which is the subject of this proposal:
+
+> The Key_Shared subscription doesn't prevent using any methods in the consumer API. For example, the
+> application might call `negativeAcknowledge` or the `redeliverUnacknowledgedMessages` method. When
+> messages are scheduled for delivery due to these methods, they will get redelivered as soon as
+> possible. There's no ordering guarantee in these cases, however the guarantee of delivering a message
+> key to a single consumer at a time will continue to be preserved.
+
+## One key per entry
+
+The broker resolves the sticky key once per **entry**, from the entry-level `MessageMetadata` only:
+`Commands#resolveStickyKey` never descends into `SingleMessageMetadata`, and a batched entry is
+dispatched whole to a single consumer. The producer stamps that entry-level key from the *first* message
+added to the batch (`Commands#initBatchMessageMetadata`), so a producer that puts several distinct keys
+into one entry has all of them dispatched under the first message's key, and the Key_Shared contract does
+not hold for the keys that ride along.
+
+**Producers on a Key_Shared topic must therefore disable batching or use `BatcherBuilder.KEY_BASED`.**
+That is a condition of the existing contract rather than something this proposal introduces:
+[PIP-460](pip-460.md) states it outright, and [PIP-486](pip-486.md) describes it as the producer-consumer
+coupling it exists to remove. Nothing enforces it, and no javadoc on `BatcherBuilder`, `ProducerBuilder`
+or `KeySharedPolicy` states it, which is why it is named here rather than assumed: this proposal reasons
+throughout on the basis that **one entry carries one sticky key**, and a mixed-key entry is outside this
+guarantee exactly as it is outside today's.
+
+What that buys is used repeatedly below. The replay queue, `PendingAcksMap` and the redelivery count are
+all keyed by position, so the *entry* is the only granularity the broker has; under this precondition it
+is also key-precise, and no rule here has to reason about the individual messages inside an entry.
+
+## The Key_Shared dispatcher mechanics that this proposal builds on
+
+Four existing mechanisms matter, all in `PersistentStickyKeyDispatcherMultipleConsumers` and its base
+class:
+
+1. **The replay queue** (`MessageRedeliveryController`, field `redeliveryMessages`). Positions that must
+ be redelivered are held here. For ordered Key_Shared subscriptions the controller also indexes each
+ position's sticky key hash, and `containsStickyKeyHash(hash)` answers "is some message with this hash
+ waiting for redelivery?".
+2. **Three dispatch gates, not one.** A message can be withheld from a consumer at three independent
+ points, and any new blocking rule has to be applied at all three:
+ - `canDispatchEntry` — the per-entry check on a normal read;
+ - `ReplayPositionFilter` — the filter that selects positions from the replay queue before entries are
+ read from storage;
+ - `handleAddingPendingAck` — the send-time recheck reached through
+ `PendingAcksMap#addPendingAckIfAllowed`, which PIP-379 added specifically to close the race between
+ a consumer-set change and a send that is already in progress. Note that the shipped method tests
+ only the draining hash; the replay-index test that appears in the PIP-379 document was removed
+ during its implementation. PIP-493's retrying-hash test will therefore be the only ordering guard at
+ this gate, which is a further reason not to omit it.
+3. **Pending acknowledgements** (`PendingAcksMap`). For each dispatched-but-unacknowledged message the
+ broker keeps `(ledgerId, entryId) -> (remainingUnacked, stickyKeyHash)`. Full removals invoke a
+ `PendingAcksRemoveHandler` callback, which is how PIP-379 keeps `DrainingHashesTracker` in sync
+ without embedding that logic into `PendingAcksMap`. Partial acknowledgement of batch indexes goes
+ through `updateRemainingUnacked`, which mutates the packed value in place and does **not** invoke the
+ callback.
+4. **Draining hashes** (PIP-379). When hash ranges change, hashes with messages still pending at the
+ previous consumer are marked *draining* and withheld from the new consumer until the previous
+ consumer has acknowledged them. They are what the current dispatcher has in place of the *recently
+ joined consumers* read-position tracking that [PIP-282](pip-282.md) redefined and that only the
+ classic dispatcher still carries — which is one reason the classic dispatcher is a different ordering
+ regime and is out of scope here.
+
+## How negative acknowledgement works today
+
+`Consumer#negativeAcknowledge` is entirely a client-side facility. `NegativeAcksTracker` stores the
+message id together with a redelivery timestamp computed from `negativeAckRedeliveryDelay` or from the
+configured `RedeliveryBackoff`, and groups nacks by trimmed timestamp so that many of them travel in one
+command. A timer fires when the delay elapses, and only *then* does the client send
+`CommandRedeliverUnacknowledgedMessages`. Until that moment the broker knows nothing: the message
+remains in the consumer's `PendingAcksMap` and counts towards the unacknowledged-message limits, exactly
+as any other in-flight message.
+
+Two consequences follow, and both are visible in the code today:
+
+- For the whole retry delay the broker keeps dispatching later messages with the same key to the
+ consumer, because nothing has told it not to.
+- The sticky key hash is dropped on the redelivery path. `Consumer#redeliverUnacknowledgedMessages(List<
+ MessageIdData>)` builds a `List<Position>`, and `PersistentDispatcherMultipleConsumers#
+ redeliverUnacknowledgedMessages(Consumer, List<Position>)` calls the two-argument
+ `addMessageToReplay(ledgerId, entryId)`, which calls `redeliveryMessages.add(ledgerId, entryId)`
+ without a hash. The position is therefore not indexed by hash, `containsStickyKeyHash` will not report
+ it, and later messages with the same key are not withheld. The code carries a `TODO` acknowledging
+ this:
+
+ ```java
+ // TODO: We want to pass a sticky key hash as a third argument to guarantee the order of the messages
+ // on Key_Shared subscription, but it's difficult to get the sticky key here
+ ```
+
+ The hash is available where it is discarded: `PendingAcksMap#removeAndGetRemainingUnacked` already
+ reads it out of the packed value.
+
+# Motivation
+
+Key-ordered processing exists because processing events for one entity out of order corrupts state or
+triggers wrong actions. The most common reason a consumer cannot process a message *right now* is a
+transient failure of a downstream dependency: an HTTP 503, a database failover, a rate limit. The
+natural tool for "try this again in a moment" is `negativeAcknowledge`.
+
+On a Key_Shared subscription that tool is currently unusable when ordering matters:
+
+1. **Negative acknowledgement reorders the key.** Two keys are in flight, `A` and `B`, delivered
+ interleaved: `A1, B1, A2, B2, A3, B3`. The application nacks `A1`; `A2` and `A3` are already in the
+ consumer's receiver queue and are processed; `A1` is redelivered afterwards and processed last.
+ Ordering for key `A` is violated, silently. `B1, B2, B3` are unaffected and should be — the failure
+ had nothing to do with them, and a mechanism that stopped them would trade one problem for
+ another.
+2. **The alternatives are worse.** Routing the failed message to a dead letter topic leaves a permanent
+ gap in the key's sequence, and re-injecting it in the right place later is generally not possible.
+ Blocking the consumer thread until the downstream recovers stalls every other key handled by that
+ consumer.
+3. **Application-level workarounds do not have the tools to be safe.** An application can keep the
+ failed message and buffer later messages for the same key itself, but it cannot stop the broker from
+ dispatching more messages for that key. Under a sustained outage the buffer grows without bound and
+ the consumer's permits are consumed by messages it cannot process.
+
+Point 3 is why this cannot be solved in the client library alone: only the broker can stop dispatching
+messages for a key, and the current protocol has no way to tell it to.
+
+# Goals
+
+## In Scope
+
+- Preserve key ordering across negative acknowledgement on Key_Shared subscriptions with ordering
+ enabled, in both AUTO_SPLIT and STICKY mode: after a message is negatively acknowledged, no later
+ message with the same key reaches any application before that message has been acknowledged. (The
+ broker withholds by sticky key hash, so *newly dispatched* messages for keys colliding with the nacked
+ one are withheld as well. Colliding-key messages already inside the consumer are unaffected — see
+ [Two halves](#two-halves-because-the-messages-are-in-two-places).)
+- Keep the resource cost bounded for the whole duration of a downstream outage, on both sides, without
+ introducing any new unbounded or client-controlled broker state.
+- Leave the existing negative acknowledgement retry delay, `RedeliveryBackoff` and grouping behaviour
+ exactly as they are.
+- Pause delivery entirely, client-side, when the application is failing regardless of key, so that a
+ broad downstream failure is answered by stopping flow permits rather than by as many concurrent retry
+ cycles as there are active keys (see
+ [Client: broad-failure delivery pause](#client-broad-failure-delivery-pause)).
+- Keep the mechanism inert when it is not in use: no new state is held while no message is in a retry
+ cycle, and the work left on the idle path is constant-time and enumerated here — the per-add
+ `PendingAcksMap` callback that ordered Key_Shared installs in both modes, a single test against an
+ empty map at each of the three broker dispatch gates, and one `isEmpty()` check per delivered message
+ on the client. An AUTO_SPLIT subscription already pays that callback cost for draining hashes; for a
+ STICKY subscription it is new, and all of it is paid whether or not anything is ever negatively
+ acknowledged.
+- Make a stuck subscription diagnosable: how many hashes are withholding messages, and how many positions
+ the broker is tracking. Not which message is blocking each hash — the application that negatively
+ acknowledged a message still holds it, so the broker owes the operator magnitude and duration rather
+ than identity.
+- Degrade safely. Where the guarantee cannot apply, the behaviour falls back to today's, never to a
+ stall. The exception is the explicit opt-in `OrderedNegativeAckMode.REQUIRED`, which fails loudly
+ rather than degrading, because an application that asked for the property should learn from the client
+ that it is absent, not from its data. Ordered processing admission, the other explicit opt-in, fails
+ loudly only for client-side misconfiguration; it produces no failure of its own where the broker
+ capability is missing, and follows the mode instead — beside the default `BEST_EFFORT` that is the
+ typed per-message `ADMITTED_WITHOUT_GUARANTEE`, which is degradation the application is told about
+ rather than a stall or a silent reorder. See [Public API](#public-api).
+
+## Out of Scope
+
+- Ordering guarantees for `redeliverUnacknowledgedMessages()`, acknowledgement timeout redelivery, dead
+ letter topics and retry letter topics. These remain as documented by PIP-379.
+- Shared, Exclusive and Failover subscriptions. Their negative acknowledgement behaviour is unchanged,
+ and the Java client does not use the new command for them.
+- Key_Shared subscriptions created with `KeySharedPolicy#setAllowOutOfOrderDelivery(true)`; the classic
+ Key_Shared dispatcher (`subscriptionKeySharedUseClassicPersistentImplementation=true`); and
+ [PIP-486](pip-486.md) entry-bucket dispatch (`KeySharedMeta.entryBucketDispatch`), where the
+ dispatch unit is a producer-stamped entry bucket spanning many keys rather than a key hash.
+- Messages with neither an ordering key nor a partition key, and chunked messages. See
+ [General Notes](#general-notes) for why each is excluded and how each could be added later.
+- Non-persistent topics, which have no redelivery.
+- Clients other than the Java client. The protocol change is additive; other clients may adopt it later
+ by implementing the [client conformance requirements](#client-conformance-requirements).
+- Detecting, rejecting or reporting batch entries that mix several distinct keys. Such entries fall
+ outside the [one key per entry](#one-key-per-entry) precondition and outside this guarantee, exactly as
+ they fall outside today's.
+
+# High Level Design
+
+## The invariant
+
+PIP-493 replaces the negative acknowledgement carve-out in the PIP-379 contract with a guarantee:
+
+> **On a Key_Shared subscription with ordering enabled, when a message is negatively acknowledged, no
+> *later* message with the same key is delivered to any application until that message has been
+> acknowledged.**
+
+The word "later" is load-bearing: the negatively acknowledged message is itself a message with that key,
+and redelivering it is the whole point. "Later" means later in position order within the subscription.
+
+The wording for `redeliverUnacknowledgedMessages` is unchanged: that method still carries no ordering
+guarantee.
+
+## Two halves, because the messages are in two places
+
+At the moment of the nack, the messages that must not reach the application live in two places:
+
+- Messages the broker has **not yet dispatched**. Only the broker can withhold these, and it must,
+ because otherwise they accumulate somewhere for the whole outage.
+- Messages **already inside the consumer**. The broker cannot recall them — they are on the wire, in the
+ receiver queue, or already queued on a listener executor. Only the client can deal with these.
+
+So the design has two mechanisms:
+
+| | Broker: *retrying hashes* | Client: *keys awaiting retry* |
+|---|---|---|
+| Unit | sticky key hash | sticky key bytes |
+| Withheld | positions strictly later than that hash's earliest outstanding nacked position | positions strictly later than that key's earliest outstanding nacked position |
+| Effect | withholds dispatch to any consumer | **returns** the message to the broker instead of delivering it |
+| Set by | the nack command | `negativeAcknowledge(Message)` |
+| Cleared by | acknowledgement of the nacked message | acknowledgement of the nacked message, with self-healing fallbacks |
+
+**One rule, applied at three places.** The *Withheld* row is deliberately the same rule on both sides,
+and the admission rule of `acquireForOrderedProcessing` (see [Public API](#public-api)) is the third
+instance of it: a message is withheld exactly when an *earlier* position of the same key is still
+unresolved, and it
+is delivered when it is at or before that position. The three differ only in what each place can see —
+the broker evaluates it over the negatively acknowledged positions of a *hash*, because the key bytes are
+not in its hands at the gates; the client's guard evaluates it over the negatively acknowledged positions
+of a *key*; and admission evaluates it over every undisposed copy of a key, because the application may
+hold several. Stating it once here is worth doing, because the alternative shape — a predicate over the
+*set* of guarded keys — is wrong in the same way at all three: it refuses positions *earlier* than the
+negatively acknowledged one, which the invariant never asked for. On the broker that wedges permanently
+(see [Broker: retrying hashes](#broker-retrying-hashes)); in the client it disarms a live guard (see
+[Client: keys awaiting retry](#client-keys-awaiting-retry)); in the application it teaches exactly the
+reordering the feature exists to prevent (see [Alternatives](#alternatives)).
+
+**The two units differ deliberately, and the client's is the finer one.** When key `A` is nacked, a
+message already inside the consumer that belongs to key `C` — a distinct key whose hash collides with
+`A`'s — is *not* returned: it is delivered and processed normally. Only newly dispatched `C` messages are
+withheld, by the broker, once it has the command. So a nack costs a colliding key its future throughput
+for the duration of the outage, but never the work already in the consumer's hands.
+
+That is sound rather than merely convenient, and the reason is worth stating because it is not obvious.
+Consumer selection is a pure function of the hash, so `A` and `C` always resolve to the *same* consumer,
+whose receiver queue is FIFO. The set of `C` messages inside the client at the moment of the nack is
+therefore exactly what the broker had already dispatched — a position-ordered **prefix** of the
+outstanding `C` stream — and everything the broker *withholds* is strictly later in position order than
+the nacked position. Delivering the prefix while withholding the remainder preserves `C`'s order. Every
+broker-side gate is hash-coarse, i.e. a superset of the key-precise set, so the error direction is always
+over-withholding, never under-withholding.
+
+What is *not* true, and is the reason all three of those rules are position-ordered rather than phrased
+over a set of keys, is that everything arriving after the nack is later than it. An earlier position of
+the same hash — the same key, or a colliding one — can still be dispatched afterwards: when a consumer
+disconnects, its pending acknowledgements are re-added to the replay queue with their hashes and replayed
+*ahead* of the nacked position, in order, to whichever consumer now owns the hash; and the legacy
+hash-less replay path leaves earlier positions in the queue that no hash index withholds at all. The
+withholding rule dispatches such a position deliberately, and the client delivers it for the same reason.
+That is correct rather than an exception: the message is earlier than everything the guard is protecting,
+nothing the broker withholds stands in front of it, and returning it would only send it straight back —
+the broker does not withhold it, so it would arrive again, and a client that treated its own return as
+evidence would disarm a guard whose hash is still retrying. The messages the client returns are the
+later ones, and only those.
+
+This rests on the `returned` list being key-precise. Returning by hash instead would pull a colliding
+key's messages back out of the client's ordered stream and break the prefix property, which is why
+conformance rule 8 is written in terms of "that key". Returning at *entry* granularity — the only unit the
+replay queue has — stays key-precise, because [one entry carries one key](#one-key-per-entry).
+
+That precondition is load-bearing one step earlier as well: "consumer selection is a pure function of the
+hash" is, for a batched message, a function of its *entry's* key rather than its own.
+
+The client **returns** messages rather than holding them. This is the central decision, and it is what
+makes the design safe: a message held inside the client is still recorded in that consumer's
+`PendingAcksMap`, so the broker believes it is being processed. If the hash is then reassigned, PIP-379
+marks it draining until the previous consumer acknowledges those messages — while the client refuses to
+hand them to the application until the nacked message is acknowledged, which cannot happen until the
+draining hash releases. That is a circular wait that nothing but an acknowledgement timeout breaks.
+Returning the messages removes them from `PendingAcksMap` and dissolves the cycle. It also removes the
+need for any client-side buffer, its memory accounting, and its interaction with permits and the
+acknowledgement timeout tracker.
+
+Returning reuses existing, proven machinery on the parts that matter most:
+`ConsumerImpl#redeliverUnacknowledgedMessages(Set<MessageId>)` already takes messages out of
+`incomingMessages`, releases them, corrects the incoming-message size accounting and restores the
+permits, and it is the model the return path follows. What it does not already do is find them. It
+drains through `GrowableArrayBlockingQueue#pollIf`, which tests only the element at the head and returns
+null at the first non-match, so it reclaims a matching *prefix* of the receiver queue and nothing behind
+it. For the nacked key's own messages sitting at the head that is exactly right; collecting a key's
+messages scattered through the queue is new work, and a predicate sweep over the whole queue rather than
+its head is the part this design adds. The other new part is on the broker: it must not count a returned
+message as a redelivery, because the application never saw it — otherwise `RedeliveryBackoff` escalates
+and the dead letter topic eventually swallows messages nobody ever tried to process.
+
+## The nack becomes an immediate signal, and nothing else moves
+
+The one structural change is *when* the broker is told. A new `CommandNegativeAck` is sent at nack time
+and carries two lists: the negatively acknowledged messages, and the messages the consumer is returning
+unprocessed. It carries **no delay**. The retry delay, `RedeliveryBackoff`, the grouping window and the
+existing `CommandRedeliverUnacknowledgedMessages` that the timer eventually sends all stay exactly where
+they are today.
+
+That is deliberate. Moving the retry deadline to the broker so that one command could do everything was
+considered and rejected, for three reasons that only became visible once the consequences were followed
+through:
+
+- A broker-side deadline requires the broker to drop the message from `PendingAcksMap` at nack time, so
+ the message escapes `maxUnackedMessagesPerConsumer` / `maxUnackedMessagesPerSubscription` accounting
+ while occupying broker state for a client-chosen duration. That is a new denial-of-service lever.
+- `RedeliveryBackoff` produces a *different* delay per message, so a single per-command delay is not
+ expressive enough, and a per-message delay on the wire also has to specify how the grouping window and
+ network transit are subtracted from it.
+- It needs a scheduler, a clamp, saturating deadline arithmetic, and a defined lifecycle across consumer
+ disconnect, cursor reset and topic unload.
+
+Leaving the timer on the client removes all of that. The nacked message stays in `PendingAcksMap`
+exactly as it does today, so it stays inside the existing unacknowledged-message accounting, and the
+broker gains no timer at all.
+
+The `negative_acked` entries carry one further thing, and it costs no schema change. Batch index
+acknowledgement is enabled by default, so a batched entry can already be partly acknowledged when one of
+its messages is negatively acknowledged, and the broker needs the batch dimension to know when that entry
+is resolved. A `negative_acked` entry therefore populates the existing `MessageIdData.batch_index` — the
+index that was negatively acknowledged — and the existing `MessageIdData.ack_set` — the client's current
+bitmap of the indexes of that entry that are **still unacknowledged**. That is the polarity `ack_set`
+already has on the wire: every index of a batch starts with its bit set, acknowledging an index *clears*
+that bit, and an entry is fully acknowledged when the bitmap is empty. This document uses that wire
+encoding everywhere it names `ack_set`; where the prose is clearer talking about the acknowledged
+indexes it says so explicitly rather than switching silently. Both fields are already on `MessageIdData`,
+so this is new semantics on an existing message rather than a protobuf schema change. The `ack_set` is a
+diagnostic cross-check, which the broker may log on mismatch and otherwise ignores; it is never treated
+as an acknowledgement, and nothing on the nack path writes acknowledgement state. See
+[Broker: retrying hashes](#broker-retrying-hashes) for how the broker resolves an entry's indexes from
+its own state, and [Client conformance requirements](#client-conformance-requirements) for the
+acknowledgement flush that makes that state at least as new as the client's.
+
+## Lifecycle
+
+```mermaid
+sequenceDiagram
+ participant App as Application
+ participant Cn as Consumer (client)
+ participant B as Broker (Key_Shared dispatcher)
+
+ B->>Cn: deliver A1, B1, A2, B2, A3, B3 (keys A and B, interleaved)
+ Cn->>App: A1
+ App->>Cn: negativeAcknowledge(A1)
+ Note over Cn: key A awaits retry
+ Cn->>B: NegativeAck(negative_acked=[A1], returned=[A2, A3])
+ Note over B: hash(A) is retrying.<br/>A2, A3 into the replay queue,<br/>not counted as redeliveries
+ Cn->>App: B1, B2, B3
+ Note over App: key B is untouched:<br/>its messages are delivered<br/>and processed in order throughout
+ B--xCn: no further dispatch for hash(A) —<br/>including future messages of key C,<br/>a distinct key whose hash collides with A's
+ Note over Cn: retry delay elapses (unchanged client timer)
+ Cn->>B: RedeliverUnacknowledged([A1])
+ B->>Cn: deliver A1
+ Note over Cn: A1 is one of this consumer's own<br/>nacked messages, so it is delivered,<br/>not returned — but key A still awaits retry
+ Cn->>App: A1
+ App->>Cn: acknowledge(A1)
+ Note over Cn: key A no longer awaits retry
+ Cn->>B: Ack(A1)
+ Note over B: hash(A) no longer retrying
+ B->>Cn: deliver A2, A3, then A4, A5 ..., and key C again
+ Cn->>App: A2, A3, ...
+```
+
+If the application nacks `A1` again instead of acknowledging it, the hash simply stays retrying and the
+cycle repeats. Nothing accumulates while it does: the broker dispatches nothing for that key, so the
+only messages the client ever has to return are the ones that were already in flight when the first nack
+happened. Key `B` is unaffected throughout — that is the difference from a client-only solution — and key
+`C` pays only for the collision, in future dispatch and never in the work already in the consumer's
+hands.
+
+# Detailed Design
+
+## Design & Implementation Details
+
+### Broker: retrying hashes
+
+A hash is **retrying** while at least one negatively acknowledged message with that hash has not been
+acknowledged. A new per-dispatcher component in `PersistentStickyKeyDispatcherMultipleConsumers` tracks
+this, alongside `DrainingHashesTracker`:
+
+- **State**: `stickyKeyHash -> ordered set of negatively acknowledged positions`. The set normally holds
+ one position; it holds more only when an application has several messages for one key in flight and
+ nacks more than one.
+- **Blocking**: an entry whose hash is retrying is withheld if and only if its position is **strictly
+ later** than the earliest position in that hash's set. The earliest nacked position is dispatched —
+ that is the retry — and so is anything before it.
+
+ The rule is stated in terms of position order rather than set membership, and the difference matters.
+ Withholding everything except the earliest nacked position looks equivalent and is not: it also
+ withholds positions *earlier* than the nacked one, which the invariant never asked for, and that
+ wedges permanently. A consumer can hold an earlier unacknowledged position with the same hash — the
+ same key, or merely a colliding one — and when that consumer disconnects, its whole pending-ack map is
+ re-added to the replay queue *with* hashes. The replay filter then meets the earlier position first,
+ withholds it, and records the hash in its per-pass blocked set; the exempt position is short-circuited
+ by that set before the exemption is ever consulted, so it is never dispatched, never acknowledged, and
+ never releases the hash that is blocking the position in front of it. Ordering by position dissolves
+ this: the earlier position replays ahead of the nacked one, in order, and the hash still withholds
+ everything after it. It also preserves what the earliest-only formulation was introduced for — a
+ second negatively acknowledged position of the same key is later than the first, so it stays withheld
+ until the first resolves.
+
+ (This does not rescue chunked messages: every chunk after the first is later than the earliest, so the
+ chunk wedge described in [General Notes](#general-notes) stands and the exclusion remains.)
+
+ The rule is applied at **all three** dispatch gates listed in Background — `canDispatchEntry`,
+ `ReplayPositionFilter`, and the send-time `handleAddingPendingAck`. Omitting the third would leave exactly
+ the race PIP-379 introduced that recheck to close: a send already in progress when the nack arrives.
+
+ Two details of *how* it is applied are easy to get wrong and are part of the design. The test in
+ `canDispatchEntry` must run for **both** read types: the pre-existing `containsStickyKeyHash` test
+ beside it is gated on `ReadType.Normal`, and a retrying test gated the same way would be bypassed by
+ exactly the replay that carries the redelivered message and its successors. And `ReplayPositionFilter`
+ cannot obtain a position's hash from the replay queue's index, which returns nothing for the hash-less
+ inserts that the legacy path produces — which is precisely how a nacked message re-enters the replay
+ queue once its retry has been requested. The tracker must therefore hold a `position -> hash` lookup of
+ its own alongside `stickyKeyHash -> ordered set of positions`, so the filter can recognise the exempt
+ position rather than waving it through.
+
+ The third gate needs care, because its contract differs from the other two. `canDispatchEntry` and
+ `ReplayPositionFilter` are predicates whose callers re-queue the rejected entry;
+ `handleAddingPendingAck` must re-queue the entry itself, because its caller in `Consumer#sendMessages`
+ drops and releases it outright. Applying the retrying rule there as a plain predicate would silently
+ lose the message. The nacked position must be exempt at this gate too — otherwise the one message the
+ mechanism exists to deliver is the one that can never be sent.
Review Comment:
Requeueing an entry rejected by the send-time gate prevents message loss, but the accounting also needs to be finalized against the entries that were actually accepted.
For example, `A2` may pass the earlier gates and be included in the computed totals, then be rejected after the nack for `A1` arrives. The current send path can still use the original totals for consumer permits, unacknowledged counts, dispatcher permits, rate accounting, and output metrics, even though `A2` was not written and has no pending acknowledgement that can later restore those values.
It would help to state that all downstream accounting uses the finalized accepted entry, message, and byte counts, and to include the nack/send race in the implementation tests.
##########
pip/pip-493.md:
##########
@@ -0,0 +1,2320 @@
+# PIP-493: Key-ordered negative acknowledgement for Key_Shared subscriptions
+
+# Background knowledge
+
+## Key_Shared subscriptions and the ordering contract
+
+A Key_Shared subscription allows multiple consumers to consume from one subscription in parallel while
+messages that share the same key are processed in order. The broker maps each message's *sticky key*
+(the ordering key, or the partition key when no ordering key is set — `Commands#resolveStickyKey`) to a
+16-bit *sticky key hash*, and maps hash ranges to consumers.
+
+[PIP-379](pip-379.md) (Pulsar 4.0) defined the ordering contract as an invariant:
+
+> In Key_Shared subscriptions, messages with the same key are delivered and allowed to be in an
+> unacknowledged state to only one consumer at a time.
+
+PIP-379 also documented an explicit carve-out, which is the subject of this proposal:
+
+> The Key_Shared subscription doesn't prevent using any methods in the consumer API. For example, the
+> application might call `negativeAcknowledge` or the `redeliverUnacknowledgedMessages` method. When
+> messages are scheduled for delivery due to these methods, they will get redelivered as soon as
+> possible. There's no ordering guarantee in these cases, however the guarantee of delivering a message
+> key to a single consumer at a time will continue to be preserved.
+
+## One key per entry
+
+The broker resolves the sticky key once per **entry**, from the entry-level `MessageMetadata` only:
+`Commands#resolveStickyKey` never descends into `SingleMessageMetadata`, and a batched entry is
+dispatched whole to a single consumer. The producer stamps that entry-level key from the *first* message
+added to the batch (`Commands#initBatchMessageMetadata`), so a producer that puts several distinct keys
+into one entry has all of them dispatched under the first message's key, and the Key_Shared contract does
+not hold for the keys that ride along.
+
+**Producers on a Key_Shared topic must therefore disable batching or use `BatcherBuilder.KEY_BASED`.**
+That is a condition of the existing contract rather than something this proposal introduces:
+[PIP-460](pip-460.md) states it outright, and [PIP-486](pip-486.md) describes it as the producer-consumer
+coupling it exists to remove. Nothing enforces it, and no javadoc on `BatcherBuilder`, `ProducerBuilder`
+or `KeySharedPolicy` states it, which is why it is named here rather than assumed: this proposal reasons
+throughout on the basis that **one entry carries one sticky key**, and a mixed-key entry is outside this
+guarantee exactly as it is outside today's.
+
+What that buys is used repeatedly below. The replay queue, `PendingAcksMap` and the redelivery count are
+all keyed by position, so the *entry* is the only granularity the broker has; under this precondition it
+is also key-precise, and no rule here has to reason about the individual messages inside an entry.
+
+## The Key_Shared dispatcher mechanics that this proposal builds on
+
+Four existing mechanisms matter, all in `PersistentStickyKeyDispatcherMultipleConsumers` and its base
+class:
+
+1. **The replay queue** (`MessageRedeliveryController`, field `redeliveryMessages`). Positions that must
+ be redelivered are held here. For ordered Key_Shared subscriptions the controller also indexes each
+ position's sticky key hash, and `containsStickyKeyHash(hash)` answers "is some message with this hash
+ waiting for redelivery?".
+2. **Three dispatch gates, not one.** A message can be withheld from a consumer at three independent
+ points, and any new blocking rule has to be applied at all three:
+ - `canDispatchEntry` — the per-entry check on a normal read;
+ - `ReplayPositionFilter` — the filter that selects positions from the replay queue before entries are
+ read from storage;
+ - `handleAddingPendingAck` — the send-time recheck reached through
+ `PendingAcksMap#addPendingAckIfAllowed`, which PIP-379 added specifically to close the race between
+ a consumer-set change and a send that is already in progress. Note that the shipped method tests
+ only the draining hash; the replay-index test that appears in the PIP-379 document was removed
+ during its implementation. PIP-493's retrying-hash test will therefore be the only ordering guard at
+ this gate, which is a further reason not to omit it.
+3. **Pending acknowledgements** (`PendingAcksMap`). For each dispatched-but-unacknowledged message the
+ broker keeps `(ledgerId, entryId) -> (remainingUnacked, stickyKeyHash)`. Full removals invoke a
+ `PendingAcksRemoveHandler` callback, which is how PIP-379 keeps `DrainingHashesTracker` in sync
+ without embedding that logic into `PendingAcksMap`. Partial acknowledgement of batch indexes goes
+ through `updateRemainingUnacked`, which mutates the packed value in place and does **not** invoke the
+ callback.
+4. **Draining hashes** (PIP-379). When hash ranges change, hashes with messages still pending at the
+ previous consumer are marked *draining* and withheld from the new consumer until the previous
+ consumer has acknowledged them. They are what the current dispatcher has in place of the *recently
+ joined consumers* read-position tracking that [PIP-282](pip-282.md) redefined and that only the
+ classic dispatcher still carries — which is one reason the classic dispatcher is a different ordering
+ regime and is out of scope here.
+
+## How negative acknowledgement works today
+
+`Consumer#negativeAcknowledge` is entirely a client-side facility. `NegativeAcksTracker` stores the
+message id together with a redelivery timestamp computed from `negativeAckRedeliveryDelay` or from the
+configured `RedeliveryBackoff`, and groups nacks by trimmed timestamp so that many of them travel in one
+command. A timer fires when the delay elapses, and only *then* does the client send
+`CommandRedeliverUnacknowledgedMessages`. Until that moment the broker knows nothing: the message
+remains in the consumer's `PendingAcksMap` and counts towards the unacknowledged-message limits, exactly
+as any other in-flight message.
+
+Two consequences follow, and both are visible in the code today:
+
+- For the whole retry delay the broker keeps dispatching later messages with the same key to the
+ consumer, because nothing has told it not to.
+- The sticky key hash is dropped on the redelivery path. `Consumer#redeliverUnacknowledgedMessages(List<
+ MessageIdData>)` builds a `List<Position>`, and `PersistentDispatcherMultipleConsumers#
+ redeliverUnacknowledgedMessages(Consumer, List<Position>)` calls the two-argument
+ `addMessageToReplay(ledgerId, entryId)`, which calls `redeliveryMessages.add(ledgerId, entryId)`
+ without a hash. The position is therefore not indexed by hash, `containsStickyKeyHash` will not report
+ it, and later messages with the same key are not withheld. The code carries a `TODO` acknowledging
+ this:
+
+ ```java
+ // TODO: We want to pass a sticky key hash as a third argument to guarantee the order of the messages
+ // on Key_Shared subscription, but it's difficult to get the sticky key here
+ ```
+
+ The hash is available where it is discarded: `PendingAcksMap#removeAndGetRemainingUnacked` already
+ reads it out of the packed value.
+
+# Motivation
+
+Key-ordered processing exists because processing events for one entity out of order corrupts state or
+triggers wrong actions. The most common reason a consumer cannot process a message *right now* is a
+transient failure of a downstream dependency: an HTTP 503, a database failover, a rate limit. The
+natural tool for "try this again in a moment" is `negativeAcknowledge`.
+
+On a Key_Shared subscription that tool is currently unusable when ordering matters:
+
+1. **Negative acknowledgement reorders the key.** Two keys are in flight, `A` and `B`, delivered
+ interleaved: `A1, B1, A2, B2, A3, B3`. The application nacks `A1`; `A2` and `A3` are already in the
+ consumer's receiver queue and are processed; `A1` is redelivered afterwards and processed last.
+ Ordering for key `A` is violated, silently. `B1, B2, B3` are unaffected and should be — the failure
+ had nothing to do with them, and a mechanism that stopped them would trade one problem for
+ another.
+2. **The alternatives are worse.** Routing the failed message to a dead letter topic leaves a permanent
+ gap in the key's sequence, and re-injecting it in the right place later is generally not possible.
+ Blocking the consumer thread until the downstream recovers stalls every other key handled by that
+ consumer.
+3. **Application-level workarounds do not have the tools to be safe.** An application can keep the
+ failed message and buffer later messages for the same key itself, but it cannot stop the broker from
+ dispatching more messages for that key. Under a sustained outage the buffer grows without bound and
+ the consumer's permits are consumed by messages it cannot process.
+
+Point 3 is why this cannot be solved in the client library alone: only the broker can stop dispatching
+messages for a key, and the current protocol has no way to tell it to.
+
+# Goals
+
+## In Scope
+
+- Preserve key ordering across negative acknowledgement on Key_Shared subscriptions with ordering
+ enabled, in both AUTO_SPLIT and STICKY mode: after a message is negatively acknowledged, no later
+ message with the same key reaches any application before that message has been acknowledged. (The
+ broker withholds by sticky key hash, so *newly dispatched* messages for keys colliding with the nacked
+ one are withheld as well. Colliding-key messages already inside the consumer are unaffected — see
+ [Two halves](#two-halves-because-the-messages-are-in-two-places).)
+- Keep the resource cost bounded for the whole duration of a downstream outage, on both sides, without
+ introducing any new unbounded or client-controlled broker state.
+- Leave the existing negative acknowledgement retry delay, `RedeliveryBackoff` and grouping behaviour
+ exactly as they are.
+- Pause delivery entirely, client-side, when the application is failing regardless of key, so that a
+ broad downstream failure is answered by stopping flow permits rather than by as many concurrent retry
+ cycles as there are active keys (see
+ [Client: broad-failure delivery pause](#client-broad-failure-delivery-pause)).
+- Keep the mechanism inert when it is not in use: no new state is held while no message is in a retry
+ cycle, and the work left on the idle path is constant-time and enumerated here — the per-add
+ `PendingAcksMap` callback that ordered Key_Shared installs in both modes, a single test against an
+ empty map at each of the three broker dispatch gates, and one `isEmpty()` check per delivered message
+ on the client. An AUTO_SPLIT subscription already pays that callback cost for draining hashes; for a
+ STICKY subscription it is new, and all of it is paid whether or not anything is ever negatively
+ acknowledged.
+- Make a stuck subscription diagnosable: how many hashes are withholding messages, and how many positions
+ the broker is tracking. Not which message is blocking each hash — the application that negatively
+ acknowledged a message still holds it, so the broker owes the operator magnitude and duration rather
+ than identity.
+- Degrade safely. Where the guarantee cannot apply, the behaviour falls back to today's, never to a
+ stall. The exception is the explicit opt-in `OrderedNegativeAckMode.REQUIRED`, which fails loudly
+ rather than degrading, because an application that asked for the property should learn from the client
+ that it is absent, not from its data. Ordered processing admission, the other explicit opt-in, fails
+ loudly only for client-side misconfiguration; it produces no failure of its own where the broker
+ capability is missing, and follows the mode instead — beside the default `BEST_EFFORT` that is the
+ typed per-message `ADMITTED_WITHOUT_GUARANTEE`, which is degradation the application is told about
+ rather than a stall or a silent reorder. See [Public API](#public-api).
+
+## Out of Scope
+
+- Ordering guarantees for `redeliverUnacknowledgedMessages()`, acknowledgement timeout redelivery, dead
+ letter topics and retry letter topics. These remain as documented by PIP-379.
+- Shared, Exclusive and Failover subscriptions. Their negative acknowledgement behaviour is unchanged,
+ and the Java client does not use the new command for them.
+- Key_Shared subscriptions created with `KeySharedPolicy#setAllowOutOfOrderDelivery(true)`; the classic
+ Key_Shared dispatcher (`subscriptionKeySharedUseClassicPersistentImplementation=true`); and
+ [PIP-486](pip-486.md) entry-bucket dispatch (`KeySharedMeta.entryBucketDispatch`), where the
+ dispatch unit is a producer-stamped entry bucket spanning many keys rather than a key hash.
+- Messages with neither an ordering key nor a partition key, and chunked messages. See
+ [General Notes](#general-notes) for why each is excluded and how each could be added later.
+- Non-persistent topics, which have no redelivery.
+- Clients other than the Java client. The protocol change is additive; other clients may adopt it later
+ by implementing the [client conformance requirements](#client-conformance-requirements).
+- Detecting, rejecting or reporting batch entries that mix several distinct keys. Such entries fall
+ outside the [one key per entry](#one-key-per-entry) precondition and outside this guarantee, exactly as
+ they fall outside today's.
+
+# High Level Design
+
+## The invariant
+
+PIP-493 replaces the negative acknowledgement carve-out in the PIP-379 contract with a guarantee:
+
+> **On a Key_Shared subscription with ordering enabled, when a message is negatively acknowledged, no
+> *later* message with the same key is delivered to any application until that message has been
+> acknowledged.**
+
+The word "later" is load-bearing: the negatively acknowledged message is itself a message with that key,
+and redelivering it is the whole point. "Later" means later in position order within the subscription.
+
+The wording for `redeliverUnacknowledgedMessages` is unchanged: that method still carries no ordering
+guarantee.
+
+## Two halves, because the messages are in two places
+
+At the moment of the nack, the messages that must not reach the application live in two places:
+
+- Messages the broker has **not yet dispatched**. Only the broker can withhold these, and it must,
+ because otherwise they accumulate somewhere for the whole outage.
+- Messages **already inside the consumer**. The broker cannot recall them — they are on the wire, in the
+ receiver queue, or already queued on a listener executor. Only the client can deal with these.
+
+So the design has two mechanisms:
+
+| | Broker: *retrying hashes* | Client: *keys awaiting retry* |
+|---|---|---|
+| Unit | sticky key hash | sticky key bytes |
+| Withheld | positions strictly later than that hash's earliest outstanding nacked position | positions strictly later than that key's earliest outstanding nacked position |
+| Effect | withholds dispatch to any consumer | **returns** the message to the broker instead of delivering it |
+| Set by | the nack command | `negativeAcknowledge(Message)` |
+| Cleared by | acknowledgement of the nacked message | acknowledgement of the nacked message, with self-healing fallbacks |
+
+**One rule, applied at three places.** The *Withheld* row is deliberately the same rule on both sides,
+and the admission rule of `acquireForOrderedProcessing` (see [Public API](#public-api)) is the third
+instance of it: a message is withheld exactly when an *earlier* position of the same key is still
+unresolved, and it
+is delivered when it is at or before that position. The three differ only in what each place can see —
+the broker evaluates it over the negatively acknowledged positions of a *hash*, because the key bytes are
+not in its hands at the gates; the client's guard evaluates it over the negatively acknowledged positions
+of a *key*; and admission evaluates it over every undisposed copy of a key, because the application may
+hold several. Stating it once here is worth doing, because the alternative shape — a predicate over the
+*set* of guarded keys — is wrong in the same way at all three: it refuses positions *earlier* than the
+negatively acknowledged one, which the invariant never asked for. On the broker that wedges permanently
+(see [Broker: retrying hashes](#broker-retrying-hashes)); in the client it disarms a live guard (see
+[Client: keys awaiting retry](#client-keys-awaiting-retry)); in the application it teaches exactly the
+reordering the feature exists to prevent (see [Alternatives](#alternatives)).
+
+**The two units differ deliberately, and the client's is the finer one.** When key `A` is nacked, a
+message already inside the consumer that belongs to key `C` — a distinct key whose hash collides with
+`A`'s — is *not* returned: it is delivered and processed normally. Only newly dispatched `C` messages are
+withheld, by the broker, once it has the command. So a nack costs a colliding key its future throughput
+for the duration of the outage, but never the work already in the consumer's hands.
+
+That is sound rather than merely convenient, and the reason is worth stating because it is not obvious.
+Consumer selection is a pure function of the hash, so `A` and `C` always resolve to the *same* consumer,
+whose receiver queue is FIFO. The set of `C` messages inside the client at the moment of the nack is
+therefore exactly what the broker had already dispatched — a position-ordered **prefix** of the
+outstanding `C` stream — and everything the broker *withholds* is strictly later in position order than
+the nacked position. Delivering the prefix while withholding the remainder preserves `C`'s order. Every
+broker-side gate is hash-coarse, i.e. a superset of the key-precise set, so the error direction is always
+over-withholding, never under-withholding.
+
+What is *not* true, and is the reason all three of those rules are position-ordered rather than phrased
+over a set of keys, is that everything arriving after the nack is later than it. An earlier position of
+the same hash — the same key, or a colliding one — can still be dispatched afterwards: when a consumer
+disconnects, its pending acknowledgements are re-added to the replay queue with their hashes and replayed
+*ahead* of the nacked position, in order, to whichever consumer now owns the hash; and the legacy
+hash-less replay path leaves earlier positions in the queue that no hash index withholds at all. The
+withholding rule dispatches such a position deliberately, and the client delivers it for the same reason.
+That is correct rather than an exception: the message is earlier than everything the guard is protecting,
+nothing the broker withholds stands in front of it, and returning it would only send it straight back —
+the broker does not withhold it, so it would arrive again, and a client that treated its own return as
+evidence would disarm a guard whose hash is still retrying. The messages the client returns are the
+later ones, and only those.
+
+This rests on the `returned` list being key-precise. Returning by hash instead would pull a colliding
+key's messages back out of the client's ordered stream and break the prefix property, which is why
+conformance rule 8 is written in terms of "that key". Returning at *entry* granularity — the only unit the
+replay queue has — stays key-precise, because [one entry carries one key](#one-key-per-entry).
+
+That precondition is load-bearing one step earlier as well: "consumer selection is a pure function of the
+hash" is, for a batched message, a function of its *entry's* key rather than its own.
+
+The client **returns** messages rather than holding them. This is the central decision, and it is what
+makes the design safe: a message held inside the client is still recorded in that consumer's
+`PendingAcksMap`, so the broker believes it is being processed. If the hash is then reassigned, PIP-379
+marks it draining until the previous consumer acknowledges those messages — while the client refuses to
+hand them to the application until the nacked message is acknowledged, which cannot happen until the
+draining hash releases. That is a circular wait that nothing but an acknowledgement timeout breaks.
+Returning the messages removes them from `PendingAcksMap` and dissolves the cycle. It also removes the
+need for any client-side buffer, its memory accounting, and its interaction with permits and the
+acknowledgement timeout tracker.
+
+Returning reuses existing, proven machinery on the parts that matter most:
+`ConsumerImpl#redeliverUnacknowledgedMessages(Set<MessageId>)` already takes messages out of
+`incomingMessages`, releases them, corrects the incoming-message size accounting and restores the
+permits, and it is the model the return path follows. What it does not already do is find them. It
+drains through `GrowableArrayBlockingQueue#pollIf`, which tests only the element at the head and returns
+null at the first non-match, so it reclaims a matching *prefix* of the receiver queue and nothing behind
+it. For the nacked key's own messages sitting at the head that is exactly right; collecting a key's
+messages scattered through the queue is new work, and a predicate sweep over the whole queue rather than
+its head is the part this design adds. The other new part is on the broker: it must not count a returned
+message as a redelivery, because the application never saw it — otherwise `RedeliveryBackoff` escalates
+and the dead letter topic eventually swallows messages nobody ever tried to process.
+
+## The nack becomes an immediate signal, and nothing else moves
+
+The one structural change is *when* the broker is told. A new `CommandNegativeAck` is sent at nack time
+and carries two lists: the negatively acknowledged messages, and the messages the consumer is returning
+unprocessed. It carries **no delay**. The retry delay, `RedeliveryBackoff`, the grouping window and the
+existing `CommandRedeliverUnacknowledgedMessages` that the timer eventually sends all stay exactly where
+they are today.
+
+That is deliberate. Moving the retry deadline to the broker so that one command could do everything was
+considered and rejected, for three reasons that only became visible once the consequences were followed
+through:
+
+- A broker-side deadline requires the broker to drop the message from `PendingAcksMap` at nack time, so
+ the message escapes `maxUnackedMessagesPerConsumer` / `maxUnackedMessagesPerSubscription` accounting
+ while occupying broker state for a client-chosen duration. That is a new denial-of-service lever.
+- `RedeliveryBackoff` produces a *different* delay per message, so a single per-command delay is not
+ expressive enough, and a per-message delay on the wire also has to specify how the grouping window and
+ network transit are subtracted from it.
+- It needs a scheduler, a clamp, saturating deadline arithmetic, and a defined lifecycle across consumer
+ disconnect, cursor reset and topic unload.
+
+Leaving the timer on the client removes all of that. The nacked message stays in `PendingAcksMap`
+exactly as it does today, so it stays inside the existing unacknowledged-message accounting, and the
+broker gains no timer at all.
+
+The `negative_acked` entries carry one further thing, and it costs no schema change. Batch index
+acknowledgement is enabled by default, so a batched entry can already be partly acknowledged when one of
+its messages is negatively acknowledged, and the broker needs the batch dimension to know when that entry
+is resolved. A `negative_acked` entry therefore populates the existing `MessageIdData.batch_index` — the
+index that was negatively acknowledged — and the existing `MessageIdData.ack_set` — the client's current
+bitmap of the indexes of that entry that are **still unacknowledged**. That is the polarity `ack_set`
+already has on the wire: every index of a batch starts with its bit set, acknowledging an index *clears*
+that bit, and an entry is fully acknowledged when the bitmap is empty. This document uses that wire
+encoding everywhere it names `ack_set`; where the prose is clearer talking about the acknowledged
+indexes it says so explicitly rather than switching silently. Both fields are already on `MessageIdData`,
+so this is new semantics on an existing message rather than a protobuf schema change. The `ack_set` is a
+diagnostic cross-check, which the broker may log on mismatch and otherwise ignores; it is never treated
+as an acknowledgement, and nothing on the nack path writes acknowledgement state. See
+[Broker: retrying hashes](#broker-retrying-hashes) for how the broker resolves an entry's indexes from
+its own state, and [Client conformance requirements](#client-conformance-requirements) for the
+acknowledgement flush that makes that state at least as new as the client's.
+
+## Lifecycle
+
+```mermaid
+sequenceDiagram
+ participant App as Application
+ participant Cn as Consumer (client)
+ participant B as Broker (Key_Shared dispatcher)
+
+ B->>Cn: deliver A1, B1, A2, B2, A3, B3 (keys A and B, interleaved)
+ Cn->>App: A1
+ App->>Cn: negativeAcknowledge(A1)
+ Note over Cn: key A awaits retry
+ Cn->>B: NegativeAck(negative_acked=[A1], returned=[A2, A3])
+ Note over B: hash(A) is retrying.<br/>A2, A3 into the replay queue,<br/>not counted as redeliveries
+ Cn->>App: B1, B2, B3
+ Note over App: key B is untouched:<br/>its messages are delivered<br/>and processed in order throughout
+ B--xCn: no further dispatch for hash(A) —<br/>including future messages of key C,<br/>a distinct key whose hash collides with A's
+ Note over Cn: retry delay elapses (unchanged client timer)
+ Cn->>B: RedeliverUnacknowledged([A1])
+ B->>Cn: deliver A1
+ Note over Cn: A1 is one of this consumer's own<br/>nacked messages, so it is delivered,<br/>not returned — but key A still awaits retry
+ Cn->>App: A1
+ App->>Cn: acknowledge(A1)
+ Note over Cn: key A no longer awaits retry
+ Cn->>B: Ack(A1)
+ Note over B: hash(A) no longer retrying
+ B->>Cn: deliver A2, A3, then A4, A5 ..., and key C again
+ Cn->>App: A2, A3, ...
+```
+
+If the application nacks `A1` again instead of acknowledging it, the hash simply stays retrying and the
+cycle repeats. Nothing accumulates while it does: the broker dispatches nothing for that key, so the
+only messages the client ever has to return are the ones that were already in flight when the first nack
+happened. Key `B` is unaffected throughout — that is the difference from a client-only solution — and key
+`C` pays only for the collision, in future dispatch and never in the work already in the consumer's
+hands.
+
+# Detailed Design
+
+## Design & Implementation Details
+
+### Broker: retrying hashes
+
+A hash is **retrying** while at least one negatively acknowledged message with that hash has not been
+acknowledged. A new per-dispatcher component in `PersistentStickyKeyDispatcherMultipleConsumers` tracks
+this, alongside `DrainingHashesTracker`:
+
+- **State**: `stickyKeyHash -> ordered set of negatively acknowledged positions`. The set normally holds
+ one position; it holds more only when an application has several messages for one key in flight and
+ nacks more than one.
+- **Blocking**: an entry whose hash is retrying is withheld if and only if its position is **strictly
+ later** than the earliest position in that hash's set. The earliest nacked position is dispatched —
+ that is the retry — and so is anything before it.
+
+ The rule is stated in terms of position order rather than set membership, and the difference matters.
+ Withholding everything except the earliest nacked position looks equivalent and is not: it also
+ withholds positions *earlier* than the nacked one, which the invariant never asked for, and that
+ wedges permanently. A consumer can hold an earlier unacknowledged position with the same hash — the
+ same key, or merely a colliding one — and when that consumer disconnects, its whole pending-ack map is
+ re-added to the replay queue *with* hashes. The replay filter then meets the earlier position first,
+ withholds it, and records the hash in its per-pass blocked set; the exempt position is short-circuited
+ by that set before the exemption is ever consulted, so it is never dispatched, never acknowledged, and
+ never releases the hash that is blocking the position in front of it. Ordering by position dissolves
+ this: the earlier position replays ahead of the nacked one, in order, and the hash still withholds
+ everything after it. It also preserves what the earliest-only formulation was introduced for — a
+ second negatively acknowledged position of the same key is later than the first, so it stays withheld
+ until the first resolves.
+
+ (This does not rescue chunked messages: every chunk after the first is later than the earliest, so the
+ chunk wedge described in [General Notes](#general-notes) stands and the exclusion remains.)
+
+ The rule is applied at **all three** dispatch gates listed in Background — `canDispatchEntry`,
+ `ReplayPositionFilter`, and the send-time `handleAddingPendingAck`. Omitting the third would leave exactly
+ the race PIP-379 introduced that recheck to close: a send already in progress when the nack arrives.
+
+ Two details of *how* it is applied are easy to get wrong and are part of the design. The test in
+ `canDispatchEntry` must run for **both** read types: the pre-existing `containsStickyKeyHash` test
+ beside it is gated on `ReadType.Normal`, and a retrying test gated the same way would be bypassed by
+ exactly the replay that carries the redelivered message and its successors. And `ReplayPositionFilter`
+ cannot obtain a position's hash from the replay queue's index, which returns nothing for the hash-less
+ inserts that the legacy path produces — which is precisely how a nacked message re-enters the replay
+ queue once its retry has been requested. The tracker must therefore hold a `position -> hash` lookup of
+ its own alongside `stickyKeyHash -> ordered set of positions`, so the filter can recognise the exempt
+ position rather than waving it through.
+
+ The third gate needs care, because its contract differs from the other two. `canDispatchEntry` and
+ `ReplayPositionFilter` are predicates whose callers re-queue the rejected entry;
+ `handleAddingPendingAck` must re-queue the entry itself, because its caller in `Consumer#sendMessages`
+ drops and releases it outright. Applying the retrying rule there as a plain predicate would silently
+ lose the message. The nacked position must be exempt at this gate too — otherwise the one message the
+ mechanism exists to deliver is the one that can never be sent.
+
+ Both `PendingAcksMap` handlers are installed together today, and only when `drainingHashesRequired` is
+ true, which excludes STICKY Key_Shared. The add handler is the one that reaches this gate; the remove
+ handler drives *draining-hash* release and nothing else — its `handleRemoving` calls
+ `DrainingHashesTracker#reduceRefCount` (`PersistentStickyKeyDispatcherMultipleConsumers.java:176-192`). What
+ this proposal needs installed for ordered Key_Shared subscriptions in **both** modes is therefore the
+ **add handler**, and only it. STICKY does not need draining hashes, because its ranges do not move, but
+ it does need retrying hashes, and its users — who pin keys to instances precisely because ordering
+ matters to them — are among those most likely to want them. The cost is the per-add callback that
+ AUTO_SPLIT subscriptions already pay.
+
+ The remove handler stays what it is today: a draining-hash mechanism, installed in AUTO_SPLIT alone.
+ The retrying tracker takes **no** removal callback at all. Its release signal is on the subscription's
+ acknowledgement path, for the reason the *Release* bullet below gives, and a non-closing removal
+ carries nothing that path does not — it fires on the retry request as readily as on an acknowledgement,
+ which is exactly why it cannot be the signal.
+- **Precedence with draining hashes**: the two rules are independent and both must pass. A retrying-hash
+ exemption exempts a position only from the *retrying* rule; if the hash is also draining, PIP-379 wins
+ and the message waits. The nacked message stays in `PendingAcksMap` until its redelivery is requested,
+ so it keeps its own hash draining-consistent, and the previous consumer's returned messages have
+ already left `PendingAcksMap` — which is what prevents a circular wait.
+- **Registration**: the nack command must register the retrying hashes and remove the returned positions
+ from `PendingAcksMap` as one synchronized step with respect to dispatch, so that no send can observe
+ neither the old pending acknowledgement nor the new retrying hash. Registration accepts a position only
+ while the sending consumer still holds it in its `PendingAcksMap`; that precondition is what ties the
+ tracker's intake to the unacknowledged-message accounting, and without it the tracker would be the one
+ structure in the design with no server-side gate on its position count. A position that fails it is
+ **skipped as an idempotent per-position no-op**, in the same terms the `returned` list already uses:
+ the command's remaining positions are still processed, the command never fails, and the connection is
+ never closed. That is a clarification of the precondition rather than a weakening of it — a nack racing
+ a disconnect is a designed-for case, and a client that batches several keys into one command must not
+ lose the well-behaved positions along with the stale one. That precondition is forced rather than
+ chosen: the broker cannot recompute a sticky key hash from a message id, and `PendingAcksMap` is the
+ only structure holding `(position -> hash)` for a dispatched message — so a read accessor must be added
+ there. What it offers today is a whole-map traversal: `PendingAcksMap#forEach` is public and hands the
+ sticky key hash of every entry to a processor without removing anything, which is what the draining-hash
+ scan (`PersistentStickyKeyDispatcherMultipleConsumers.java:202`) and
+ `PersistentDispatcherMultipleConsumers#redeliverUnacknowledgedMessages(Consumer, long)`
+ (`PersistentDispatcherMultipleConsumers.java:1142`) already use. What is missing is a **per-position**
+ hash lookup, which is what registration needs. What stops a stale nack from registering once its
+ consumer is gone is that precondition, and it is worth saying which mechanism satisfies it in which
+ case, because the two disconnect paths differ. When
+ **other consumers remain**, `removeConsumer` drains the departing consumer's pending acknowledgements
+ through `PendingAcksMap#forEachAndClose`, which closes the map to further entries: the precondition can
+ never be met again, and the closed map is a genuine fence. When the **last** consumer disconnects the
+ map is neither closed nor cleared — that path takes `clearComponentsAfterRemovedAllConsumers` instead —
+ and it needs no fence, for the reason the *Lifecycle* bullet below gives: the same path clears the
+ replay queue and the tracker, and the next consumer to arrive rewinds the cursor, so every position
+ reverts to an ordinary unread one and there is nothing left for a late registration to be about.
+ Registration is idempotent: a second nack of a position already in the set is a no-op rather than an
+ error, which is what makes repeated nacks of the same message well defined. Registration skips the
+ `NONE_KEY` marker's hash, which a message reaches only when its metadata cannot be parsed. Note that
+ this does *not* implement the exclusion of keyless messages described in
+ [General Notes](#general-notes): `resolveStickyKey` falls back to a producer-name/sequence-id key
+ before `NONE_KEY`, so by the time the broker sees a hash it cannot tell a keyless message from a keyed one.
+ That exclusion is necessarily client-side.
+
+ Registration also snapshots, in the same synchronized step, the entry's unresolved **batch-index**
+ state. `PendingAcksMap` packs `remainingUnacked`, which says how many of the entry's messages are still
+ outstanding but not which ones, so the tracker materialises the unresolved indexes as a bitmap from the
+ broker's own batch-index acknowledgement state for that position; the client-sent `ack_set` is
+ cross-checked against it and is never a source of truth. That bitmap carries the same polarity as
+ `ack_set` — a set bit is an index that is still unacknowledged — and it composes with an arriving
+ `ack_set` the way the cursor already composes them, by intersection: `ManagedCursorImpl` merges an
+ incoming `ack_set` into the stored one with `and` and deletes the entry once the result is empty. So
+ "clear the bits an acknowledgement resolves" and "intersect the bitmap with the acknowledgement's
+ `ack_set`" are the same operation, and the tracker's release condition — the unresolved set is empty —
+ is the same condition under which the cursor deletes the entry. The tracker **retains** that per-entry
+ bitmap after the retry request later removes the entry from `PendingAcksMap`. Retention is what makes
+ release possible at all: once the retry has been requested there is no pending acknowledgement left to carry
+ the state, and an acknowledgement arriving after that moment must still find something to resolve.
+- **Release**: a position leaves the set when every index it holds has been acknowledged. **This needs a
+ new, acknowledgement-specific signal; the existing `PendingAcksRemoveHandler` cannot carry it.** That
+ callback fires for every removal from `PendingAcksMap`, and the client's own redelivery request removes
+ the nacked position through the same method as an acknowledgement — `removeAndGetRemainingUnacked`,
+ reached from the ack path and from `redeliverUnacknowledgedMessages` alike — with the same arguments
+ and the same `closing=false`. A tracker that released on that callback would release on the retry
+ request, which is the one moment it must not.
+
+ The signal is therefore taken on the **subscription's acknowledgement path**, keyed by position and
+ independent of `PendingAcksMap` membership, and it clears bits from the entry's unresolved-index bitmap
+ rather than decrementing a counter. It must fire for all four ways an index is genuinely resolved:
+ acknowledgement of individual batch indexes, which already travels this very path with its `ack_set`
+ attached to the position — `Consumer#individualAck` calls `subscription.acknowledgeMessageAsync`
+ (`Consumer.java:699`) on the `nonTxnPositions` it assembles with `buildPosition` (called at `:663`,
+ body at `:771-786`), and those positions carry the ack set, built by
+ `AckSetStateUtil.createPositionWithAckSet`; acknowledgement of the whole entry; the cursor's
+ mark-delete position advancing past it, which covers cumulative acknowledgement, message expiry and
+ administrative skips; and the **commit** of a transactional acknowledgement. It must **not** fire for a
+ removal caused by redelivery, at either granularity. When the entry's bitmap is empty its position leaves
+ the set, and when the set becomes empty the hash stops retrying and the existing batched unblock
+ notification (`keySharedUnblockingIntervalMs`, `RescheduleReadHandler`) schedules a read.
+
+ `PendingAcksMap#updateRemainingUnacked` is not that signal and must not be mistaken for it. It is the
+ per-consumer unacknowledged-count bookkeeping applied *after* the acknowledgement has been handed to
+ the subscription (`Consumer.java:733-745`), it mutates the packed value in place, and it invokes no
+ callback at all — which is exactly why a release signal anchored on `PendingAcksMap` cannot see a
+ batch-index acknowledgement, and why the signal is taken on the acknowledgement path instead.
+
+ Two properties of that shape are load-bearing. *Resolution is idempotent*, because it is a bitmap and
+ never a scalar decrement: a duplicate or reordered acknowledgement command clears an already-clear bit
+ and changes nothing, where a decrement would double-release and let the key run ahead of its own nacked
+ message. And *nothing on the nack path ever writes acknowledgement state* — no cursor mutation, no
+ synthesized acknowledgement. "The indexes before the nacked one are acknowledged" is something the
+ broker **observes** in its own state, made current by the client's flush before the command (see
+ [Client conformance requirements](#client-conformance-requirements)), and never something the broker
+ assumes or applies. If the application violated the in-order processing discipline and an earlier index
+ is genuinely unacknowledged at the broker, the bitmap stays non-empty and the hash simply stays
+ retrying until real resolution arrives: over-withholding, never loss.
+
+ **A transactional acknowledgement releases the position only on commit.** The broker removes the
+ pending acknowledgement when the transactional ack is processed, before the transaction's outcome is
+ known, and `PendingAckHandleImpl` replays the transaction's positions if it aborts. Treating that
+ removal as final would release the hash, let the next message for the key be dispatched, and then
+ replay the nacked message behind it. The tracker must therefore **keep** the position across that
+ removal and **release** it at commit — not re-register it. There is nothing to re-register: the
+ position never left the tracker. Re-registration is not even available, because registration accepts a
+ position only while the sending consumer still holds it in its `PendingAcksMap`, which a committed
+ transactional acknowledgement no longer does. The same holds index by index: a transactional
+ acknowledgement of individual batch indexes clears their bits only at commit, and an abort leaves them
+ set, so a transaction that never commits cannot release a partly acknowledged entry.
+
+ This needs no commit-side hook of its own, and the reason strengthens the rule rather than merely
+ saving work. `PendingAckHandleImpl`'s commit paths acknowledge through
+ `persistentSubscription.acknowledgeMessageAsync` (`PendingAckHandleImpl.java:470`, `:780` and `:800`)
+ — the subscription acknowledgement path this design already places the release signal on, and a path
+ that reaches the dispatcher today. Commit is thus the only moment a transactionally acknowledged
+ position reaches that path at all, so the release can fire nowhere else: "release only on commit" is a
+ property of where the signal is taken rather than a rule an implementation has to remember to enforce.
+ The abort side needs nothing either: the position never left the tracker, and the existing abort
+ replay is enough.
+
+ While the outcome is pending the position is in the tracker but in neither `PendingAcksMap` nor the
+ replay queue, so it is the earliest and nothing for that hash can be dispatched. That is correct, and
+ it is worth naming as the longest wait in the design: a consumer that acknowledges in a transaction
+ and then dies withholds the key until the transaction times out. Every other wait here is bounded by
+ a retry delay.
+- **Lifecycle**: the tracker holds *positions*. It holds no consumer identity and has no range dimension,
+ and must acquire neither. A position stays in it for exactly as long as it is a negatively
+ acknowledged message of this subscription that has not been acknowledged. Consumer scoping belongs to
+ **registration** and only there; retention is position-scoped and release is acknowledgement-driven.
+
+ *A position is removed only by resolution*: acknowledgement, the mark-delete position advancing past
+ it, or one of the bulk resets that invalidates every position the dispatcher holds — cursor reset or
+ seek, topic unload, and the disconnect of the **last** consumer
+ (`clearComponentsAfterRemovedAllConsumers`). That last case is not merely "runtime state is cleared":
+ the same path clears the replay queue, and the next consumer to arrive rewinds the cursor, so every
+ position reverts to an ordinary unread one and there is nothing left for a retrying entry to be about.
+
+ *Retrying hashes survive the disconnect of one consumer among several — including the consumer that
+ sent the nack.* `removeConsumer` re-adds that consumer's pending acknowledgements to the replay queue
+ **with their sticky key hash** and triggers a read, so a nacked message whose redelivery had not yet
+ been requested becomes immediately deliverable again: it is the earliest position of its hash, and it
+ is replayed to whichever consumer now owns that hash, with no dependence on the client timer that died
+ with the connection. The replay queue is not a substitute for the tracker here. Its hash index
+ withholds only until the position is *dispatched* — replay positions leave `redeliveryMessages` just
+ before `Consumer#sendMessages` — not until it is acknowledged, which is exactly the interval this
+ proposal exists to cover; and `ReplayPositionFilter` accepts later same-hash positions once an earlier
+ one has been accepted, so the nacked message and its returned successors would be selected in one pass
+ and handed together to a consumer whose guard is not armed, which is the original bug. If the retry had
+ already been requested, the position sits in the replay queue *without* a hash, by the legacy path this
+ proposal deliberately leaves alone, and the tracker is then the only ordering guard there is.
+
+ *Retrying hashes survive hash range reassignment, in both modes.* Every gate resolves the target
+ consumer from the selector at decision time, so the exempt position is dispatched to the new owner and
+ the withholding transfers with the range. The *request* side is ownership-independent as well, which
+ the argument below depends on and which is worth stating because it is the opposite of what one
+ expects: `Consumer#redeliverUnacknowledgedMessages(List<MessageIdData>)` accepts a position exactly
+ when the *sending* consumer still holds it in its own `PendingAcksMap`, and consults the selector
+ nowhere; a range change neither moves nor clears pending acknowledgements — that is precisely what
+ makes the hash draining. So a consumer that has lost the range still has its retry honoured, and the
+ position enters the subscription-wide replay queue from which the current owner takes it.
+
+ Draining hashes are not a substitute: a draining entry lasts only from the range change until the
+ nacked message leaves the previous consumer's `PendingAcksMap`, and that boundary *is* the retry
+ request — so the draining guard expires at the instant the retry begins. Draining is also computed from
+ a scan of `PendingAcksMap` taken at the moment of the change, so it cannot see a position whose
+ redelivery has already been requested. And STICKY has no draining machinery at all.
+
+ Implementation note: **discarding on disconnect is what an implementation gets by accident** if it
+ anchors the tracker on `PendingAcksMap` removals. `PendingAcksMap#forEachAndClose` invokes the remove
+ handler with `closing=true` for every drained entry, so a tracker wired there would discard precisely
+ the entries this bullet says survive — the rejected alternative, arrived at by omission. Taking no
+ removal callback at all, which the *Release* bullet requires for its own reason, forecloses it.
+
+Nothing here is persisted. After an unload or a broker restart the nacked messages are simply
+unacknowledged messages, replayed in position order on reconnection, which preserves ordering even
+though the retry delay is lost — the same as today.
+
+### Broker: preserving the sticky key hash on the redelivery path
+
+Positions that `CommandNegativeAck` puts into the replay queue — the `returned` list — carry their
+sticky key hash, taken from `PendingAcksMap` where `removeAndGetRemainingUnacked` already reads it. This
+is the `TODO` quoted in Background, applied on the new path.
+
+It is applied **only** on the new path. The tempting move is to fix the `TODO` everywhere, so that every
+targeted redelivery becomes hash-aware, and that was considered and rejected. It is out of scope: it
+changes behaviour for older clients' negative acknowledgements and for every
+`redeliverUnacknowledgedMessages(Set<MessageId>)` call, which would make this PIP carry an ordering
+change nobody voting on it asked for. PIP-493 needs no such change — a retrying hash is withheld by the
+tracker, not by the replay queue's hash index — so the legacy path keeps today's behaviour and the
+compatibility story stays clean.
+
+The hash-less overload of `Subscription#redeliverUnacknowledgedMessages(Consumer, List<Position>)`
+therefore stays as it is, which is required anyway:
+`MessageRedeliveryController#add(ledgerId, entryId, stickyKeyHash)` throws `IllegalArgumentException`
+when the hash is `STICKY_KEY_HASH_NOT_SET` on the current dispatcher, and at least one caller has no
+hash to give — `PendingAckHandleImpl` replays positions taken from the transaction pending-ack map on
+transaction abort, not from `PendingAcksMap`.
+
+### Broker: bounds
+
+The retrying-hash map has at most one bucket per hash. Every `StickyKeyConsumerSelector` that ordered
+Key_Shared dispatch can use produces hashes in a 65 535-value space — `ConsistentHashing` over
+`[1, 65535]`, the two `HashRange` selectors over `[0, 65535]` with a zero result remapped to 1 — so a
+subscription has at most 65 535 buckets, each keyed by an `int`, and the map is empty in the normal case.
+The tree holds a fourth implementation, [PIP-486](pip-486.md)'s `EntryBucketConsumerSelector`, but it
+serves entry-bucket dispatch, which is already out of scope for this proposal (see
+[Out of Scope](#out-of-scope)); no subscription this proposal applies to selects through it.
+
+The number of *positions* it holds is not bounded by that, and — contrary to what one might assume — it is
+not bounded by the unacknowledged-message limits either. What those limits bound is how many positions can
+be negatively acknowledged *at one instant*: a position enters the tracker only while the sending consumer
+holds it in `PendingAcksMap`, and for ordered Key_Shared the per-consumer limit is enforced before
+dispatch. The bound stops there, because the accounting is refunded *before* the tracker entry is
+released. The unconditional retry request removes the position from `PendingAcksMap` and decrements both
+the per-consumer and the per-subscription counter; the returned positions leave `PendingAcksMap` at nack
+time by design; and a consumer disconnect refunds the subscription counter and moves that consumer's whole
+map into the replay queue. The tracker holds all of them until acknowledgement, which is strictly later.
+A retrying position therefore spends most of its life with no unacknowledged-message accounting behind it,
+and that window is the ordinary retry cycle rather than an edge case. `maxUnackedMessagesPerSubscription`
+never capped a structure in any case: it gates normal reads, and it is checked in an `else if` after the
+replay branch, so a dispatcher blocked on it keeps replaying.
+
+What limits the total is intake. A refund moves a position from `PendingAcksMap` to the replay queue; it
+does not create one. A new tracked position requires a new dispatch, a dispatch of an unread message
+requires a normal read, and normal reads stop once the replay queue reaches the effective look-ahead
+limit. The look-ahead limits still do not cap the replay queue — redelivery requests and consumer
+disconnects add to it unchecked — but gating reads is what throttles growth. They throttle the tracker
+rather than bound it. With defaults that puts the resident state at the order of
+`min(consumers × 50 000, 200 000)` messages in `PendingAcksMap` plus `min(consumers × 4000, 40 000)`
+positions parked in the replay queue. Those two limits are not directly comparable — the replay queue
+counts positions while the unacknowledged counters count messages, batch members individually — but since
+positions ≤ messages, the replay threshold binds first.
+
+The ceiling that survives every configuration is the withholding rule itself. Once a hash is retrying,
+only its earliest position may be dispatched, so that hash accepts no positions beyond those already in
+flight when it became retrying; further growth needs hashes that are not yet retrying, and there are at
+most 65 535 of them. Everything else can be switched off: both unacknowledged limits accept zero, the
+per-consumer limit is zero for non-durable subscriptions whatever the configuration, and the effective
+look-ahead limit falls back to the unacknowledged settings when both thresholds are zero and to
+`Integer.MAX_VALUE` when those are zero too.
+
+The tracker therefore carries a per-subscription ceiling on tracked positions of its own, configured by a
+new broker key `keySharedNegativeAckMaxRetryingPositionsPerSubscription`, default `50000` and dynamic.
+The default sits above the 40 000 default per-subscription replay look-ahead threshold, so it never binds
+in a default configuration; it takes effect only once the throttles above it have been turned off, which
+is exactly the case the previous paragraph describes.
+
+The ceiling is enforced at the **three dispatch gates**, not at registration. While the tracked-position
+count is at or above it, `canDispatchEntry`, `ReplayPositionFilter` and `handleAddingPendingAck` admit
+only the exempt earliest positions of hashes that are already retrying, so nothing that could create a
+*new* tracked position is delivered and the tracker cannot grow. Registration of a negative
+acknowledgement for a message that has already been dispatched is **always** accepted, overflow or not:
+refusing it would let that message's successors through while its own retry is outstanding, which is the
+guarantee itself, and intake at that instant is bounded by the unacknowledged-message limits exactly as
+this section argues above. Recovery needs no intervention — capacity frees as acknowledgements resolve
+positions and their hashes release, and dispatch resumes. Overflow is observable rather than silent:
+`retryingPositionsCount` (see [Metrics](#metrics)) sits **at or above** the configured ceiling for as
+long as it lasts, and the broker emits a rate-limited warning on entry into overflow. The *or above* is
+not slack in the wording: the gates stop admitting anything that could create a *new* tracked position
+once the ceiling is reached, but the negative acknowledgements the previous sentence always accepts
+still arrive, so the count settles somewhat past the ceiling and falls back only as those positions are
+acknowledged. The ceiling is the line at which overflow begins, not a value the count is pinned to. This is
+the same over-withhold-never-under-withhold direction as every other rule here. The alternative — accepting
+the nack but not tracking it, so ordering silently lapses under load — was rejected: a guarantee that stops
+holding precisely when the system is under pressure is not one an application can build on.
Review Comment:
The configured value appears to be a dispatch threshold rather than a bound on tracker state. With the unacknowledged-message limits disabled, a consumer can accumulate an arbitrary number `N` of pending positions before issuing negative acknowledgements. The first 50,000 nacks close the dispatch gates, while every remaining already-dispatched position is still accepted, so the tracker can grow to `N`. Even with the default limits, the overshoot can approach the per-subscription unacknowledged-message limit rather than remain only “somewhat” above 50,000.
The overflow predicate also needs to preserve the earlier `position <= earliestNackPosition` progress rule. If position 20 is the earliest tracked nack for hash `H` and an earlier position 10 enters replay after a disconnect, rejecting position 10 can mark `H` as blocked before position 20 is selected. Neither position can then make progress, so capacity cannot recover.
It would help to define the actual resource bound and progress predicate together. If this value is intentionally a soft dispatch threshold, narrowing the bounded-state claim and retaining the `<= earliest` rule would make the contract clearer. A strict bound would require capacity to be accounted for before messages become already dispatched.
##########
pip/pip-493.md:
##########
@@ -0,0 +1,2320 @@
+# PIP-493: Key-ordered negative acknowledgement for Key_Shared subscriptions
+
+# Background knowledge
+
+## Key_Shared subscriptions and the ordering contract
+
+A Key_Shared subscription allows multiple consumers to consume from one subscription in parallel while
+messages that share the same key are processed in order. The broker maps each message's *sticky key*
+(the ordering key, or the partition key when no ordering key is set — `Commands#resolveStickyKey`) to a
+16-bit *sticky key hash*, and maps hash ranges to consumers.
+
+[PIP-379](pip-379.md) (Pulsar 4.0) defined the ordering contract as an invariant:
+
+> In Key_Shared subscriptions, messages with the same key are delivered and allowed to be in an
+> unacknowledged state to only one consumer at a time.
+
+PIP-379 also documented an explicit carve-out, which is the subject of this proposal:
+
+> The Key_Shared subscription doesn't prevent using any methods in the consumer API. For example, the
+> application might call `negativeAcknowledge` or the `redeliverUnacknowledgedMessages` method. When
+> messages are scheduled for delivery due to these methods, they will get redelivered as soon as
+> possible. There's no ordering guarantee in these cases, however the guarantee of delivering a message
+> key to a single consumer at a time will continue to be preserved.
+
+## One key per entry
+
+The broker resolves the sticky key once per **entry**, from the entry-level `MessageMetadata` only:
+`Commands#resolveStickyKey` never descends into `SingleMessageMetadata`, and a batched entry is
+dispatched whole to a single consumer. The producer stamps that entry-level key from the *first* message
+added to the batch (`Commands#initBatchMessageMetadata`), so a producer that puts several distinct keys
+into one entry has all of them dispatched under the first message's key, and the Key_Shared contract does
+not hold for the keys that ride along.
+
+**Producers on a Key_Shared topic must therefore disable batching or use `BatcherBuilder.KEY_BASED`.**
+That is a condition of the existing contract rather than something this proposal introduces:
+[PIP-460](pip-460.md) states it outright, and [PIP-486](pip-486.md) describes it as the producer-consumer
+coupling it exists to remove. Nothing enforces it, and no javadoc on `BatcherBuilder`, `ProducerBuilder`
+or `KeySharedPolicy` states it, which is why it is named here rather than assumed: this proposal reasons
+throughout on the basis that **one entry carries one sticky key**, and a mixed-key entry is outside this
+guarantee exactly as it is outside today's.
+
+What that buys is used repeatedly below. The replay queue, `PendingAcksMap` and the redelivery count are
+all keyed by position, so the *entry* is the only granularity the broker has; under this precondition it
+is also key-precise, and no rule here has to reason about the individual messages inside an entry.
+
+## The Key_Shared dispatcher mechanics that this proposal builds on
+
+Four existing mechanisms matter, all in `PersistentStickyKeyDispatcherMultipleConsumers` and its base
+class:
+
+1. **The replay queue** (`MessageRedeliveryController`, field `redeliveryMessages`). Positions that must
+ be redelivered are held here. For ordered Key_Shared subscriptions the controller also indexes each
+ position's sticky key hash, and `containsStickyKeyHash(hash)` answers "is some message with this hash
+ waiting for redelivery?".
+2. **Three dispatch gates, not one.** A message can be withheld from a consumer at three independent
+ points, and any new blocking rule has to be applied at all three:
+ - `canDispatchEntry` — the per-entry check on a normal read;
+ - `ReplayPositionFilter` — the filter that selects positions from the replay queue before entries are
+ read from storage;
+ - `handleAddingPendingAck` — the send-time recheck reached through
+ `PendingAcksMap#addPendingAckIfAllowed`, which PIP-379 added specifically to close the race between
+ a consumer-set change and a send that is already in progress. Note that the shipped method tests
+ only the draining hash; the replay-index test that appears in the PIP-379 document was removed
+ during its implementation. PIP-493's retrying-hash test will therefore be the only ordering guard at
+ this gate, which is a further reason not to omit it.
+3. **Pending acknowledgements** (`PendingAcksMap`). For each dispatched-but-unacknowledged message the
+ broker keeps `(ledgerId, entryId) -> (remainingUnacked, stickyKeyHash)`. Full removals invoke a
+ `PendingAcksRemoveHandler` callback, which is how PIP-379 keeps `DrainingHashesTracker` in sync
+ without embedding that logic into `PendingAcksMap`. Partial acknowledgement of batch indexes goes
+ through `updateRemainingUnacked`, which mutates the packed value in place and does **not** invoke the
+ callback.
+4. **Draining hashes** (PIP-379). When hash ranges change, hashes with messages still pending at the
+ previous consumer are marked *draining* and withheld from the new consumer until the previous
+ consumer has acknowledged them. They are what the current dispatcher has in place of the *recently
+ joined consumers* read-position tracking that [PIP-282](pip-282.md) redefined and that only the
+ classic dispatcher still carries — which is one reason the classic dispatcher is a different ordering
+ regime and is out of scope here.
+
+## How negative acknowledgement works today
+
+`Consumer#negativeAcknowledge` is entirely a client-side facility. `NegativeAcksTracker` stores the
+message id together with a redelivery timestamp computed from `negativeAckRedeliveryDelay` or from the
+configured `RedeliveryBackoff`, and groups nacks by trimmed timestamp so that many of them travel in one
+command. A timer fires when the delay elapses, and only *then* does the client send
+`CommandRedeliverUnacknowledgedMessages`. Until that moment the broker knows nothing: the message
+remains in the consumer's `PendingAcksMap` and counts towards the unacknowledged-message limits, exactly
+as any other in-flight message.
+
+Two consequences follow, and both are visible in the code today:
+
+- For the whole retry delay the broker keeps dispatching later messages with the same key to the
+ consumer, because nothing has told it not to.
+- The sticky key hash is dropped on the redelivery path. `Consumer#redeliverUnacknowledgedMessages(List<
+ MessageIdData>)` builds a `List<Position>`, and `PersistentDispatcherMultipleConsumers#
+ redeliverUnacknowledgedMessages(Consumer, List<Position>)` calls the two-argument
+ `addMessageToReplay(ledgerId, entryId)`, which calls `redeliveryMessages.add(ledgerId, entryId)`
+ without a hash. The position is therefore not indexed by hash, `containsStickyKeyHash` will not report
+ it, and later messages with the same key are not withheld. The code carries a `TODO` acknowledging
+ this:
+
+ ```java
+ // TODO: We want to pass a sticky key hash as a third argument to guarantee the order of the messages
+ // on Key_Shared subscription, but it's difficult to get the sticky key here
+ ```
+
+ The hash is available where it is discarded: `PendingAcksMap#removeAndGetRemainingUnacked` already
+ reads it out of the packed value.
+
+# Motivation
+
+Key-ordered processing exists because processing events for one entity out of order corrupts state or
+triggers wrong actions. The most common reason a consumer cannot process a message *right now* is a
+transient failure of a downstream dependency: an HTTP 503, a database failover, a rate limit. The
+natural tool for "try this again in a moment" is `negativeAcknowledge`.
+
+On a Key_Shared subscription that tool is currently unusable when ordering matters:
+
+1. **Negative acknowledgement reorders the key.** Two keys are in flight, `A` and `B`, delivered
+ interleaved: `A1, B1, A2, B2, A3, B3`. The application nacks `A1`; `A2` and `A3` are already in the
+ consumer's receiver queue and are processed; `A1` is redelivered afterwards and processed last.
+ Ordering for key `A` is violated, silently. `B1, B2, B3` are unaffected and should be — the failure
+ had nothing to do with them, and a mechanism that stopped them would trade one problem for
+ another.
+2. **The alternatives are worse.** Routing the failed message to a dead letter topic leaves a permanent
+ gap in the key's sequence, and re-injecting it in the right place later is generally not possible.
+ Blocking the consumer thread until the downstream recovers stalls every other key handled by that
+ consumer.
+3. **Application-level workarounds do not have the tools to be safe.** An application can keep the
+ failed message and buffer later messages for the same key itself, but it cannot stop the broker from
+ dispatching more messages for that key. Under a sustained outage the buffer grows without bound and
+ the consumer's permits are consumed by messages it cannot process.
+
+Point 3 is why this cannot be solved in the client library alone: only the broker can stop dispatching
+messages for a key, and the current protocol has no way to tell it to.
+
+# Goals
+
+## In Scope
+
+- Preserve key ordering across negative acknowledgement on Key_Shared subscriptions with ordering
+ enabled, in both AUTO_SPLIT and STICKY mode: after a message is negatively acknowledged, no later
+ message with the same key reaches any application before that message has been acknowledged. (The
+ broker withholds by sticky key hash, so *newly dispatched* messages for keys colliding with the nacked
+ one are withheld as well. Colliding-key messages already inside the consumer are unaffected — see
+ [Two halves](#two-halves-because-the-messages-are-in-two-places).)
+- Keep the resource cost bounded for the whole duration of a downstream outage, on both sides, without
+ introducing any new unbounded or client-controlled broker state.
+- Leave the existing negative acknowledgement retry delay, `RedeliveryBackoff` and grouping behaviour
+ exactly as they are.
+- Pause delivery entirely, client-side, when the application is failing regardless of key, so that a
+ broad downstream failure is answered by stopping flow permits rather than by as many concurrent retry
+ cycles as there are active keys (see
+ [Client: broad-failure delivery pause](#client-broad-failure-delivery-pause)).
+- Keep the mechanism inert when it is not in use: no new state is held while no message is in a retry
+ cycle, and the work left on the idle path is constant-time and enumerated here — the per-add
+ `PendingAcksMap` callback that ordered Key_Shared installs in both modes, a single test against an
+ empty map at each of the three broker dispatch gates, and one `isEmpty()` check per delivered message
+ on the client. An AUTO_SPLIT subscription already pays that callback cost for draining hashes; for a
+ STICKY subscription it is new, and all of it is paid whether or not anything is ever negatively
+ acknowledged.
+- Make a stuck subscription diagnosable: how many hashes are withholding messages, and how many positions
+ the broker is tracking. Not which message is blocking each hash — the application that negatively
+ acknowledged a message still holds it, so the broker owes the operator magnitude and duration rather
+ than identity.
+- Degrade safely. Where the guarantee cannot apply, the behaviour falls back to today's, never to a
+ stall. The exception is the explicit opt-in `OrderedNegativeAckMode.REQUIRED`, which fails loudly
+ rather than degrading, because an application that asked for the property should learn from the client
+ that it is absent, not from its data. Ordered processing admission, the other explicit opt-in, fails
+ loudly only for client-side misconfiguration; it produces no failure of its own where the broker
+ capability is missing, and follows the mode instead — beside the default `BEST_EFFORT` that is the
+ typed per-message `ADMITTED_WITHOUT_GUARANTEE`, which is degradation the application is told about
+ rather than a stall or a silent reorder. See [Public API](#public-api).
+
+## Out of Scope
+
+- Ordering guarantees for `redeliverUnacknowledgedMessages()`, acknowledgement timeout redelivery, dead
+ letter topics and retry letter topics. These remain as documented by PIP-379.
+- Shared, Exclusive and Failover subscriptions. Their negative acknowledgement behaviour is unchanged,
+ and the Java client does not use the new command for them.
+- Key_Shared subscriptions created with `KeySharedPolicy#setAllowOutOfOrderDelivery(true)`; the classic
+ Key_Shared dispatcher (`subscriptionKeySharedUseClassicPersistentImplementation=true`); and
+ [PIP-486](pip-486.md) entry-bucket dispatch (`KeySharedMeta.entryBucketDispatch`), where the
+ dispatch unit is a producer-stamped entry bucket spanning many keys rather than a key hash.
+- Messages with neither an ordering key nor a partition key, and chunked messages. See
+ [General Notes](#general-notes) for why each is excluded and how each could be added later.
+- Non-persistent topics, which have no redelivery.
+- Clients other than the Java client. The protocol change is additive; other clients may adopt it later
+ by implementing the [client conformance requirements](#client-conformance-requirements).
+- Detecting, rejecting or reporting batch entries that mix several distinct keys. Such entries fall
+ outside the [one key per entry](#one-key-per-entry) precondition and outside this guarantee, exactly as
+ they fall outside today's.
+
+# High Level Design
+
+## The invariant
+
+PIP-493 replaces the negative acknowledgement carve-out in the PIP-379 contract with a guarantee:
+
+> **On a Key_Shared subscription with ordering enabled, when a message is negatively acknowledged, no
+> *later* message with the same key is delivered to any application until that message has been
+> acknowledged.**
+
+The word "later" is load-bearing: the negatively acknowledged message is itself a message with that key,
+and redelivering it is the whole point. "Later" means later in position order within the subscription.
+
+The wording for `redeliverUnacknowledgedMessages` is unchanged: that method still carries no ordering
+guarantee.
+
+## Two halves, because the messages are in two places
+
+At the moment of the nack, the messages that must not reach the application live in two places:
+
+- Messages the broker has **not yet dispatched**. Only the broker can withhold these, and it must,
+ because otherwise they accumulate somewhere for the whole outage.
+- Messages **already inside the consumer**. The broker cannot recall them — they are on the wire, in the
+ receiver queue, or already queued on a listener executor. Only the client can deal with these.
+
+So the design has two mechanisms:
+
+| | Broker: *retrying hashes* | Client: *keys awaiting retry* |
+|---|---|---|
+| Unit | sticky key hash | sticky key bytes |
+| Withheld | positions strictly later than that hash's earliest outstanding nacked position | positions strictly later than that key's earliest outstanding nacked position |
+| Effect | withholds dispatch to any consumer | **returns** the message to the broker instead of delivering it |
+| Set by | the nack command | `negativeAcknowledge(Message)` |
+| Cleared by | acknowledgement of the nacked message | acknowledgement of the nacked message, with self-healing fallbacks |
+
+**One rule, applied at three places.** The *Withheld* row is deliberately the same rule on both sides,
+and the admission rule of `acquireForOrderedProcessing` (see [Public API](#public-api)) is the third
+instance of it: a message is withheld exactly when an *earlier* position of the same key is still
+unresolved, and it
+is delivered when it is at or before that position. The three differ only in what each place can see —
+the broker evaluates it over the negatively acknowledged positions of a *hash*, because the key bytes are
+not in its hands at the gates; the client's guard evaluates it over the negatively acknowledged positions
+of a *key*; and admission evaluates it over every undisposed copy of a key, because the application may
+hold several. Stating it once here is worth doing, because the alternative shape — a predicate over the
+*set* of guarded keys — is wrong in the same way at all three: it refuses positions *earlier* than the
+negatively acknowledged one, which the invariant never asked for. On the broker that wedges permanently
+(see [Broker: retrying hashes](#broker-retrying-hashes)); in the client it disarms a live guard (see
+[Client: keys awaiting retry](#client-keys-awaiting-retry)); in the application it teaches exactly the
+reordering the feature exists to prevent (see [Alternatives](#alternatives)).
+
+**The two units differ deliberately, and the client's is the finer one.** When key `A` is nacked, a
+message already inside the consumer that belongs to key `C` — a distinct key whose hash collides with
+`A`'s — is *not* returned: it is delivered and processed normally. Only newly dispatched `C` messages are
+withheld, by the broker, once it has the command. So a nack costs a colliding key its future throughput
+for the duration of the outage, but never the work already in the consumer's hands.
+
+That is sound rather than merely convenient, and the reason is worth stating because it is not obvious.
+Consumer selection is a pure function of the hash, so `A` and `C` always resolve to the *same* consumer,
+whose receiver queue is FIFO. The set of `C` messages inside the client at the moment of the nack is
+therefore exactly what the broker had already dispatched — a position-ordered **prefix** of the
+outstanding `C` stream — and everything the broker *withholds* is strictly later in position order than
+the nacked position. Delivering the prefix while withholding the remainder preserves `C`'s order. Every
+broker-side gate is hash-coarse, i.e. a superset of the key-precise set, so the error direction is always
+over-withholding, never under-withholding.
+
+What is *not* true, and is the reason all three of those rules are position-ordered rather than phrased
+over a set of keys, is that everything arriving after the nack is later than it. An earlier position of
+the same hash — the same key, or a colliding one — can still be dispatched afterwards: when a consumer
+disconnects, its pending acknowledgements are re-added to the replay queue with their hashes and replayed
+*ahead* of the nacked position, in order, to whichever consumer now owns the hash; and the legacy
+hash-less replay path leaves earlier positions in the queue that no hash index withholds at all. The
+withholding rule dispatches such a position deliberately, and the client delivers it for the same reason.
+That is correct rather than an exception: the message is earlier than everything the guard is protecting,
+nothing the broker withholds stands in front of it, and returning it would only send it straight back —
+the broker does not withhold it, so it would arrive again, and a client that treated its own return as
+evidence would disarm a guard whose hash is still retrying. The messages the client returns are the
+later ones, and only those.
+
+This rests on the `returned` list being key-precise. Returning by hash instead would pull a colliding
+key's messages back out of the client's ordered stream and break the prefix property, which is why
+conformance rule 8 is written in terms of "that key". Returning at *entry* granularity — the only unit the
+replay queue has — stays key-precise, because [one entry carries one key](#one-key-per-entry).
+
+That precondition is load-bearing one step earlier as well: "consumer selection is a pure function of the
+hash" is, for a batched message, a function of its *entry's* key rather than its own.
+
+The client **returns** messages rather than holding them. This is the central decision, and it is what
+makes the design safe: a message held inside the client is still recorded in that consumer's
+`PendingAcksMap`, so the broker believes it is being processed. If the hash is then reassigned, PIP-379
+marks it draining until the previous consumer acknowledges those messages — while the client refuses to
+hand them to the application until the nacked message is acknowledged, which cannot happen until the
+draining hash releases. That is a circular wait that nothing but an acknowledgement timeout breaks.
+Returning the messages removes them from `PendingAcksMap` and dissolves the cycle. It also removes the
+need for any client-side buffer, its memory accounting, and its interaction with permits and the
+acknowledgement timeout tracker.
+
+Returning reuses existing, proven machinery on the parts that matter most:
+`ConsumerImpl#redeliverUnacknowledgedMessages(Set<MessageId>)` already takes messages out of
+`incomingMessages`, releases them, corrects the incoming-message size accounting and restores the
+permits, and it is the model the return path follows. What it does not already do is find them. It
+drains through `GrowableArrayBlockingQueue#pollIf`, which tests only the element at the head and returns
+null at the first non-match, so it reclaims a matching *prefix* of the receiver queue and nothing behind
+it. For the nacked key's own messages sitting at the head that is exactly right; collecting a key's
+messages scattered through the queue is new work, and a predicate sweep over the whole queue rather than
+its head is the part this design adds. The other new part is on the broker: it must not count a returned
+message as a redelivery, because the application never saw it — otherwise `RedeliveryBackoff` escalates
+and the dead letter topic eventually swallows messages nobody ever tried to process.
+
+## The nack becomes an immediate signal, and nothing else moves
+
+The one structural change is *when* the broker is told. A new `CommandNegativeAck` is sent at nack time
+and carries two lists: the negatively acknowledged messages, and the messages the consumer is returning
+unprocessed. It carries **no delay**. The retry delay, `RedeliveryBackoff`, the grouping window and the
+existing `CommandRedeliverUnacknowledgedMessages` that the timer eventually sends all stay exactly where
+they are today.
+
+That is deliberate. Moving the retry deadline to the broker so that one command could do everything was
+considered and rejected, for three reasons that only became visible once the consequences were followed
+through:
+
+- A broker-side deadline requires the broker to drop the message from `PendingAcksMap` at nack time, so
+ the message escapes `maxUnackedMessagesPerConsumer` / `maxUnackedMessagesPerSubscription` accounting
+ while occupying broker state for a client-chosen duration. That is a new denial-of-service lever.
+- `RedeliveryBackoff` produces a *different* delay per message, so a single per-command delay is not
+ expressive enough, and a per-message delay on the wire also has to specify how the grouping window and
+ network transit are subtracted from it.
+- It needs a scheduler, a clamp, saturating deadline arithmetic, and a defined lifecycle across consumer
+ disconnect, cursor reset and topic unload.
+
+Leaving the timer on the client removes all of that. The nacked message stays in `PendingAcksMap`
+exactly as it does today, so it stays inside the existing unacknowledged-message accounting, and the
+broker gains no timer at all.
+
+The `negative_acked` entries carry one further thing, and it costs no schema change. Batch index
+acknowledgement is enabled by default, so a batched entry can already be partly acknowledged when one of
+its messages is negatively acknowledged, and the broker needs the batch dimension to know when that entry
+is resolved. A `negative_acked` entry therefore populates the existing `MessageIdData.batch_index` — the
+index that was negatively acknowledged — and the existing `MessageIdData.ack_set` — the client's current
+bitmap of the indexes of that entry that are **still unacknowledged**. That is the polarity `ack_set`
+already has on the wire: every index of a batch starts with its bit set, acknowledging an index *clears*
+that bit, and an entry is fully acknowledged when the bitmap is empty. This document uses that wire
+encoding everywhere it names `ack_set`; where the prose is clearer talking about the acknowledged
+indexes it says so explicitly rather than switching silently. Both fields are already on `MessageIdData`,
+so this is new semantics on an existing message rather than a protobuf schema change. The `ack_set` is a
+diagnostic cross-check, which the broker may log on mismatch and otherwise ignores; it is never treated
+as an acknowledgement, and nothing on the nack path writes acknowledgement state. See
+[Broker: retrying hashes](#broker-retrying-hashes) for how the broker resolves an entry's indexes from
+its own state, and [Client conformance requirements](#client-conformance-requirements) for the
+acknowledgement flush that makes that state at least as new as the client's.
+
+## Lifecycle
+
+```mermaid
+sequenceDiagram
+ participant App as Application
+ participant Cn as Consumer (client)
+ participant B as Broker (Key_Shared dispatcher)
+
+ B->>Cn: deliver A1, B1, A2, B2, A3, B3 (keys A and B, interleaved)
+ Cn->>App: A1
+ App->>Cn: negativeAcknowledge(A1)
+ Note over Cn: key A awaits retry
+ Cn->>B: NegativeAck(negative_acked=[A1], returned=[A2, A3])
+ Note over B: hash(A) is retrying.<br/>A2, A3 into the replay queue,<br/>not counted as redeliveries
+ Cn->>App: B1, B2, B3
+ Note over App: key B is untouched:<br/>its messages are delivered<br/>and processed in order throughout
+ B--xCn: no further dispatch for hash(A) —<br/>including future messages of key C,<br/>a distinct key whose hash collides with A's
+ Note over Cn: retry delay elapses (unchanged client timer)
+ Cn->>B: RedeliverUnacknowledged([A1])
+ B->>Cn: deliver A1
+ Note over Cn: A1 is one of this consumer's own<br/>nacked messages, so it is delivered,<br/>not returned — but key A still awaits retry
+ Cn->>App: A1
+ App->>Cn: acknowledge(A1)
+ Note over Cn: key A no longer awaits retry
+ Cn->>B: Ack(A1)
+ Note over B: hash(A) no longer retrying
+ B->>Cn: deliver A2, A3, then A4, A5 ..., and key C again
+ Cn->>App: A2, A3, ...
+```
+
+If the application nacks `A1` again instead of acknowledging it, the hash simply stays retrying and the
+cycle repeats. Nothing accumulates while it does: the broker dispatches nothing for that key, so the
+only messages the client ever has to return are the ones that were already in flight when the first nack
+happened. Key `B` is unaffected throughout — that is the difference from a client-only solution — and key
+`C` pays only for the collision, in future dispatch and never in the work already in the consumer's
+hands.
+
+# Detailed Design
+
+## Design & Implementation Details
+
+### Broker: retrying hashes
+
+A hash is **retrying** while at least one negatively acknowledged message with that hash has not been
+acknowledged. A new per-dispatcher component in `PersistentStickyKeyDispatcherMultipleConsumers` tracks
+this, alongside `DrainingHashesTracker`:
+
+- **State**: `stickyKeyHash -> ordered set of negatively acknowledged positions`. The set normally holds
+ one position; it holds more only when an application has several messages for one key in flight and
+ nacks more than one.
+- **Blocking**: an entry whose hash is retrying is withheld if and only if its position is **strictly
+ later** than the earliest position in that hash's set. The earliest nacked position is dispatched —
+ that is the retry — and so is anything before it.
+
+ The rule is stated in terms of position order rather than set membership, and the difference matters.
+ Withholding everything except the earliest nacked position looks equivalent and is not: it also
+ withholds positions *earlier* than the nacked one, which the invariant never asked for, and that
+ wedges permanently. A consumer can hold an earlier unacknowledged position with the same hash — the
+ same key, or merely a colliding one — and when that consumer disconnects, its whole pending-ack map is
+ re-added to the replay queue *with* hashes. The replay filter then meets the earlier position first,
+ withholds it, and records the hash in its per-pass blocked set; the exempt position is short-circuited
+ by that set before the exemption is ever consulted, so it is never dispatched, never acknowledged, and
+ never releases the hash that is blocking the position in front of it. Ordering by position dissolves
+ this: the earlier position replays ahead of the nacked one, in order, and the hash still withholds
+ everything after it. It also preserves what the earliest-only formulation was introduced for — a
+ second negatively acknowledged position of the same key is later than the first, so it stays withheld
+ until the first resolves.
+
+ (This does not rescue chunked messages: every chunk after the first is later than the earliest, so the
+ chunk wedge described in [General Notes](#general-notes) stands and the exclusion remains.)
+
+ The rule is applied at **all three** dispatch gates listed in Background — `canDispatchEntry`,
+ `ReplayPositionFilter`, and the send-time `handleAddingPendingAck`. Omitting the third would leave exactly
+ the race PIP-379 introduced that recheck to close: a send already in progress when the nack arrives.
+
+ Two details of *how* it is applied are easy to get wrong and are part of the design. The test in
+ `canDispatchEntry` must run for **both** read types: the pre-existing `containsStickyKeyHash` test
+ beside it is gated on `ReadType.Normal`, and a retrying test gated the same way would be bypassed by
+ exactly the replay that carries the redelivered message and its successors. And `ReplayPositionFilter`
+ cannot obtain a position's hash from the replay queue's index, which returns nothing for the hash-less
+ inserts that the legacy path produces — which is precisely how a nacked message re-enters the replay
+ queue once its retry has been requested. The tracker must therefore hold a `position -> hash` lookup of
+ its own alongside `stickyKeyHash -> ordered set of positions`, so the filter can recognise the exempt
+ position rather than waving it through.
+
+ The third gate needs care, because its contract differs from the other two. `canDispatchEntry` and
+ `ReplayPositionFilter` are predicates whose callers re-queue the rejected entry;
+ `handleAddingPendingAck` must re-queue the entry itself, because its caller in `Consumer#sendMessages`
+ drops and releases it outright. Applying the retrying rule there as a plain predicate would silently
+ lose the message. The nacked position must be exempt at this gate too — otherwise the one message the
+ mechanism exists to deliver is the one that can never be sent.
+
+ Both `PendingAcksMap` handlers are installed together today, and only when `drainingHashesRequired` is
+ true, which excludes STICKY Key_Shared. The add handler is the one that reaches this gate; the remove
+ handler drives *draining-hash* release and nothing else — its `handleRemoving` calls
+ `DrainingHashesTracker#reduceRefCount` (`PersistentStickyKeyDispatcherMultipleConsumers.java:176-192`). What
+ this proposal needs installed for ordered Key_Shared subscriptions in **both** modes is therefore the
+ **add handler**, and only it. STICKY does not need draining hashes, because its ranges do not move, but
+ it does need retrying hashes, and its users — who pin keys to instances precisely because ordering
+ matters to them — are among those most likely to want them. The cost is the per-add callback that
+ AUTO_SPLIT subscriptions already pay.
+
+ The remove handler stays what it is today: a draining-hash mechanism, installed in AUTO_SPLIT alone.
+ The retrying tracker takes **no** removal callback at all. Its release signal is on the subscription's
+ acknowledgement path, for the reason the *Release* bullet below gives, and a non-closing removal
+ carries nothing that path does not — it fires on the retry request as readily as on an acknowledgement,
+ which is exactly why it cannot be the signal.
+- **Precedence with draining hashes**: the two rules are independent and both must pass. A retrying-hash
+ exemption exempts a position only from the *retrying* rule; if the hash is also draining, PIP-379 wins
+ and the message waits. The nacked message stays in `PendingAcksMap` until its redelivery is requested,
+ so it keeps its own hash draining-consistent, and the previous consumer's returned messages have
+ already left `PendingAcksMap` — which is what prevents a circular wait.
+- **Registration**: the nack command must register the retrying hashes and remove the returned positions
+ from `PendingAcksMap` as one synchronized step with respect to dispatch, so that no send can observe
+ neither the old pending acknowledgement nor the new retrying hash. Registration accepts a position only
+ while the sending consumer still holds it in its `PendingAcksMap`; that precondition is what ties the
+ tracker's intake to the unacknowledged-message accounting, and without it the tracker would be the one
+ structure in the design with no server-side gate on its position count. A position that fails it is
+ **skipped as an idempotent per-position no-op**, in the same terms the `returned` list already uses:
+ the command's remaining positions are still processed, the command never fails, and the connection is
+ never closed. That is a clarification of the precondition rather than a weakening of it — a nack racing
+ a disconnect is a designed-for case, and a client that batches several keys into one command must not
+ lose the well-behaved positions along with the stale one. That precondition is forced rather than
+ chosen: the broker cannot recompute a sticky key hash from a message id, and `PendingAcksMap` is the
+ only structure holding `(position -> hash)` for a dispatched message — so a read accessor must be added
+ there. What it offers today is a whole-map traversal: `PendingAcksMap#forEach` is public and hands the
+ sticky key hash of every entry to a processor without removing anything, which is what the draining-hash
+ scan (`PersistentStickyKeyDispatcherMultipleConsumers.java:202`) and
+ `PersistentDispatcherMultipleConsumers#redeliverUnacknowledgedMessages(Consumer, long)`
+ (`PersistentDispatcherMultipleConsumers.java:1142`) already use. What is missing is a **per-position**
+ hash lookup, which is what registration needs. What stops a stale nack from registering once its
+ consumer is gone is that precondition, and it is worth saying which mechanism satisfies it in which
+ case, because the two disconnect paths differ. When
+ **other consumers remain**, `removeConsumer` drains the departing consumer's pending acknowledgements
+ through `PendingAcksMap#forEachAndClose`, which closes the map to further entries: the precondition can
+ never be met again, and the closed map is a genuine fence. When the **last** consumer disconnects the
+ map is neither closed nor cleared — that path takes `clearComponentsAfterRemovedAllConsumers` instead —
+ and it needs no fence, for the reason the *Lifecycle* bullet below gives: the same path clears the
+ replay queue and the tracker, and the next consumer to arrive rewinds the cursor, so every position
+ reverts to an ordinary unread one and there is nothing left for a late registration to be about.
+ Registration is idempotent: a second nack of a position already in the set is a no-op rather than an
+ error, which is what makes repeated nacks of the same message well defined. Registration skips the
+ `NONE_KEY` marker's hash, which a message reaches only when its metadata cannot be parsed. Note that
+ this does *not* implement the exclusion of keyless messages described in
+ [General Notes](#general-notes): `resolveStickyKey` falls back to a producer-name/sequence-id key
+ before `NONE_KEY`, so by the time the broker sees a hash it cannot tell a keyless message from a keyed one.
+ That exclusion is necessarily client-side.
+
+ Registration also snapshots, in the same synchronized step, the entry's unresolved **batch-index**
+ state. `PendingAcksMap` packs `remainingUnacked`, which says how many of the entry's messages are still
+ outstanding but not which ones, so the tracker materialises the unresolved indexes as a bitmap from the
+ broker's own batch-index acknowledgement state for that position; the client-sent `ack_set` is
+ cross-checked against it and is never a source of truth. That bitmap carries the same polarity as
+ `ack_set` — a set bit is an index that is still unacknowledged — and it composes with an arriving
+ `ack_set` the way the cursor already composes them, by intersection: `ManagedCursorImpl` merges an
+ incoming `ack_set` into the stored one with `and` and deletes the entry once the result is empty. So
+ "clear the bits an acknowledgement resolves" and "intersect the bitmap with the acknowledgement's
+ `ack_set`" are the same operation, and the tracker's release condition — the unresolved set is empty —
+ is the same condition under which the cursor deletes the entry. The tracker **retains** that per-entry
+ bitmap after the retry request later removes the entry from `PendingAcksMap`. Retention is what makes
+ release possible at all: once the retry has been requested there is no pending acknowledgement left to carry
+ the state, and an acknowledgement arriving after that moment must still find something to resolve.
+- **Release**: a position leaves the set when every index it holds has been acknowledged. **This needs a
+ new, acknowledgement-specific signal; the existing `PendingAcksRemoveHandler` cannot carry it.** That
+ callback fires for every removal from `PendingAcksMap`, and the client's own redelivery request removes
+ the nacked position through the same method as an acknowledgement — `removeAndGetRemainingUnacked`,
+ reached from the ack path and from `redeliverUnacknowledgedMessages` alike — with the same arguments
+ and the same `closing=false`. A tracker that released on that callback would release on the retry
+ request, which is the one moment it must not.
+
+ The signal is therefore taken on the **subscription's acknowledgement path**, keyed by position and
+ independent of `PendingAcksMap` membership, and it clears bits from the entry's unresolved-index bitmap
+ rather than decrementing a counter. It must fire for all four ways an index is genuinely resolved:
+ acknowledgement of individual batch indexes, which already travels this very path with its `ack_set`
+ attached to the position — `Consumer#individualAck` calls `subscription.acknowledgeMessageAsync`
+ (`Consumer.java:699`) on the `nonTxnPositions` it assembles with `buildPosition` (called at `:663`,
+ body at `:771-786`), and those positions carry the ack set, built by
+ `AckSetStateUtil.createPositionWithAckSet`; acknowledgement of the whole entry; the cursor's
+ mark-delete position advancing past it, which covers cumulative acknowledgement, message expiry and
+ administrative skips; and the **commit** of a transactional acknowledgement. It must **not** fire for a
+ removal caused by redelivery, at either granularity. When the entry's bitmap is empty its position leaves
+ the set, and when the set becomes empty the hash stops retrying and the existing batched unblock
+ notification (`keySharedUnblockingIntervalMs`, `RescheduleReadHandler`) schedules a read.
+
+ `PendingAcksMap#updateRemainingUnacked` is not that signal and must not be mistaken for it. It is the
+ per-consumer unacknowledged-count bookkeeping applied *after* the acknowledgement has been handed to
+ the subscription (`Consumer.java:733-745`), it mutates the packed value in place, and it invokes no
+ callback at all — which is exactly why a release signal anchored on `PendingAcksMap` cannot see a
+ batch-index acknowledgement, and why the signal is taken on the acknowledgement path instead.
+
+ Two properties of that shape are load-bearing. *Resolution is idempotent*, because it is a bitmap and
+ never a scalar decrement: a duplicate or reordered acknowledgement command clears an already-clear bit
+ and changes nothing, where a decrement would double-release and let the key run ahead of its own nacked
+ message. And *nothing on the nack path ever writes acknowledgement state* — no cursor mutation, no
+ synthesized acknowledgement. "The indexes before the nacked one are acknowledged" is something the
+ broker **observes** in its own state, made current by the client's flush before the command (see
+ [Client conformance requirements](#client-conformance-requirements)), and never something the broker
+ assumes or applies. If the application violated the in-order processing discipline and an earlier index
+ is genuinely unacknowledged at the broker, the bitmap stays non-empty and the hash simply stays
+ retrying until real resolution arrives: over-withholding, never loss.
+
+ **A transactional acknowledgement releases the position only on commit.** The broker removes the
+ pending acknowledgement when the transactional ack is processed, before the transaction's outcome is
+ known, and `PendingAckHandleImpl` replays the transaction's positions if it aborts. Treating that
+ removal as final would release the hash, let the next message for the key be dispatched, and then
+ replay the nacked message behind it. The tracker must therefore **keep** the position across that
+ removal and **release** it at commit — not re-register it. There is nothing to re-register: the
+ position never left the tracker. Re-registration is not even available, because registration accepts a
+ position only while the sending consumer still holds it in its `PendingAcksMap`, which a committed
+ transactional acknowledgement no longer does. The same holds index by index: a transactional
+ acknowledgement of individual batch indexes clears their bits only at commit, and an abort leaves them
+ set, so a transaction that never commits cannot release a partly acknowledged entry.
+
+ This needs no commit-side hook of its own, and the reason strengthens the rule rather than merely
+ saving work. `PendingAckHandleImpl`'s commit paths acknowledge through
+ `persistentSubscription.acknowledgeMessageAsync` (`PendingAckHandleImpl.java:470`, `:780` and `:800`)
+ — the subscription acknowledgement path this design already places the release signal on, and a path
+ that reaches the dispatcher today. Commit is thus the only moment a transactionally acknowledged
+ position reaches that path at all, so the release can fire nowhere else: "release only on commit" is a
+ property of where the signal is taken rather than a rule an implementation has to remember to enforce.
+ The abort side needs nothing either: the position never left the tracker, and the existing abort
+ replay is enough.
+
+ While the outcome is pending the position is in the tracker but in neither `PendingAcksMap` nor the
+ replay queue, so it is the earliest and nothing for that hash can be dispatched. That is correct, and
+ it is worth naming as the longest wait in the design: a consumer that acknowledges in a transaction
+ and then dies withholds the key until the transaction times out. Every other wait here is bounded by
+ a retry delay.
+- **Lifecycle**: the tracker holds *positions*. It holds no consumer identity and has no range dimension,
+ and must acquire neither. A position stays in it for exactly as long as it is a negatively
+ acknowledged message of this subscription that has not been acknowledged. Consumer scoping belongs to
+ **registration** and only there; retention is position-scoped and release is acknowledgement-driven.
+
+ *A position is removed only by resolution*: acknowledgement, the mark-delete position advancing past
+ it, or one of the bulk resets that invalidates every position the dispatcher holds — cursor reset or
+ seek, topic unload, and the disconnect of the **last** consumer
+ (`clearComponentsAfterRemovedAllConsumers`). That last case is not merely "runtime state is cleared":
+ the same path clears the replay queue, and the next consumer to arrive rewinds the cursor, so every
+ position reverts to an ordinary unread one and there is nothing left for a retrying entry to be about.
+
+ *Retrying hashes survive the disconnect of one consumer among several — including the consumer that
+ sent the nack.* `removeConsumer` re-adds that consumer's pending acknowledgements to the replay queue
+ **with their sticky key hash** and triggers a read, so a nacked message whose redelivery had not yet
+ been requested becomes immediately deliverable again: it is the earliest position of its hash, and it
+ is replayed to whichever consumer now owns that hash, with no dependence on the client timer that died
+ with the connection. The replay queue is not a substitute for the tracker here. Its hash index
+ withholds only until the position is *dispatched* — replay positions leave `redeliveryMessages` just
+ before `Consumer#sendMessages` — not until it is acknowledged, which is exactly the interval this
+ proposal exists to cover; and `ReplayPositionFilter` accepts later same-hash positions once an earlier
+ one has been accepted, so the nacked message and its returned successors would be selected in one pass
+ and handed together to a consumer whose guard is not armed, which is the original bug. If the retry had
+ already been requested, the position sits in the replay queue *without* a hash, by the legacy path this
+ proposal deliberately leaves alone, and the tracker is then the only ordering guard there is.
+
+ *Retrying hashes survive hash range reassignment, in both modes.* Every gate resolves the target
+ consumer from the selector at decision time, so the exempt position is dispatched to the new owner and
+ the withholding transfers with the range. The *request* side is ownership-independent as well, which
+ the argument below depends on and which is worth stating because it is the opposite of what one
+ expects: `Consumer#redeliverUnacknowledgedMessages(List<MessageIdData>)` accepts a position exactly
+ when the *sending* consumer still holds it in its own `PendingAcksMap`, and consults the selector
+ nowhere; a range change neither moves nor clears pending acknowledgements — that is precisely what
+ makes the hash draining. So a consumer that has lost the range still has its retry honoured, and the
+ position enters the subscription-wide replay queue from which the current owner takes it.
+
+ Draining hashes are not a substitute: a draining entry lasts only from the range change until the
+ nacked message leaves the previous consumer's `PendingAcksMap`, and that boundary *is* the retry
+ request — so the draining guard expires at the instant the retry begins. Draining is also computed from
+ a scan of `PendingAcksMap` taken at the moment of the change, so it cannot see a position whose
+ redelivery has already been requested. And STICKY has no draining machinery at all.
+
+ Implementation note: **discarding on disconnect is what an implementation gets by accident** if it
+ anchors the tracker on `PendingAcksMap` removals. `PendingAcksMap#forEachAndClose` invokes the remove
+ handler with `closing=true` for every drained entry, so a tracker wired there would discard precisely
+ the entries this bullet says survive — the rejected alternative, arrived at by omission. Taking no
+ removal callback at all, which the *Release* bullet requires for its own reason, forecloses it.
+
+Nothing here is persisted. After an unload or a broker restart the nacked messages are simply
+unacknowledged messages, replayed in position order on reconnection, which preserves ordering even
+though the retry delay is lost — the same as today.
+
+### Broker: preserving the sticky key hash on the redelivery path
+
+Positions that `CommandNegativeAck` puts into the replay queue — the `returned` list — carry their
+sticky key hash, taken from `PendingAcksMap` where `removeAndGetRemainingUnacked` already reads it. This
+is the `TODO` quoted in Background, applied on the new path.
+
+It is applied **only** on the new path. The tempting move is to fix the `TODO` everywhere, so that every
+targeted redelivery becomes hash-aware, and that was considered and rejected. It is out of scope: it
+changes behaviour for older clients' negative acknowledgements and for every
+`redeliverUnacknowledgedMessages(Set<MessageId>)` call, which would make this PIP carry an ordering
+change nobody voting on it asked for. PIP-493 needs no such change — a retrying hash is withheld by the
+tracker, not by the replay queue's hash index — so the legacy path keeps today's behaviour and the
+compatibility story stays clean.
+
+The hash-less overload of `Subscription#redeliverUnacknowledgedMessages(Consumer, List<Position>)`
+therefore stays as it is, which is required anyway:
+`MessageRedeliveryController#add(ledgerId, entryId, stickyKeyHash)` throws `IllegalArgumentException`
+when the hash is `STICKY_KEY_HASH_NOT_SET` on the current dispatcher, and at least one caller has no
+hash to give — `PendingAckHandleImpl` replays positions taken from the transaction pending-ack map on
+transaction abort, not from `PendingAcksMap`.
+
+### Broker: bounds
+
+The retrying-hash map has at most one bucket per hash. Every `StickyKeyConsumerSelector` that ordered
+Key_Shared dispatch can use produces hashes in a 65 535-value space — `ConsistentHashing` over
+`[1, 65535]`, the two `HashRange` selectors over `[0, 65535]` with a zero result remapped to 1 — so a
+subscription has at most 65 535 buckets, each keyed by an `int`, and the map is empty in the normal case.
+The tree holds a fourth implementation, [PIP-486](pip-486.md)'s `EntryBucketConsumerSelector`, but it
+serves entry-bucket dispatch, which is already out of scope for this proposal (see
+[Out of Scope](#out-of-scope)); no subscription this proposal applies to selects through it.
+
+The number of *positions* it holds is not bounded by that, and — contrary to what one might assume — it is
+not bounded by the unacknowledged-message limits either. What those limits bound is how many positions can
+be negatively acknowledged *at one instant*: a position enters the tracker only while the sending consumer
+holds it in `PendingAcksMap`, and for ordered Key_Shared the per-consumer limit is enforced before
+dispatch. The bound stops there, because the accounting is refunded *before* the tracker entry is
+released. The unconditional retry request removes the position from `PendingAcksMap` and decrements both
+the per-consumer and the per-subscription counter; the returned positions leave `PendingAcksMap` at nack
+time by design; and a consumer disconnect refunds the subscription counter and moves that consumer's whole
+map into the replay queue. The tracker holds all of them until acknowledgement, which is strictly later.
+A retrying position therefore spends most of its life with no unacknowledged-message accounting behind it,
+and that window is the ordinary retry cycle rather than an edge case. `maxUnackedMessagesPerSubscription`
+never capped a structure in any case: it gates normal reads, and it is checked in an `else if` after the
+replay branch, so a dispatcher blocked on it keeps replaying.
+
+What limits the total is intake. A refund moves a position from `PendingAcksMap` to the replay queue; it
+does not create one. A new tracked position requires a new dispatch, a dispatch of an unread message
+requires a normal read, and normal reads stop once the replay queue reaches the effective look-ahead
+limit. The look-ahead limits still do not cap the replay queue — redelivery requests and consumer
+disconnects add to it unchecked — but gating reads is what throttles growth. They throttle the tracker
+rather than bound it. With defaults that puts the resident state at the order of
+`min(consumers × 50 000, 200 000)` messages in `PendingAcksMap` plus `min(consumers × 4000, 40 000)`
+positions parked in the replay queue. Those two limits are not directly comparable — the replay queue
+counts positions while the unacknowledged counters count messages, batch members individually — but since
+positions ≤ messages, the replay threshold binds first.
+
+The ceiling that survives every configuration is the withholding rule itself. Once a hash is retrying,
+only its earliest position may be dispatched, so that hash accepts no positions beyond those already in
+flight when it became retrying; further growth needs hashes that are not yet retrying, and there are at
+most 65 535 of them. Everything else can be switched off: both unacknowledged limits accept zero, the
+per-consumer limit is zero for non-durable subscriptions whatever the configuration, and the effective
+look-ahead limit falls back to the unacknowledged settings when both thresholds are zero and to
+`Integer.MAX_VALUE` when those are zero too.
+
+The tracker therefore carries a per-subscription ceiling on tracked positions of its own, configured by a
+new broker key `keySharedNegativeAckMaxRetryingPositionsPerSubscription`, default `50000` and dynamic.
+The default sits above the 40 000 default per-subscription replay look-ahead threshold, so it never binds
+in a default configuration; it takes effect only once the throttles above it have been turned off, which
+is exactly the case the previous paragraph describes.
+
+The ceiling is enforced at the **three dispatch gates**, not at registration. While the tracked-position
+count is at or above it, `canDispatchEntry`, `ReplayPositionFilter` and `handleAddingPendingAck` admit
+only the exempt earliest positions of hashes that are already retrying, so nothing that could create a
+*new* tracked position is delivered and the tracker cannot grow. Registration of a negative
+acknowledgement for a message that has already been dispatched is **always** accepted, overflow or not:
+refusing it would let that message's successors through while its own retry is outstanding, which is the
+guarantee itself, and intake at that instant is bounded by the unacknowledged-message limits exactly as
+this section argues above. Recovery needs no intervention — capacity frees as acknowledgements resolve
+positions and their hashes release, and dispatch resumes. Overflow is observable rather than silent:
+`retryingPositionsCount` (see [Metrics](#metrics)) sits **at or above** the configured ceiling for as
+long as it lasts, and the broker emits a rate-limited warning on entry into overflow. The *or above* is
+not slack in the wording: the gates stop admitting anything that could create a *new* tracked position
+once the ceiling is reached, but the negative acknowledgements the previous sentence always accepts
+still arrive, so the count settles somewhat past the ceiling and falls back only as those positions are
+acknowledged. The ceiling is the line at which overflow begins, not a value the count is pinned to. This is
+the same over-withhold-never-under-withhold direction as every other rule here. The alternative — accepting
+the nack but not tracking it, so ordering silently lapses under load — was rejected: a guarantee that stops
+holding precisely when the system is under pressure is not one an application can build on.
+
+Per position the tracker costs a long pair plus map overhead, duplicating identity `PendingAcksMap`
+already holds. This is where hash-level tracking earns its place: the bucket count has a hard structural
+ceiling and the bucket key is four bytes. A key-level tracker would be keyed by client-chosen bytes
+bounded only by `maxMessageSize`, with no ceiling on the number of buckets, so it would have to carry its
+own cap or store a digest — a bound it would owe rather than one it inherits.
+
+Every lookup on the dispatch path is a single test against an empty map when nothing is retrying.
+
+One cost is new and worth stating: returned positions stay unreplayable until their hash releases, and
+`MessageRedeliveryController#getMessagesToReplayNow` walks the position set on every read cycle, so
+during a long outage each cycle re-evaluates the replay filter for every withheld position. This is
+work the rejected hold-buffer design did not do. It does not starve anything — iteration continues past
+rejected positions — but on a subscription with a large replay queue it is a per-read cost proportional
+to the number of withheld messages.
+
+### Client: keys awaiting retry
+
+`ConsumerImpl` keeps a map of the keys that are awaiting retry, indexed from the negatively acknowledged
+messages the application has not yet acknowledged. Each entry holds the *positions* of that key's
+outstanding negatively acknowledged messages — the guard compares against the earliest of them, so the
+positions rather than the bare key are what the state is for — together with the ids this client has
+returned for the key. The value it indexes by is the **guard key** — the client's counterpart to the
+broker's sticky key, and what the rest of this section means by a message's sticky key. It is derived
+from the delivered message alone, through the public `Message` API:
+
+- the message's **ordering key** bytes when the message has an ordering key;
+- otherwise the message's **partition key** bytes, base64-decoded when the metadata flags the partition
+ key as base64 encoded;
+- and a message with neither key is **keyless**: it has no guard key, and is excluded from the feature —
+ see [General Notes](#general-notes).
+
+The guard compares bytes, so presence and emptiness are distinguished explicitly. Presence of the field
+decides, never its length: a message whose ordering key is set to an empty byte sequence *has* an
+ordering key and guards as the empty key, and an absent partition key and a present-but-empty one are
+different keys, which a client must not conflate. The existing helper `ConsumerBase#peekMessageKey` does
+not conflate them either — it branches on `hasOrderingKey()` and `hasKey()`, presence rather than length,
+so an absent key never yields empty bytes — and its one null-array path is unreachable through the public
+producer API: it requires `hasKey()` to be true while `MessageImpl#getKeyBytes()` takes its
+`isNullPartitionKey()` branch, and `TypedMessageBuilderImpl#key(null)` / `#keyBytes(null)` set
+`null_partition_key` *without* setting `partition_key`, so such a message has no key at all and is
+keyless to broker and client alike.
+
+The divergence that does matter is `peekMessageKey`'s treatment of the producer name. Keylessness follows
+from the two key fields alone and is never inferred from the producer name: `peekMessageKey` tests
+`msg.getProducerName() != null` where the metadata question `Commands#resolveStickyKey` asks is
+`metadata.hasProducerName()`, presence rather than nullness. A guard key derived the first way is not the
+broker's sticky key.
+
+The client deliberately does **not** reproduce `Commands#resolveStickyKey`. Its third branch,
+`producerName + "-" + sequenceId`, stays an internal broker dispatch detail and is left unmirrored on
+purpose: the broker owns the sticky key calculation and must be able to change it without a client
+change, and keyless messages are recognised by both key fields being absent rather than by computing the
+fallback. PIP-493 therefore neither exposes `resolveStickyKey` to clients nor promises that a client can
+predict which hash ranges a consumer owns; the deferred-work record closing
+[General Notes](#general-notes) states what a client would need before it could.
+
+On the two branches the client does mirror, its per-*message* guard key equals the broker's per-*entry*
+sticky key, because [one entry carries one key](#one-key-per-entry). That equality is what lets a return
+at entry granularity be key-precise, and it is what the prefix argument in
+[Two halves](#two-halves-because-the-messages-are-in-two-places) rests on. Any divergence between the two
+silently breaks the guarantee for the affected keys, so the agreement of the client's two-branch
+resolution with the broker's is worth a test over a corpus of keyed message shapes.
+
+- **The guard is position-ordered, not a set of keys.** A message whose guard key is awaiting retry is
+ returned **if and only if its position `(ledgerId, entryId)` is strictly later than the earliest
+ outstanding negatively acknowledged position of that key**; a message at or before that position is
+ **delivered**. This is the broker's blocking rule, evaluated on the key rather than on the hash — the
+ same rule at another of the three places [Two halves](#two-halves-because-the-messages-are-in-two-places)
+ names. The comparison is at *entry* granularity because the unit of return is the entry: the messages
+ of the negatively acknowledged entry itself compare equal and are therefore delivered with it, which is
+ what [General Notes](#general-notes) requires of them, and the negatively acknowledged message is
+ delivered by the same clause rather than by an exception to the rule.
+
+ A predicate over the *set* of guarded keys would return an earlier same-key message too, and that is
+ reachable: a disconnected consumer's pending acknowledgements are replayed with their hashes ahead of
+ the nacked position, to whichever consumer now owns the hash. Being earlier, such a message is exempt
+ from the broker's withholding rule, so it is redispatched at once, and its second arrival would satisfy
+ the self-healing disarm clause below and disarm the guard while the hash is still retrying — after
+ which a later same-key message already queued inside the client, on the listener executor say, could
+ reach the hand-off boundary before the nacked message is acknowledged. That is the inversion the
+ invariant forbids, produced by the guard that exists to prevent it.
+- **The guard is applied at one boundary: the hand-off to the application.** Immediately before a
+ message is returned from `receive`/`batchReceive`, completes a pending `receiveAsync`, or is passed to
+ a `MessageListener`, the client applies the test above; if the message is to be returned, it goes back
+ to the broker instead of being delivered, and the delivery path moves on to the next message. Choosing
+ this boundary rather than "when a message is taken from `incomingMessages`" is what
+ makes the rule complete: a pending `receiveAsync` is completed directly without entering the queue,
+ the zero-receiver-queue path bypasses the queue entirely, and `triggerListener` drains many messages
+ onto the listener executor before any of them reaches the application. In `MultiTopicsConsumerImpl`
+ the same rule is applied at the parent's hand-off boundary, and the return is routed to the
+ sub-consumer that owns the message.
+- **Sweeping the receiver queue is an optimisation, not the mechanism.** When the nack is issued the
+ client also sweeps the messages already sitting in `incomingMessages` that the test above would
+ return — that key's later-positioned ones — into the same return, which frees their memory and restores
+ their permits immediately instead of one at a time. It is an optimisation that has to be built: the
+ existing drain reclaims only a matching prefix of the queue, because
+ `GrowableArrayBlockingQueue#pollIf` stops at the first head element that does not match, so sweeping a
+ key's messages out of the middle of the queue needs a traversal the client does not have today. The
+ guard above is what makes the guarantee hold whether or not the sweep catches a given message, which is
+ why the sweep is the part that may be added incrementally.
+- **A returned message must not remain in the client's unacknowledged-message tracker**, and must not be
+ entered into it, because the application never received it. Acknowledgement-timeout tracking begins,
+ as it does today, when the message is actually handed to the application. For the same reason a
+ returned message must not run `ConsumerInterceptor#beforeConsume`, which otherwise reports a delivery
+ that never happened, and its permit must be restored — a returned message has already consumed one.
+- **Guard lifetime.** The guard for a key is armed when a message with that key is negatively
+ acknowledged, and is disarmed when either:
+
+ - the application has acknowledged every one of this client's negatively acknowledged messages for
+ that key — the same condition that releases the hash on the broker; or
+ - a message with that key that this client has already returned once during this guard arrives again.
+ The broker withholds returned messages while the hash is retrying, so a second arrival proves the
+ hash has been released — by an acknowledgement at another consumer, or because this subscription is
+ one where the broker does not withhold at all. The client therefore keeps the ids it has returned
+ for as long as the guard is armed.
+
+ The position-ordered predicate is what makes that second clause exact, and this is its most useful
+ consequence: because only later-positioned messages are ever returned, and later-positioned messages
+ are precisely the ones a retrying hash withholds, a returned message that arrives again really does
+ prove the hash was released. The clause needs no qualifier of its own — its premise is true rather than
+ nearly true. Under a key-set predicate it would not be: an earlier same-key message is returned but not
+ withheld, so its immediate redispatch would disarm a live guard.
+
+ The **earliest** of this client's negatively acknowledged messages for a key is therefore **delivered**
+ rather than returned when it comes back — it compares equal to the earliest outstanding negatively
+ acknowledged position of that key, so the rule delivers it, which is the retry the guard exists to
+ enable; returning it would put it straight back into the replay queue where the exemption dispatches it
+ again. A second negatively acknowledged message of the same key is later than that position, so the
+ rule returns it until the first resolves — which is what the broker's exemption enforces in any case.
+ But receiving the retry does **not** disarm the guard: the hash is still retrying at that point, so a
+ same-key message that was already queued for hand-off inside the client could otherwise slip past
+ behind it, before the retry has been acknowledged.
+
+ Every later-positioned message of the key is returned. The guard is also dropped on reconnection, and it
+ expires on a deadline computed from that key's own outstanding negatively acknowledged messages: each
+ of them contributes its own computed redelivery delay — from `negativeAckRedeliveryDelay`, or from
+ `RedeliveryBackoff` where one is configured — plus a fixed slack of 60 seconds, counted from that
+ message's negative acknowledgement, and the guard expires at the latest of those deadlines. Every new
+ nack for the key re-arms it, so a key that is being re-nacked through a long outage keeps its guard, and
+ only a guard that nothing has touched expires. The expiry exists only so that guard state cannot leak:
+ if a hash is reassigned while the guard is armed and never comes back to this consumer, neither
+ disarming condition can ever occur, and without a deadline the guard and its returned-id set would live
+ until the next reconnection.
Review Comment:
The bounded cleanup is understandable, but the fixed deadline and reconnect cleanup do not appear to be ordered with hand-offs already submitted to the listener executor.
For example, `A1`, `B1`, and `A2` may already be queued on one executor stripe, with `A1` and `A2` sharing a key. `A1` is negatively acknowledged, then `B1` blocks the stripe longer than the retry delay plus the guard margin. `A2` remains queued ahead of the retry of `A1`; after the guard expires, `A2` can reach the application before the retried `A1` is acknowledged. Reconnection has a similar shape because clearing the receiver queue does not cancel listener tasks that were already submitted.
It would help to define guard retirement so that queued hand-offs remain protected or are explicitly fenced and reclaimed. If reconnection is intended to form a guarantee boundary, old-connection hand-offs must not cross that boundary.
--
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