You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pulsar.apache.org by "programmerahul (via GitHub)" <gi...@apache.org> on 2026/09/22 14:15:12 UTC
[PR] [fix][client]in chunk message consumer, pendingChunkedMessageCount is not synced with count of entries present in chunkedMessagesMap [pulsar]
programmerahul opened a new pull request, #26689:
URL: https://github.com/apache/pulsar/pull/26689
<!--
### Contribution Checklist
- PR title format should be *[type][component] summary*. The valid `[type]` and `[component]`/scope
prefixes are enforced by CI (see `.github/workflows/ci-semantic-pull-request.yml`); for details,
see *[Guideline - Pulsar PR Naming Convention](https://pulsar.apache.org/contribute/develop-semantic-title/)*.
- Fill out the template below to describe the changes contributed by the pull request. That will give reviewers the context they need to do the review.
- The **Motivation** and **Modifications** sections are required: explain *why* (the problem/context)
and *what/how* (the change). A title alone, or a description that only restates the title, is not enough.
- Each pull request should address only one issue, not mix up code from multiple issues.
- Each commit in the pull request has a meaningful commit message
- For the local build/test/PR workflow see `CONTRIBUTING.md`, and for coding conventions see
`CODING.md`. If you use an AI coding assistant, see `AGENTS.md`.
- Once all items of the checklist are addressed, remove the above text and this checklist, leaving only the filled out template below.
-->
<!-- Either this PR fixes/closes an issue — use "Fixes #xyz" or, equivalently, "Closes #xyz", -->
Fixes https://github.com/apache/pulsar/issues/26688
<!-- or this PR is one task of an issue -->
### Motivation
The count pendingChunkedMessageCount is not decrease while the actual count of incomplete chunked messages present in chunkedMessagesMap is decreased when out-of-order or duplicate chunk is received. So this cause unnecessary eviction, since eviction policy is based on this pendingChunkedMessageCount.
### Modifications
Decrease the count when ctx uuid entries is removed from chunkedMessagesMap
### Verifying this change
- [ * ] Make sure that the change passes the CI checks.
*(Please pick either of the following options)*
This change added tests and can be verified as follows:
- Added a test-case for this
### Does this pull request potentially affect one of the following parts:
<!-- DO NOT REMOVE THIS SECTION. CHECK THE PROPER BOX ONLY. -->
*If the box was checked, please highlight the changes*
- [ ] Dependencies (add or upgrade a dependency)
- [ ] The public API
- [ ] The schema
- [ ] The default values of configurations
- [ ] The threading model
- [ ] The binary protocol
- [ ] The REST endpoints
- [ ] The admin CLI options
- [ ] The metrics
- [ ] Anything that affects deployment
--
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] [fix][client]in chunk message consumer, pendingChunkedMessageCount is not synced with count of entries present in chunkedMessagesMap [pulsar]
Posted by "Denovo1998 (via GitHub)" <gi...@apache.org>.
Denovo1998 commented on PR #26689:
URL: https://github.com/apache/pulsar/pull/26689#issuecomment-6412143324
> @Denovo1998 Please take a look, shall we merge this PR, if no other changes are needed?
Let's wait for @lhotari or @merlimat to have time to review it.
--
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] [fix][client]in chunk message consumer, pendingChunkedMessageCount is not synced with count of entries present in chunkedMessagesMap [pulsar]
Posted by "programmerahul (via GitHub)" <gi...@apache.org>.
programmerahul commented on code in PR #26689:
URL: https://github.com/apache/pulsar/pull/26689#discussion_r4073795137
##########
pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerImpl.java:
##########
@@ -1636,6 +1642,12 @@ private ByteBuf processMessageChunk(ByteBuf compressedPayload, MessageMetadata m
}
chunkedMsgCtx.recycle();
chunkedMessagesMap.remove(msgMetadata.getUuid());
+ // The replaced (old) context was counted when its first chunk arrived. It is being
+ // discarded here without completing, so decrement the count before the unconditional
+ // increment below re-counts the new replacement context. Otherwise each duplicate/
+ // resent first chunk inflates pendingChunkedMessageCount by 1 while chunkedMessagesMap
+ // stays the same size -- drift that eventually triggers spurious eviction.
+ pendingChunkedMessageCount--;
Review Comment:
yes, that will be more cleaner, since these three are interrelated (map, count, and queue) so updating them together will keep those in sync.
I will update the implementation accordingly.
--
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] [fix][client]in chunk message consumer, pendingChunkedMessageCount is not synced with count of entries present in chunkedMessagesMap [pulsar]
Posted by "lhotari (via GitHub)" <gi...@apache.org>.
lhotari commented on code in PR #26689:
URL: https://github.com/apache/pulsar/pull/26689#discussion_r4158117601
##########
pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerImpl.java:
##########
@@ -1628,25 +1639,43 @@ private ByteBuf processMessageChunk(ByteBuf compressedPayload, MessageMetadata m
}
});
}
- // The first chunk of a new chunked-message received before receiving other chunks of previous
- // chunked-message
- // so, remove previous chunked-message from map and release buffer
+ // The first chunk of a new chunked-message received before receiving the other chunks
+ // of the previous chunked-message with the SAME uuid (a resent/duplicated first
+ // chunk, or a producer restart reusing the sequenceId). Discard the previous context.
+ // This is a REPLACEMENT of an existing tracking slot: the uuid is already counted once
+ // in pendingChunkedMessageCount, so this branch must NOT increment the count -- only
+ // the new-uuid branch below does. Otherwise each duplicate first chunk would drift the
+ // count above the real chunkedMessagesMap size (triggering spurious eviction).
+ //
+ // The uuid must, however, be re-positioned in pendingChunkedMessageUuidQueue. The
+ // replacement context below gets a fresh receivedTime, so leaving the uuid at its
+ // original (older) position would make queue order no longer match expiry order:
+ // removeExpireIncompleteChunkedMessages() only inspects the head and returns at the
+ // first non-expired entry, so a repeatedly-refreshed head uuid would indefinitely
+ // block expiry of genuinely-expired entries behind it. Remove the stale entry and
+ // re-add it so its position reflects the refreshed receivedTime. The count is
+ // unchanged (one entry out, one back in).
if (chunkedMsgCtx.chunkedMsgBuffer != null) {
ReferenceCountUtil.safeRelease(chunkedMsgCtx.chunkedMsgBuffer);
}
chunkedMsgCtx.recycle();
chunkedMessagesMap.remove(msgMetadata.getUuid());
- }
- pendingChunkedMessageCount++;
- if (maxPendingChunkedMessage > 0 && pendingChunkedMessageCount > maxPendingChunkedMessage) {
- removeOldestPendingChunkedMessage();
+ pendingChunkedMessageUuidQueue.remove(msgMetadata.getUuid());
+ pendingChunkedMessageUuidQueue.add(msgMetadata.getUuid());
+ } else {
+ // Genuinely new uuid: count it and enqueue it exactly once. Eviction is only checked
+ // here because only a new uuid grows the number of in-flight chunked messages.
+ pendingChunkedMessageCount++;
Review Comment:
**[SUGGESTION] consider deriving the pending count from chunkedMessagesMap instead of a separate counter**
The bug here is that a hand-maintained `int` has to be adjusted on every path that touches the map (completion, replace, out-of-order discard, eviction, expiry), and this PR adds two more adjustments. Since `chunkedMessagesMap` is the source of truth, the eviction check could be `chunkedMessagesMap.size() >= maxPendingChunkedMessage` before inserting a new uuid, and `pendingChunkedMessageCount` (and its `ForTest` getter) could go away, which removes this whole class of drift. It would also avoid the plain `int` being modified from both the Netty thread and the expiry task on `internalPinnedExecutor`.
If you keep the counter, that is fine too; it just means every future change to these paths has to keep it in step by hand.
##########
pulsar-broker/src/test/java/org/apache/pulsar/client/impl/MessageChunkingTest.java:
##########
@@ -439,6 +439,126 @@ public void testResendChunkMessages() throws Exception {
Assert.assertEquals(((ConsumerImpl<String>) consumer).getAvailablePermits(), 8);
}
+ /**
+ * Proves that pendingChunkedMessageCount stays in sync with chunkedMessagesMap when duplicate
+ * (resent) first chunks arrive.
+ *
+ * When a first chunk (chunkId 0) arrives for a uuid that already has a ChunkedMessageCtx,
+ * processMessageChunk() removes the old context from chunkedMessagesMap without decrementing
+ * pendingChunkedMessageCount, then unconditionally increments it for the replacement. Before the
+ * fix, each duplicate first chunk inflated the count by 1 while the map size stayed 1 -- an
+ * upward drift that eventually pushes the count past maxPendingChunkedMessage and triggers
+ * spurious eviction of good in-flight messages.
+ *
+ * Invariant: pendingChunkedMessageCount == chunkedMessagesMap.size().
+ * Buggy client: count == N, map == 1 -> FAIL. Fixed client: count == 1 -> PASS.
+ */
+ @Test
+ public void testPendingChunkedMessageCountDriftOnDuplicateFirstChunk() throws Exception {
+ final String topicName = "persistent://my-property/my-ns/chunkCountDrift";
+ @Cleanup
+ Consumer<String> consumer = pulsarClient.newConsumer(Schema.STRING)
+ .topic(topicName)
+ .subscriptionName("my-sub")
+ .maxPendingChunkedMessage(100) // high so eviction does not mask the drift
+ .autoAckOldestChunkedMessageOnQueueFull(true)
+ .subscribe();
+ @Cleanup
+ Producer<String> producer = pulsarClient.newProducer(Schema.STRING)
+ .topic(topicName)
+ .chunkMaxMessageSize(100)
+ .enableChunking(true)
+ .enableBatching(false)
+ .create();
+
+ ConsumerImpl<String> consumerImpl = (ConsumerImpl<String>) consumer;
+
+ // Send the first chunk (chunkId 0) of the SAME uuid many times (duplicate/resent first
+ // chunk), never completing it. Each duplicate replaces the context in the map (size stays 1)
+ // but bumps pendingChunkedMessageCount on the buggy client.
+ final int duplicates = 10;
+ for (int i = 0; i < duplicates; i++) {
+ sendSingleChunk(producer, "dup-uuid", 0, 2);
+ }
+
+ Awaitility.await().atMost(10, TimeUnit.SECONDS)
+ .untilAsserted(() -> assertEquals(consumerImpl.chunkedMessagesMap.size(), 1));
+
+ int mapSize = consumerImpl.chunkedMessagesMap.size();
+ int count = consumerImpl.getPendingChunkedMessageCountForTest();
+ int queueSize = consumerImpl.getPendingChunkedMessageUuidQueueSizeForTest();
+
+ // All three structures track the same single in-flight uuid; they must stay consistent
+ // regardless of how many duplicate first chunks arrive for it.
+ assertEquals(queueSize, mapSize,
+ "pendingChunkedMessageUuidQueue.size (" + queueSize + ") drifted from chunkedMessagesMap.size ("
+ + mapSize + ") after " + duplicates + " duplicate first chunks");
+ assertEquals(count, mapSize,
+ "pendingChunkedMessageCount (" + count + ") drifted from chunkedMessagesMap.size ("
+ + mapSize + ") after " + duplicates + " duplicate first chunks");
+ }
+
+ /**
+ * A duplicate first chunk resets its context's receivedTime. If the uuid is left at its original
+ * position in pendingChunkedMessageUuidQueue, queue order no longer matches expiry order, and
+ * because removeExpireIncompleteChunkedMessages() only inspects the head and returns at the first
+ * non-expired entry, a repeatedly-refreshed head uuid blocks expiry of genuinely-expired entries
+ * behind it (the reviewer's A/B head-of-line scenario).
+ *
+ * Here A's first chunk is refreshed continuously so A never expires, while B is left untouched
+ * past the expiry window. B must still be expired and removed. The fix re-positions A's uuid in
+ * the queue on each refresh so B reaches the head and is collected.
+ */
+ @Test
+ public void testRefreshedFirstChunkDoesNotBlockExpiryOfLaterEntries() throws Exception {
+ final String topicName = "persistent://my-property/my-ns/refreshedHeadExpiry";
+ @Cleanup
+ Consumer<String> consumer = pulsarClient.newConsumer(Schema.STRING)
+ .topic(topicName)
+ .subscriptionName("my-sub")
+ .maxPendingChunkedMessage(100)
+ .expireTimeOfIncompleteChunkedMessage(2, TimeUnit.SECONDS)
+ .subscribe();
+ @Cleanup
+ Producer<String> producer = pulsarClient.newProducer(Schema.STRING)
+ .topic(topicName)
+ .chunkMaxMessageSize(100)
+ .enableChunking(true)
+ .enableBatching(false)
+ .create();
+
+ ConsumerImpl<String> consumerImpl = (ConsumerImpl<String>) consumer;
+
+ // A arrives first, then B. Both incomplete. Queue: [A, B].
+ sendSingleChunk(producer, "A", 0, 2);
+ sendSingleChunk(producer, "B", 0, 2);
+ Awaitility.await().atMost(10, TimeUnit.SECONDS)
+ .untilAsserted(() -> assertEquals(consumerImpl.chunkedMessagesMap.size(), 2));
+
+ // Keep refreshing A's first chunk continuously so A's receivedTime is never older than the
+ // 2s expiry window -- A must never be eligible for expiry while we observe. We check B's
+ // removal WHILE still refreshing A: where the
Review Comment:
**[NIT] tidy the new expiry test's comments**
This comment has a fragment (`WHILE still refreshing A: where the`), and the Javadoc refers to "the reviewer's" scenario. Please reword both so the test reads standalone. The loop also sleeps up to ~12s; it passes quickly in the normal case, but it is worth checking it is not close to the 10s-style Awaitility limits used elsewhere in this class if CI is slow.
##########
pulsar-broker/src/test/java/org/apache/pulsar/client/impl/MessageChunkingTest.java:
##########
@@ -439,6 +439,126 @@ public void testResendChunkMessages() throws Exception {
Assert.assertEquals(((ConsumerImpl<String>) consumer).getAvailablePermits(), 8);
}
+ /**
+ * Proves that pendingChunkedMessageCount stays in sync with chunkedMessagesMap when duplicate
+ * (resent) first chunks arrive.
+ *
+ * When a first chunk (chunkId 0) arrives for a uuid that already has a ChunkedMessageCtx,
+ * processMessageChunk() removes the old context from chunkedMessagesMap without decrementing
+ * pendingChunkedMessageCount, then unconditionally increments it for the replacement. Before the
+ * fix, each duplicate first chunk inflated the count by 1 while the map size stayed 1 -- an
+ * upward drift that eventually pushes the count past maxPendingChunkedMessage and triggers
+ * spurious eviction of good in-flight messages.
+ *
+ * Invariant: pendingChunkedMessageCount == chunkedMessagesMap.size().
+ * Buggy client: count == N, map == 1 -> FAIL. Fixed client: count == 1 -> PASS.
+ */
+ @Test
+ public void testPendingChunkedMessageCountDriftOnDuplicateFirstChunk() throws Exception {
+ final String topicName = "persistent://my-property/my-ns/chunkCountDrift";
+ @Cleanup
+ Consumer<String> consumer = pulsarClient.newConsumer(Schema.STRING)
+ .topic(topicName)
+ .subscriptionName("my-sub")
+ .maxPendingChunkedMessage(100) // high so eviction does not mask the drift
+ .autoAckOldestChunkedMessageOnQueueFull(true)
+ .subscribe();
+ @Cleanup
+ Producer<String> producer = pulsarClient.newProducer(Schema.STRING)
+ .topic(topicName)
+ .chunkMaxMessageSize(100)
+ .enableChunking(true)
+ .enableBatching(false)
+ .create();
+
+ ConsumerImpl<String> consumerImpl = (ConsumerImpl<String>) consumer;
+
+ // Send the first chunk (chunkId 0) of the SAME uuid many times (duplicate/resent first
+ // chunk), never completing it. Each duplicate replaces the context in the map (size stays 1)
+ // but bumps pendingChunkedMessageCount on the buggy client.
+ final int duplicates = 10;
+ for (int i = 0; i < duplicates; i++) {
+ sendSingleChunk(producer, "dup-uuid", 0, 2);
+ }
+
+ Awaitility.await().atMost(10, TimeUnit.SECONDS)
+ .untilAsserted(() -> assertEquals(consumerImpl.chunkedMessagesMap.size(), 1));
Review Comment:
**[SUGGESTION] this test can assert before the duplicate chunks are processed, and the out-of-order path is not covered**
`producer.send()` returning does not mean the consumer has processed the chunk, and `chunkedMessagesMap.size() == 1` is already true after the first of the ten duplicates, so the assertions below can run before the rest have arrived (and between a replacement's `remove` and `computeIfAbsent` the map is briefly empty). It failed reliably for me with the fix reverted, so it is not vacuous in practice, but it is timing-dependent. A deterministic way is to send a complete second chunked message afterwards, receive it (messages are processed in order, so all duplicates are done), and then assert the three sizes.
It would also be good to cover the out-of-order discard (`count--` plus `queue.remove`), and eviction order after a replacement.
##########
pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerImpl.java:
##########
@@ -1692,6 +1721,14 @@ private ByteBuf processMessageChunk(ByteBuf compressedPayload, MessageMetadata m
ReferenceCountUtil.safeRelease(chunkedMsgCtx.chunkedMsgBuffer);
}
chunkedMsgCtx.recycle();
+ // A non-null context here means an out-of-order chunk is discarding a previously
+ // tracked assembly. That assembly's uuid was counted AND added to
+ // pendingChunkedMessageUuidQueue when its first chunk arrived, so remove it from both
+ // to keep chunkedMessagesMap, pendingChunkedMessageCount and the uuid queue in sync.
+ // (When chunkedMsgCtx is null nothing was ever tracked for this uuid, so there is
+ // nothing to decrement or dequeue.)
+ pendingChunkedMessageCount--;
+ pendingChunkedMessageUuidQueue.remove(msgMetadata.getUuid());
Review Comment:
**[NIT] queue.remove(uuid) is a linear scan on a locked array queue**
`GrowableArrayBlockingQueue.remove(Object)` scans and shifts the backing array while holding its locks, and this runs on the Netty thread. With the default `maxPendingChunkedMessage` that is small, but with `0` (unbounded) a stream of out-of-order chunks against a large queue gets more expensive. The replace path now does the same remove-then-add. Not a blocker; an insertion-ordered map keyed by uuid would make these O(1).
--
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] [fix][client]in chunk message consumer, pendingChunkedMessageCount is not synced with count of entries present in chunkedMessagesMap [pulsar]
Posted by "programmerahul (via GitHub)" <gi...@apache.org>.
programmerahul commented on PR #26689:
URL: https://github.com/apache/pulsar/pull/26689#issuecomment-6075636601
> Thanks for tracking down the pendingChunkedMessageCount drift and for adding regression tests; splitting the replace case from the new-uuid case in [`ConsumerImpl.java:1639-1681`](https://github.com/apache/pulsar/blob/24d2088ae03bed9ed68b7ef3bf34f99801fb6951/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerImpl.java#L1639-L1681) is a clear improvement, and re-queueing the uuid on replacement addresses the ordering concern @void-ptr974 raised. I confirmed that both new tests fail with the corresponding change reverted and pass with it.
>
> The main thing left is sequencing with #26658 (same author, same bookkeeping). It also edits the completion path and adds the same `getPendingChunkedMessageUuidQueueSizeForTest()` accessor at the same spot in ConsumerImpl.java, so whichever lands second will conflict, and the test's claim that map, count and queue stay in sync only holds fully once #26658's removal of completed uuids is in. I would suggest landing #26658 first (or combining them) and rebasing this one. #26661 (merged) only touches the discard-branch permit return and does not conflict; chunk reassembly lives only in ConsumerImpl, so the v5 client is not affected.
>
> A few smaller points are inline. For context, not for this PR: `processMessageChunk` runs on the Netty thread (ClientCnx.handleMessage calls `messageReceived` directly) while expiry runs on `internalPinnedExecutor`, so the plain `int` counter and the recycle/replace of a context are touched from two threads. That race pre-exists, but it is a reason to derive occupancy from the map rather than a separate counter.
I will address comments on this PR ( and rebase this) after merging : https://github.com/apache/pulsar/pull/26658
--
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] [fix][client]in chunk message consumer, pendingChunkedMessageCount is not synced with count of entries present in chunkedMessagesMap [pulsar]
Posted by "programmerahul (via GitHub)" <gi...@apache.org>.
programmerahul commented on code in PR #26689:
URL: https://github.com/apache/pulsar/pull/26689#discussion_r4074464985
##########
pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerImpl.java:
##########
@@ -1636,6 +1642,12 @@ private ByteBuf processMessageChunk(ByteBuf compressedPayload, MessageMetadata m
}
chunkedMsgCtx.recycle();
chunkedMessagesMap.remove(msgMetadata.getUuid());
+ // The replaced (old) context was counted when its first chunk arrived. It is being
+ // discarded here without completing, so decrement the count before the unconditional
+ // increment below re-counts the new replacement context. Otherwise each duplicate/
+ // resent first chunk inflates pendingChunkedMessageCount by 1 while chunkedMessagesMap
+ // stays the same size -- drift that eventually triggers spurious eviction.
+ pendingChunkedMessageCount--;
Review Comment:
@void-ptr974 I have updated the pr. Please review.
1. if chunkedMsgCtx.chunkedMsgBuffer buffer already exists, then only clean map. (no change in count and uuid queue)
2. if buffer doesn't exists, then adding in map, queue, count increase and also call removeOldestPendingChunkedMessage here. ( since in case 1, the overall count of incomplete message isn't increased, so no need for checking eviction)
--
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][client] Replace chunked-message queue and counter with an insertion-ordered map in ConsumerImpl [pulsar]
Posted by "programmerahul (via GitHub) via commits" <co...@pulsar.apache.org>.
programmerahul commented on PR #26689:
URL: https://github.com/apache/pulsar/pull/26689#issuecomment-7060884381
@lhotari I have merged master. Please check
--
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] [fix][client]in chunk message consumer, pendingChunkedMessageCount is not synced with count of entries present in chunkedMessagesMap [pulsar]
Posted by "void-ptr974 (via GitHub)" <gi...@apache.org>.
void-ptr974 commented on code in PR #26689:
URL: https://github.com/apache/pulsar/pull/26689#discussion_r4154784754
##########
pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerImpl.java:
##########
@@ -1628,25 +1639,36 @@ private ByteBuf processMessageChunk(ByteBuf compressedPayload, MessageMetadata m
}
});
}
- // The first chunk of a new chunked-message received before receiving other chunks of previous
- // chunked-message
- // so, remove previous chunked-message from map and release buffer
+ // The first chunk of a new chunked-message received before receiving the other chunks
+ // of the previous chunked-message with the SAME uuid (a resent/duplicated first
+ // chunk, or a producer restart reusing the sequenceId). Discard the previous context.
+ // This is a REPLACEMENT of an existing tracking slot: the uuid is already represented
+ // exactly once in pendingChunkedMessageCount and once in pendingChunkedMessageUuidQueue,
+ // so this branch must NOT increment the count or re-add the uuid to the queue -- only
Review Comment:
The duplicate first chunk creates a replacement context with a new `receivedTime`, but the UUID remains at its original position in `pendingChunkedMessageUuidQueue`. As a result, the queue order no longer matches the expiration order of the contexts.
For example, assuming a 60-second expiration:
- `A/0` arrives at `t=0`, queue: `[A]`
- `B/0` arrives at `t=10`, queue: `[A, B]`
- another `A/0` arrives at `t=50`, resetting A’s `receivedTime`, but the queue remains `[A, B]`
At `t=71`, B has expired but the refreshed A has not. The expiration task checks only the queue head, sees that A is not expired, and returns. Therefore, expired B remains in the map and queue. Repeated `A/0` chunks can keep B and all following entries from being cleaned up indefinitely.
--
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] [fix][client]in chunk message consumer, pendingChunkedMessageCount is not synced with count of entries present in chunkedMessagesMap [pulsar]
Posted by "programmerahul (via GitHub)" <gi...@apache.org>.
programmerahul commented on code in PR #26689:
URL: https://github.com/apache/pulsar/pull/26689#discussion_r4286555823
##########
pulsar-broker/src/test/java/org/apache/pulsar/client/impl/MessageChunkingTest.java:
##########
@@ -439,6 +439,126 @@ public void testResendChunkMessages() throws Exception {
Assert.assertEquals(((ConsumerImpl<String>) consumer).getAvailablePermits(), 8);
}
+ /**
+ * Proves that pendingChunkedMessageCount stays in sync with chunkedMessagesMap when duplicate
+ * (resent) first chunks arrive.
+ *
+ * When a first chunk (chunkId 0) arrives for a uuid that already has a ChunkedMessageCtx,
+ * processMessageChunk() removes the old context from chunkedMessagesMap without decrementing
+ * pendingChunkedMessageCount, then unconditionally increments it for the replacement. Before the
+ * fix, each duplicate first chunk inflated the count by 1 while the map size stayed 1 -- an
+ * upward drift that eventually pushes the count past maxPendingChunkedMessage and triggers
+ * spurious eviction of good in-flight messages.
+ *
+ * Invariant: pendingChunkedMessageCount == chunkedMessagesMap.size().
+ * Buggy client: count == N, map == 1 -> FAIL. Fixed client: count == 1 -> PASS.
+ */
+ @Test
+ public void testPendingChunkedMessageCountDriftOnDuplicateFirstChunk() throws Exception {
+ final String topicName = "persistent://my-property/my-ns/chunkCountDrift";
+ @Cleanup
+ Consumer<String> consumer = pulsarClient.newConsumer(Schema.STRING)
+ .topic(topicName)
+ .subscriptionName("my-sub")
+ .maxPendingChunkedMessage(100) // high so eviction does not mask the drift
+ .autoAckOldestChunkedMessageOnQueueFull(true)
+ .subscribe();
+ @Cleanup
+ Producer<String> producer = pulsarClient.newProducer(Schema.STRING)
+ .topic(topicName)
+ .chunkMaxMessageSize(100)
+ .enableChunking(true)
+ .enableBatching(false)
+ .create();
+
+ ConsumerImpl<String> consumerImpl = (ConsumerImpl<String>) consumer;
+
+ // Send the first chunk (chunkId 0) of the SAME uuid many times (duplicate/resent first
+ // chunk), never completing it. Each duplicate replaces the context in the map (size stays 1)
+ // but bumps pendingChunkedMessageCount on the buggy client.
+ final int duplicates = 10;
+ for (int i = 0; i < duplicates; i++) {
+ sendSingleChunk(producer, "dup-uuid", 0, 2);
+ }
+
+ Awaitility.await().atMost(10, TimeUnit.SECONDS)
+ .untilAsserted(() -> assertEquals(consumerImpl.chunkedMessagesMap.size(), 1));
+
+ int mapSize = consumerImpl.chunkedMessagesMap.size();
+ int count = consumerImpl.getPendingChunkedMessageCountForTest();
+ int queueSize = consumerImpl.getPendingChunkedMessageUuidQueueSizeForTest();
+
+ // All three structures track the same single in-flight uuid; they must stay consistent
+ // regardless of how many duplicate first chunks arrive for it.
+ assertEquals(queueSize, mapSize,
+ "pendingChunkedMessageUuidQueue.size (" + queueSize + ") drifted from chunkedMessagesMap.size ("
+ + mapSize + ") after " + duplicates + " duplicate first chunks");
+ assertEquals(count, mapSize,
+ "pendingChunkedMessageCount (" + count + ") drifted from chunkedMessagesMap.size ("
+ + mapSize + ") after " + duplicates + " duplicate first chunks");
+ }
+
+ /**
+ * A duplicate first chunk resets its context's receivedTime. If the uuid is left at its original
+ * position in pendingChunkedMessageUuidQueue, queue order no longer matches expiry order, and
+ * because removeExpireIncompleteChunkedMessages() only inspects the head and returns at the first
+ * non-expired entry, a repeatedly-refreshed head uuid blocks expiry of genuinely-expired entries
+ * behind it (the reviewer's A/B head-of-line scenario).
+ *
+ * Here A's first chunk is refreshed continuously so A never expires, while B is left untouched
+ * past the expiry window. B must still be expired and removed. The fix re-positions A's uuid in
+ * the queue on each refresh so B reaches the head and is collected.
+ */
+ @Test
+ public void testRefreshedFirstChunkDoesNotBlockExpiryOfLaterEntries() throws Exception {
+ final String topicName = "persistent://my-property/my-ns/refreshedHeadExpiry";
+ @Cleanup
+ Consumer<String> consumer = pulsarClient.newConsumer(Schema.STRING)
+ .topic(topicName)
+ .subscriptionName("my-sub")
+ .maxPendingChunkedMessage(100)
+ .expireTimeOfIncompleteChunkedMessage(2, TimeUnit.SECONDS)
+ .subscribe();
+ @Cleanup
+ Producer<String> producer = pulsarClient.newProducer(Schema.STRING)
+ .topic(topicName)
+ .chunkMaxMessageSize(100)
+ .enableChunking(true)
+ .enableBatching(false)
+ .create();
+
+ ConsumerImpl<String> consumerImpl = (ConsumerImpl<String>) consumer;
+
+ // A arrives first, then B. Both incomplete. Queue: [A, B].
+ sendSingleChunk(producer, "A", 0, 2);
+ sendSingleChunk(producer, "B", 0, 2);
+ Awaitility.await().atMost(10, TimeUnit.SECONDS)
+ .untilAsserted(() -> assertEquals(consumerImpl.chunkedMessagesMap.size(), 2));
+
+ // Keep refreshing A's first chunk continuously so A's receivedTime is never older than the
+ // 2s expiry window -- A must never be eligible for expiry while we observe. We check B's
+ // removal WHILE still refreshing A: where the
Review Comment:
updated
--
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][client] Replace chunked-message queue and counter with an insertion-ordered map in ConsumerImpl [pulsar]
Posted by "lhotari (via GitHub) via commits" <co...@pulsar.apache.org>.
lhotari commented on PR #26689:
URL: https://github.com/apache/pulsar/pull/26689#issuecomment-6972359238
I updated the title to describe what this PR changes. The miscount of `pendingChunkedMessageCount` on out-of-order and duplicate chunks was already fixed in #26084. This PR is the structural follow-up: it replaces the separately maintained queue and counter with a single insertion-ordered map, so the pending count and the eviction order come from the map itself and can't drift apart again as new code paths are added. `[improve]` fits that better than `[fix]`, and the new title follows the `[type][scope] Summary` convention.
--
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] [fix][client]in chunk message consumer, pendingChunkedMessageCount is not synced with count of entries present in chunkedMessagesMap [pulsar]
Posted by "programmerahul (via GitHub)" <gi...@apache.org>.
programmerahul commented on code in PR #26689:
URL: https://github.com/apache/pulsar/pull/26689#discussion_r4302415180
##########
pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerImpl.java:
##########
@@ -1628,25 +1639,43 @@ private ByteBuf processMessageChunk(ByteBuf compressedPayload, MessageMetadata m
}
});
}
- // The first chunk of a new chunked-message received before receiving other chunks of previous
- // chunked-message
- // so, remove previous chunked-message from map and release buffer
+ // The first chunk of a new chunked-message received before receiving the other chunks
+ // of the previous chunked-message with the SAME uuid (a resent/duplicated first
+ // chunk, or a producer restart reusing the sequenceId). Discard the previous context.
+ // This is a REPLACEMENT of an existing tracking slot: the uuid is already counted once
+ // in pendingChunkedMessageCount, so this branch must NOT increment the count -- only
+ // the new-uuid branch below does. Otherwise each duplicate first chunk would drift the
+ // count above the real chunkedMessagesMap size (triggering spurious eviction).
+ //
+ // The uuid must, however, be re-positioned in pendingChunkedMessageUuidQueue. The
+ // replacement context below gets a fresh receivedTime, so leaving the uuid at its
+ // original (older) position would make queue order no longer match expiry order:
+ // removeExpireIncompleteChunkedMessages() only inspects the head and returns at the
+ // first non-expired entry, so a repeatedly-refreshed head uuid would indefinitely
+ // block expiry of genuinely-expired entries behind it. Remove the stale entry and
+ // re-add it so its position reflects the refreshed receivedTime. The count is
+ // unchanged (one entry out, one back in).
if (chunkedMsgCtx.chunkedMsgBuffer != null) {
ReferenceCountUtil.safeRelease(chunkedMsgCtx.chunkedMsgBuffer);
}
chunkedMsgCtx.recycle();
chunkedMessagesMap.remove(msgMetadata.getUuid());
- }
- pendingChunkedMessageCount++;
- if (maxPendingChunkedMessage > 0 && pendingChunkedMessageCount > maxPendingChunkedMessage) {
- removeOldestPendingChunkedMessage();
+ pendingChunkedMessageUuidQueue.remove(msgMetadata.getUuid());
+ pendingChunkedMessageUuidQueue.add(msgMetadata.getUuid());
Review Comment:
The races are covered by https://github.com/apache/pulsar/pull/26084, so the current pr now have made those changes atomic, by removing the counter and queue
--
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] [fix][client]in chunk message consumer, pendingChunkedMessageCount is not synced with count of entries present in chunkedMessagesMap [pulsar]
Posted by "Denovo1998 (via GitHub)" <gi...@apache.org>.
Denovo1998 commented on code in PR #26689:
URL: https://github.com/apache/pulsar/pull/26689#discussion_r4230625438
##########
pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerImpl.java:
##########
@@ -1628,25 +1639,43 @@ private ByteBuf processMessageChunk(ByteBuf compressedPayload, MessageMetadata m
}
});
}
- // The first chunk of a new chunked-message received before receiving other chunks of previous
- // chunked-message
- // so, remove previous chunked-message from map and release buffer
+ // The first chunk of a new chunked-message received before receiving the other chunks
+ // of the previous chunked-message with the SAME uuid (a resent/duplicated first
+ // chunk, or a producer restart reusing the sequenceId). Discard the previous context.
+ // This is a REPLACEMENT of an existing tracking slot: the uuid is already counted once
+ // in pendingChunkedMessageCount, so this branch must NOT increment the count -- only
+ // the new-uuid branch below does. Otherwise each duplicate first chunk would drift the
+ // count above the real chunkedMessagesMap size (triggering spurious eviction).
+ //
+ // The uuid must, however, be re-positioned in pendingChunkedMessageUuidQueue. The
+ // replacement context below gets a fresh receivedTime, so leaving the uuid at its
+ // original (older) position would make queue order no longer match expiry order:
+ // removeExpireIncompleteChunkedMessages() only inspects the head and returns at the
+ // first non-expired entry, so a repeatedly-refreshed head uuid would indefinitely
+ // block expiry of genuinely-expired entries behind it. Remove the stale entry and
+ // re-add it so its position reflects the refreshed receivedTime. The count is
+ // unchanged (one entry out, one back in).
if (chunkedMsgCtx.chunkedMsgBuffer != null) {
ReferenceCountUtil.safeRelease(chunkedMsgCtx.chunkedMsgBuffer);
}
chunkedMsgCtx.recycle();
chunkedMessagesMap.remove(msgMetadata.getUuid());
- }
- pendingChunkedMessageCount++;
- if (maxPendingChunkedMessage > 0 && pendingChunkedMessageCount > maxPendingChunkedMessage) {
- removeOldestPendingChunkedMessage();
+ pendingChunkedMessageUuidQueue.remove(msgMetadata.getUuid());
+ pendingChunkedMessageUuidQueue.add(msgMetadata.getUuid());
Review Comment:
I think there's still a race here when this PR is combined with #26658.
The replacement path removes the old context from `chunkedMessagesMap`, re-adds the UUID to the queue, and only then creates the replacement context through `computeIfAbsent()`.
Meanwhile, #26658 changes the expiry loop to poll a queue head when its context is missing.
So the following interleaving seems possible:
1. The receive thread removes the old A context and re-adds A to the queue.
2. Before `computeIfAbsent()` runs, the expiry thread sees A at the queue head.
3. `chunkedMessagesMap.get("A")` returns null, so expiry polls A as a stale entry.
4. The receive thread creates the new A context.
Now A is back in the map and still counted, but its UUID is missing from the expiry queue. An incomplete A can then remain tracked without ever being expired.
Could we make the map/queue replacement atomic with respect to expiry? Moving `queue.add()` after `computeIfAbsent()` would reduce this specific window, but it wouldn't solve all the existing receive-vs-expiry races. #26084 already has a serialization approach we might be able to reuse.
##########
pulsar-broker/src/test/java/org/apache/pulsar/client/impl/MessageChunkingTest.java:
##########
@@ -439,6 +439,126 @@ public void testResendChunkMessages() throws Exception {
Assert.assertEquals(((ConsumerImpl<String>) consumer).getAvailablePermits(), 8);
}
+ /**
+ * Proves that pendingChunkedMessageCount stays in sync with chunkedMessagesMap when duplicate
+ * (resent) first chunks arrive.
+ *
+ * When a first chunk (chunkId 0) arrives for a uuid that already has a ChunkedMessageCtx,
+ * processMessageChunk() removes the old context from chunkedMessagesMap without decrementing
+ * pendingChunkedMessageCount, then unconditionally increments it for the replacement. Before the
+ * fix, each duplicate first chunk inflated the count by 1 while the map size stayed 1 -- an
+ * upward drift that eventually pushes the count past maxPendingChunkedMessage and triggers
+ * spurious eviction of good in-flight messages.
+ *
+ * Invariant: pendingChunkedMessageCount == chunkedMessagesMap.size().
+ * Buggy client: count == N, map == 1 -> FAIL. Fixed client: count == 1 -> PASS.
+ */
+ @Test
+ public void testPendingChunkedMessageCountDriftOnDuplicateFirstChunk() throws Exception {
+ final String topicName = "persistent://my-property/my-ns/chunkCountDrift";
+ @Cleanup
+ Consumer<String> consumer = pulsarClient.newConsumer(Schema.STRING)
+ .topic(topicName)
+ .subscriptionName("my-sub")
+ .maxPendingChunkedMessage(100) // high so eviction does not mask the drift
+ .autoAckOldestChunkedMessageOnQueueFull(true)
+ .subscribe();
+ @Cleanup
+ Producer<String> producer = pulsarClient.newProducer(Schema.STRING)
+ .topic(topicName)
+ .chunkMaxMessageSize(100)
+ .enableChunking(true)
+ .enableBatching(false)
+ .create();
+
+ ConsumerImpl<String> consumerImpl = (ConsumerImpl<String>) consumer;
+
+ // Send the first chunk (chunkId 0) of the SAME uuid many times (duplicate/resent first
+ // chunk), never completing it. Each duplicate replaces the context in the map (size stays 1)
+ // but bumps pendingChunkedMessageCount on the buggy client.
+ final int duplicates = 10;
+ for (int i = 0; i < duplicates; i++) {
+ sendSingleChunk(producer, "dup-uuid", 0, 2);
+ }
+
+ Awaitility.await().atMost(10, TimeUnit.SECONDS)
+ .untilAsserted(() -> assertEquals(consumerImpl.chunkedMessagesMap.size(), 1));
+
+ int mapSize = consumerImpl.chunkedMessagesMap.size();
+ int count = consumerImpl.getPendingChunkedMessageCountForTest();
+ int queueSize = consumerImpl.getPendingChunkedMessageUuidQueueSizeForTest();
+
+ // All three structures track the same single in-flight uuid; they must stay consistent
+ // regardless of how many duplicate first chunks arrive for it.
+ assertEquals(queueSize, mapSize,
+ "pendingChunkedMessageUuidQueue.size (" + queueSize + ") drifted from chunkedMessagesMap.size ("
+ + mapSize + ") after " + duplicates + " duplicate first chunks");
+ assertEquals(count, mapSize,
+ "pendingChunkedMessageCount (" + count + ") drifted from chunkedMessagesMap.size ("
+ + mapSize + ") after " + duplicates + " duplicate first chunks");
+ }
+
+ /**
+ * A duplicate first chunk resets its context's receivedTime. If the uuid is left at its original
+ * position in pendingChunkedMessageUuidQueue, queue order no longer matches expiry order, and
+ * because removeExpireIncompleteChunkedMessages() only inspects the head and returns at the first
+ * non-expired entry, a repeatedly-refreshed head uuid blocks expiry of genuinely-expired entries
+ * behind it (the reviewer's A/B head-of-line scenario).
+ *
+ * Here A's first chunk is refreshed continuously so A never expires, while B is left untouched
+ * past the expiry window. B must still be expired and removed. The fix re-positions A's uuid in
+ * the queue on each refresh so B reaches the head and is collected.
+ */
+ @Test
+ public void testRefreshedFirstChunkDoesNotBlockExpiryOfLaterEntries() throws Exception {
+ final String topicName = "persistent://my-property/my-ns/refreshedHeadExpiry";
+ @Cleanup
+ Consumer<String> consumer = pulsarClient.newConsumer(Schema.STRING)
+ .topic(topicName)
+ .subscriptionName("my-sub")
+ .maxPendingChunkedMessage(100)
+ .expireTimeOfIncompleteChunkedMessage(2, TimeUnit.SECONDS)
+ .subscribe();
+ @Cleanup
+ Producer<String> producer = pulsarClient.newProducer(Schema.STRING)
+ .topic(topicName)
+ .chunkMaxMessageSize(100)
+ .enableChunking(true)
+ .enableBatching(false)
+ .create();
+
+ ConsumerImpl<String> consumerImpl = (ConsumerImpl<String>) consumer;
+
+ // A arrives first, then B. Both incomplete. Queue: [A, B].
+ sendSingleChunk(producer, "A", 0, 2);
+ sendSingleChunk(producer, "B", 0, 2);
+ Awaitility.await().atMost(10, TimeUnit.SECONDS)
+ .untilAsserted(() -> assertEquals(consumerImpl.chunkedMessagesMap.size(), 2));
+
+ // Keep refreshing A's first chunk continuously so A's receivedTime is never older than the
+ // 2s expiry window -- A must never be eligible for expiry while we observe. We check B's
+ // removal WHILE still refreshing A: where the
+ // perpetually-refreshed head uuid actively shields the entry behind it. B is never refreshed,
+ // so once >2s pass it is expired -- unless A (left at the stale queue head without the fix)
+ // blocks the head-only expiry scan. Refresh every 400ms for up to ~12s, asserting B is gone.
+ long bArrivalNanos = System.nanoTime();
+ boolean bCollected = false;
+ for (int i = 0; i < 30 && !bCollected; i++) {
+ sendSingleChunk(producer, "A", 0, 2); // keep A's receivedTime fresh (head stays non-expired)
+ Thread.sleep(400);
+ // only meaningful once B is well past its 2s expiry window
+ if (System.nanoTime() - bArrivalNanos > TimeUnit.SECONDS.toNanos(4)) {
+ bCollected = consumerImpl.chunkedMessagesMap.get("B") == null;
+ }
+ }
+
+ // B must have been expired and removed while A was still being refreshed at the (old) queue
+ // head. On the buggy client B stays stuck behind the refreshed A indefinitely.
+ assertNull(consumerImpl.chunkedMessagesMap.get("B"),
Review Comment:
One concern with this test: it only checks that B was eventually removed, but it doesn't verify that A was still alive when B expired.
`sendSingleChunk()` waits for the producer send, not for the consumer to process A's replacement chunk. If A isn't refreshed quickly enough under CI load, A itself could expire, allowing the expiry loop to reach B even with the original queue-ordering bug. The test would then pass for the wrong reason.
Could we also verify that A is still tracked when B is collected? Alternatively, we could make this deterministic by controlling the contexts' `receivedTime` values and invoking the expiry method directly. That would avoid relying on the 400ms refresh loop and the 2-second timeout.
--
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][client] Replace chunked-message queue and counter with an insertion-ordered map in ConsumerImpl [pulsar]
Posted by "programmerahul (via GitHub) via commits" <co...@pulsar.apache.org>.
programmerahul commented on code in PR #26689:
URL: https://github.com/apache/pulsar/pull/26689#discussion_r4657180470
##########
pulsar-broker/src/test/java/org/apache/pulsar/client/impl/MessageChunkingTest.java:
##########
@@ -961,6 +755,132 @@ public void testResendChunkMessages() throws Exception {
Assert.assertEquals(((ConsumerImpl<String>) consumer).getAvailablePermits(), 8);
}
+ /**
+ * A duplicate first chunk replaces the assembly with a fresh one, so for eviction purposes that
+ * uuid becomes the newest in-flight message. With maxPendingChunkedMessage=2 and chunks A0, B0,
+ * A0 (replacement), C0, the oldest in-flight message when C arrives is B, so B must be evicted,
+ * not the just-refreshed A.
+ */
+ @Test
+ public void testEvictionOrderFollowsReplacedFirstChunk() throws Exception {
+ final String topicName = "persistent://my-property/my-ns/evictionOrderAfterReplacement";
Review Comment:
Updated topic fqn and client
--
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] [fix][client]in chunk message consumer, pendingChunkedMessageCount is not synced with count of entries present in chunkedMessagesMap [pulsar]
Posted by "programmerahul (via GitHub)" <gi...@apache.org>.
programmerahul commented on PR #26689:
URL: https://github.com/apache/pulsar/pull/26689#issuecomment-6247887325
@lhotari @codelipenghui PTAL
--
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] [fix][client]in chunk message consumer, pendingChunkedMessageCount is not synced with count of entries present in chunkedMessagesMap [pulsar]
Posted by "programmerahul (via GitHub)" <gi...@apache.org>.
programmerahul commented on PR #26689:
URL: https://github.com/apache/pulsar/pull/26689#issuecomment-6412103150
@Denovo1998 Please take a look, shall we merge this PR, if no other changes are needed?
--
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] [fix][client]in chunk message consumer, pendingChunkedMessageCount is not synced with count of entries present in chunkedMessagesMap [pulsar]
Posted by "lhotari (via GitHub) via commits" <co...@pulsar.apache.org>.
lhotari commented on code in PR #26689:
URL: https://github.com/apache/pulsar/pull/26689#discussion_r4610393124
##########
pulsar-broker/src/test/java/org/apache/pulsar/client/impl/MessageChunkingTest.java:
##########
@@ -947,6 +741,132 @@ public void testResendChunkMessages() throws Exception {
Assert.assertEquals(((ConsumerImpl<String>) consumer).getAvailablePermits(), 8);
}
+ /**
+ * A duplicate first chunk replaces the assembly with a fresh one, so for eviction purposes that
+ * uuid becomes the newest in-flight message. With maxPendingChunkedMessage=2 and chunks A0, B0,
+ * A0 (replacement), C0, the oldest in-flight message when C arrives is B, so B must be evicted,
+ * not the just-refreshed A.
+ */
+ @Test
+ public void testEvictionOrderFollowsReplacedFirstChunk() throws Exception {
+ final String topicName = "persistent://my-property/my-ns/evictionOrderAfterReplacement";
+ @Cleanup
+ Consumer<String> consumer = pulsarClient.newConsumer(Schema.STRING)
+ .topic(topicName)
+ .subscriptionName("my-sub")
+ .maxPendingChunkedMessage(2)
+ .autoAckOldestChunkedMessageOnQueueFull(true)
+ .subscribe();
+ @Cleanup
+ Producer<String> producer = pulsarClient.newProducer(Schema.STRING)
+ .topic(topicName)
+ .chunkMaxMessageSize(100)
+ .enableChunking(true)
+ .enableBatching(false)
+ .create();
+
+ ConsumerImpl<String> consumerImpl = (ConsumerImpl<String>) consumer;
+
+ sendSingleChunk(producer, "A", 0, 2);
+ sendSingleChunk(producer, "B", 0, 2);
+ sendSingleChunk(producer, "A", 0, 2); // replacement: A is now the newest
+ sendSingleChunk(producer, "C", 0, 2); // limit reached: evicts the oldest, B
+
+ // C is processed after everything before it, and eviction happens while processing C0.
+ Awaitility.await().atMost(10, TimeUnit.SECONDS)
+ .untilAsserted(() -> assertNotNull(consumerImpl.chunkedMessagesMap.get("C")));
+ assertEquals(consumerImpl.chunkedMessagesMap.keySet(), Set.of("A", "C"),
+ "the wrong message was evicted after A's first chunk was replaced");
+
+ // A and C can still complete.
+ sendSingleChunk(producer, "A", 1, 2);
+ sendSingleChunk(producer, "C", 1, 2);
+ Set<String> received = new HashSet<>();
+ for (int i = 0; i < 2; i++) {
+ Message<String> msg = consumer.receive(10, TimeUnit.SECONDS);
+ assertNotNull(msg, "expected both A and C to be delivered, got only " + received);
+ received.add(msg.getValue());
+ consumer.acknowledge(msg);
+ }
+ assertEquals(received, Set.of("chunk-A-0|chunk-A-1|", "chunk-C-0|chunk-C-1|"));
+ }
+
+ /**
+ * A duplicate first chunk resets its context's receivedTime. If the uuid kept its original position
+ * in chunkedMessagesMap's order, that order would no longer match expiry order, and because
+ * removeExpireIncompleteChunkedMessages() stops at the first non-expired entry, the refreshed uuid
+ * would block expiry of expired entries behind it.
+ *
+ * Chunks A0, B0, A0 (refresh): B is then made expired by back-dating its receivedTime, while A's
+ * refreshed context is brand new, and expiry is invoked directly. B must be collected and A must
+ * still be tracked. The expiry window is an hour, so the scheduled expiry task never runs and
+ * nothing depends on timing.
+ */
+ @Test
+ public void testRefreshedFirstChunkDoesNotBlockExpiryOfLaterEntries() throws Exception {
+ final String topicName = "persistent://my-property/my-ns/refreshedHeadExpiry";
+ @Cleanup
+ Consumer<String> consumer = pulsarClient.newConsumer(Schema.STRING)
+ .topic(topicName)
+ .subscriptionName("my-sub")
+ .maxPendingChunkedMessage(100)
+ .expireTimeOfIncompleteChunkedMessage(1, TimeUnit.HOURS)
+ .subscribe();
+ @Cleanup
+ Producer<String> producer = pulsarClient.newProducer(Schema.STRING)
+ .topic(topicName)
+ .chunkMaxMessageSize(100)
+ .enableChunking(true)
+ .enableBatching(false)
+ .create();
+
+ ConsumerImpl<String> consumerImpl = (ConsumerImpl<String>) consumer;
+
+ try {
+ sendSingleChunk(producer, "A", 0, 2);
+ sendSingleChunk(producer, "B", 0, 2);
+ sendSingleChunk(producer, "A", 0, 2); // refresh: A's context is replaced by a fresh one
+ // Barrier: C's first chunk is processed after everything before it.
+ sendSingleChunk(producer, "C", 0, 2);
+ Awaitility.await().atMost(10, TimeUnit.SECONDS)
+ .untilAsserted(() -> assertNotNull(consumerImpl.chunkedMessagesMap.get("C")));
+ assertEquals(consumerImpl.chunkedMessagesMap.keySet(), Set.of("A", "B", "C"));
+
+ // Make B expired. A (refreshed) and C were just created, so they are far from expiring.
+ ConsumerImpl.ChunkedMessageCtx b = consumerImpl.chunkedMessagesMap.get("B");
+ ByteBuf bBuffer = b.chunkedMsgBuffer;
+ b.receivedTime = 0;
+
+ consumerImpl.removeExpireIncompleteChunkedMessages();
+
+ assertNull(consumerImpl.chunkedMessagesMap.get("B"),
+ "B was not expired: the refreshed uuid A was still ahead of it in chunkedMessagesMap");
+ assertEquals(bBuffer.refCnt(), 0);
+ assertNotNull(consumerImpl.chunkedMessagesMap.get("A"), "A must still be tracked");
+ assertNotNull(consumerImpl.chunkedMessagesMap.get("C"), "C must still be tracked");
+
+ // A and C can still complete.
+ sendSingleChunk(producer, "A", 1, 2);
+ sendSingleChunk(producer, "C", 1, 2);
+ Set<String> received = new HashSet<>();
+ for (int i = 0; i < 2; i++) {
+ Message<String> msg = consumer.receive(10, TimeUnit.SECONDS);
+ assertNotNull(msg, "expected both A and C to be delivered, got only " + received);
+ received.add(msg.getValue());
+ consumer.acknowledge(msg);
+ }
+ assertEquals(received, Set.of("chunk-A-0|chunk-A-1|", "chunk-C-0|chunk-C-1|"));
+ } finally {
+ // Release whatever is still pending (only on failure paths) so the test does not leak.
+ for (ConsumerImpl.ChunkedMessageCtx ctx : consumerImpl.chunkedMessagesMap.values()) {
Review Comment:
**[NIT] failure-path cleanup iterates the map without a lock**
`chunkedMessagesMap` is now a `LinkedHashMap` behind `Collections.synchronizedMap`, so iterating `values()` is not safe while the IO thread may still insert a chunk (the consumer is still open here). If the wait for `C` times out, this loop can throw `ConcurrentModificationException` and hide the real failure. Wrapping the loop and `clear()` in `synchronized (consumerImpl.chunkedMessagesMap) { ... }` (the wrapper's mutex) would make it safe. Failure path only, so not a blocker.
--
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] [fix][client]in chunk message consumer, pendingChunkedMessageCount is not synced with count of entries present in chunkedMessagesMap [pulsar]
Posted by "programmerahul (via GitHub)" <gi...@apache.org>.
programmerahul commented on code in PR #26689:
URL: https://github.com/apache/pulsar/pull/26689#discussion_r4158184639
##########
pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerImpl.java:
##########
@@ -1628,25 +1639,36 @@ private ByteBuf processMessageChunk(ByteBuf compressedPayload, MessageMetadata m
}
});
}
- // The first chunk of a new chunked-message received before receiving other chunks of previous
- // chunked-message
- // so, remove previous chunked-message from map and release buffer
+ // The first chunk of a new chunked-message received before receiving the other chunks
+ // of the previous chunked-message with the SAME uuid (a resent/duplicated first
+ // chunk, or a producer restart reusing the sequenceId). Discard the previous context.
+ // This is a REPLACEMENT of an existing tracking slot: the uuid is already represented
+ // exactly once in pendingChunkedMessageCount and once in pendingChunkedMessageUuidQueue,
+ // so this branch must NOT increment the count or re-add the uuid to the queue -- only
Review Comment:
thanks for pointing this out.
So to solve this case. I am now removing the entry from queue and adding it back.
Also added a testcase for the same
--
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] [fix][client]in chunk message consumer, pendingChunkedMessageCount is not synced with count of entries present in chunkedMessagesMap [pulsar]
Posted by "void-ptr974 (via GitHub)" <gi...@apache.org>.
void-ptr974 commented on code in PR #26689:
URL: https://github.com/apache/pulsar/pull/26689#discussion_r4073481104
##########
pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerImpl.java:
##########
@@ -1636,6 +1642,12 @@ private ByteBuf processMessageChunk(ByteBuf compressedPayload, MessageMetadata m
}
chunkedMsgCtx.recycle();
chunkedMessagesMap.remove(msgMetadata.getUuid());
+ // The replaced (old) context was counted when its first chunk arrived. It is being
+ // discarded here without completing, so decrement the count before the unconditional
+ // increment below re-counts the new replacement context. Otherwise each duplicate/
+ // resent first chunk inflates pendingChunkedMessageCount by 1 while chunkedMessagesMap
+ // stays the same size -- drift that eventually triggers spurious eviction.
+ pendingChunkedMessageCount--;
Review Comment:
Decrementing `pendingChunkedMessageCount` fixes the counter drift, but the UUID belonging to the discarded context remains in `pendingChunkedMessageUuidQueue`. Repeated first chunks therefore leave the map and count at `1` while the queue keeps growing, and a stale queue head can block expiry.
Could the map, count, and queue be updated together when replacing the existing context?
--
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] [fix][client]in chunk message consumer, pendingChunkedMessageCount is not synced with count of entries present in chunkedMessagesMap [pulsar]
Posted by "programmerahul (via GitHub)" <gi...@apache.org>.
programmerahul commented on PR #26689:
URL: https://github.com/apache/pulsar/pull/26689#issuecomment-6232790336
> Thanks for addressing the review comments. The updated replacement logic and deterministic expiry test look much better. One important update: #26084 has just been merged into master. It already fixes the duplicate-first-chunk count drift, queue ordering, forward-gap cleanup, and stale queue entries. More importantly, it serializes chunk assembly and expiry using chunkedMessageLock, which also addresses the remaining receive-vs-expiry races that a single map.put() cannot fully prevent. I checked the merged code, and the original issue #26688 appears to be covered by #26084?
I think that one of the reason for the divergence of counter and the map, was that those are hand maintained, and can diverge in future also, if there are more branches added. So I think as earlier suggested by @lhotari , we can remove the counter ( and the queue also?) and just use one insertion ordered map, (for map, queue and counter). And with the new change #26084, these paths are already thread safe, ( and the insertion ordered map, will make those atomic, so they can never diverge)
--
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][client] Replace chunked-message queue and counter with an insertion-ordered map in ConsumerImpl [pulsar]
Posted by "lhotari (via GitHub) via commits" <co...@pulsar.apache.org>.
lhotari commented on code in PR #26689:
URL: https://github.com/apache/pulsar/pull/26689#discussion_r4663641517
##########
pulsar-broker/src/test/java/org/apache/pulsar/client/impl/MessageChunkingTest.java:
##########
@@ -961,6 +755,132 @@ public void testResendChunkMessages() throws Exception {
Assert.assertEquals(((ConsumerImpl<String>) consumer).getAvailablePermits(), 8);
}
+ /**
+ * A duplicate first chunk replaces the assembly with a fresh one, so for eviction purposes that
+ * uuid becomes the newest in-flight message. With maxPendingChunkedMessage=2 and chunks A0, B0,
+ * A0 (replacement), C0, the oldest in-flight message when C arrives is B, so B must be evicted,
+ * not the just-refreshed A.
+ */
+ @Test
+ public void testEvictionOrderFollowsReplacedFirstChunk() throws Exception {
+ final String topicName = "persistent://my-property/my-ns/evictionOrderAfterReplacement";
Review Comment:
Thanks, that looks good.
--
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] [fix][client]in chunk message consumer, pendingChunkedMessageCount is not synced with count of entries present in chunkedMessagesMap [pulsar]
Posted by "Denovo1998 (via GitHub)" <gi...@apache.org>.
Denovo1998 commented on PR #26689:
URL: https://github.com/apache/pulsar/pull/26689#issuecomment-6214112791
Thanks for addressing the review comments. The updated replacement logic and deterministic expiry test look much better.
One important update: #26084 has just been merged into master. It already fixes the duplicate-first-chunk count drift, queue ordering, forward-gap cleanup, and stale queue entries. More importantly, it serializes chunk assembly and expiry using chunkedMessageLock, which also addresses the remaining receive-vs-expiry races that a single map.put() cannot fully prevent.
I checked the merged code, and the original issue #26688 appears to be covered by #26084?
--
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] [fix][client]in chunk message consumer, pendingChunkedMessageCount is not synced with count of entries present in chunkedMessagesMap [pulsar]
Posted by "programmerahul (via GitHub)" <gi...@apache.org>.
programmerahul commented on code in PR #26689:
URL: https://github.com/apache/pulsar/pull/26689#discussion_r4302413217
##########
pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerImpl.java:
##########
@@ -1692,6 +1721,14 @@ private ByteBuf processMessageChunk(ByteBuf compressedPayload, MessageMetadata m
ReferenceCountUtil.safeRelease(chunkedMsgCtx.chunkedMsgBuffer);
}
chunkedMsgCtx.recycle();
+ // A non-null context here means an out-of-order chunk is discarding a previously
+ // tracked assembly. That assembly's uuid was counted AND added to
+ // pendingChunkedMessageUuidQueue when its first chunk arrived, so remove it from both
+ // to keep chunkedMessagesMap, pendingChunkedMessageCount and the uuid queue in sync.
+ // (When chunkedMsgCtx is null nothing was ever tracked for this uuid, so there is
+ // nothing to decrement or dequeue.)
+ pendingChunkedMessageCount--;
+ pendingChunkedMessageUuidQueue.remove(msgMetadata.getUuid());
Review Comment:
removed the counter and queue and map: by single insertion ordered map
--
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] [fix][client]in chunk message consumer, pendingChunkedMessageCount is not synced with count of entries present in chunkedMessagesMap [pulsar]
Posted by "programmerahul (via GitHub)" <gi...@apache.org>.
programmerahul commented on code in PR #26689:
URL: https://github.com/apache/pulsar/pull/26689#discussion_r4286553281
##########
pulsar-broker/src/test/java/org/apache/pulsar/client/impl/MessageChunkingTest.java:
##########
@@ -439,6 +439,126 @@ public void testResendChunkMessages() throws Exception {
Assert.assertEquals(((ConsumerImpl<String>) consumer).getAvailablePermits(), 8);
}
+ /**
+ * Proves that pendingChunkedMessageCount stays in sync with chunkedMessagesMap when duplicate
+ * (resent) first chunks arrive.
+ *
+ * When a first chunk (chunkId 0) arrives for a uuid that already has a ChunkedMessageCtx,
+ * processMessageChunk() removes the old context from chunkedMessagesMap without decrementing
+ * pendingChunkedMessageCount, then unconditionally increments it for the replacement. Before the
+ * fix, each duplicate first chunk inflated the count by 1 while the map size stayed 1 -- an
+ * upward drift that eventually pushes the count past maxPendingChunkedMessage and triggers
+ * spurious eviction of good in-flight messages.
+ *
+ * Invariant: pendingChunkedMessageCount == chunkedMessagesMap.size().
+ * Buggy client: count == N, map == 1 -> FAIL. Fixed client: count == 1 -> PASS.
+ */
+ @Test
+ public void testPendingChunkedMessageCountDriftOnDuplicateFirstChunk() throws Exception {
+ final String topicName = "persistent://my-property/my-ns/chunkCountDrift";
+ @Cleanup
+ Consumer<String> consumer = pulsarClient.newConsumer(Schema.STRING)
+ .topic(topicName)
+ .subscriptionName("my-sub")
+ .maxPendingChunkedMessage(100) // high so eviction does not mask the drift
+ .autoAckOldestChunkedMessageOnQueueFull(true)
+ .subscribe();
+ @Cleanup
+ Producer<String> producer = pulsarClient.newProducer(Schema.STRING)
+ .topic(topicName)
+ .chunkMaxMessageSize(100)
+ .enableChunking(true)
+ .enableBatching(false)
+ .create();
+
+ ConsumerImpl<String> consumerImpl = (ConsumerImpl<String>) consumer;
+
+ // Send the first chunk (chunkId 0) of the SAME uuid many times (duplicate/resent first
+ // chunk), never completing it. Each duplicate replaces the context in the map (size stays 1)
+ // but bumps pendingChunkedMessageCount on the buggy client.
+ final int duplicates = 10;
+ for (int i = 0; i < duplicates; i++) {
+ sendSingleChunk(producer, "dup-uuid", 0, 2);
+ }
+
+ Awaitility.await().atMost(10, TimeUnit.SECONDS)
+ .untilAsserted(() -> assertEquals(consumerImpl.chunkedMessagesMap.size(), 1));
Review Comment:
yes, updated and added testcase for out-of-order
--
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] [fix][client]in chunk message consumer, pendingChunkedMessageCount is not synced with count of entries present in chunkedMessagesMap [pulsar]
Posted by "programmerahul (via GitHub)" <gi...@apache.org>.
programmerahul commented on code in PR #26689:
URL: https://github.com/apache/pulsar/pull/26689#discussion_r4286663962
##########
pulsar-broker/src/test/java/org/apache/pulsar/client/impl/MessageChunkingTest.java:
##########
@@ -439,6 +439,126 @@ public void testResendChunkMessages() throws Exception {
Assert.assertEquals(((ConsumerImpl<String>) consumer).getAvailablePermits(), 8);
}
+ /**
+ * Proves that pendingChunkedMessageCount stays in sync with chunkedMessagesMap when duplicate
+ * (resent) first chunks arrive.
+ *
+ * When a first chunk (chunkId 0) arrives for a uuid that already has a ChunkedMessageCtx,
+ * processMessageChunk() removes the old context from chunkedMessagesMap without decrementing
+ * pendingChunkedMessageCount, then unconditionally increments it for the replacement. Before the
+ * fix, each duplicate first chunk inflated the count by 1 while the map size stayed 1 -- an
+ * upward drift that eventually pushes the count past maxPendingChunkedMessage and triggers
+ * spurious eviction of good in-flight messages.
+ *
+ * Invariant: pendingChunkedMessageCount == chunkedMessagesMap.size().
+ * Buggy client: count == N, map == 1 -> FAIL. Fixed client: count == 1 -> PASS.
+ */
+ @Test
+ public void testPendingChunkedMessageCountDriftOnDuplicateFirstChunk() throws Exception {
+ final String topicName = "persistent://my-property/my-ns/chunkCountDrift";
+ @Cleanup
+ Consumer<String> consumer = pulsarClient.newConsumer(Schema.STRING)
+ .topic(topicName)
+ .subscriptionName("my-sub")
+ .maxPendingChunkedMessage(100) // high so eviction does not mask the drift
+ .autoAckOldestChunkedMessageOnQueueFull(true)
+ .subscribe();
+ @Cleanup
+ Producer<String> producer = pulsarClient.newProducer(Schema.STRING)
+ .topic(topicName)
+ .chunkMaxMessageSize(100)
+ .enableChunking(true)
+ .enableBatching(false)
+ .create();
+
+ ConsumerImpl<String> consumerImpl = (ConsumerImpl<String>) consumer;
+
+ // Send the first chunk (chunkId 0) of the SAME uuid many times (duplicate/resent first
+ // chunk), never completing it. Each duplicate replaces the context in the map (size stays 1)
+ // but bumps pendingChunkedMessageCount on the buggy client.
+ final int duplicates = 10;
+ for (int i = 0; i < duplicates; i++) {
+ sendSingleChunk(producer, "dup-uuid", 0, 2);
+ }
+
+ Awaitility.await().atMost(10, TimeUnit.SECONDS)
+ .untilAsserted(() -> assertEquals(consumerImpl.chunkedMessagesMap.size(), 1));
+
+ int mapSize = consumerImpl.chunkedMessagesMap.size();
+ int count = consumerImpl.getPendingChunkedMessageCountForTest();
+ int queueSize = consumerImpl.getPendingChunkedMessageUuidQueueSizeForTest();
+
+ // All three structures track the same single in-flight uuid; they must stay consistent
+ // regardless of how many duplicate first chunks arrive for it.
+ assertEquals(queueSize, mapSize,
+ "pendingChunkedMessageUuidQueue.size (" + queueSize + ") drifted from chunkedMessagesMap.size ("
+ + mapSize + ") after " + duplicates + " duplicate first chunks");
+ assertEquals(count, mapSize,
+ "pendingChunkedMessageCount (" + count + ") drifted from chunkedMessagesMap.size ("
+ + mapSize + ") after " + duplicates + " duplicate first chunks");
+ }
+
+ /**
+ * A duplicate first chunk resets its context's receivedTime. If the uuid is left at its original
+ * position in pendingChunkedMessageUuidQueue, queue order no longer matches expiry order, and
+ * because removeExpireIncompleteChunkedMessages() only inspects the head and returns at the first
+ * non-expired entry, a repeatedly-refreshed head uuid blocks expiry of genuinely-expired entries
+ * behind it (the reviewer's A/B head-of-line scenario).
+ *
+ * Here A's first chunk is refreshed continuously so A never expires, while B is left untouched
+ * past the expiry window. B must still be expired and removed. The fix re-positions A's uuid in
+ * the queue on each refresh so B reaches the head and is collected.
+ */
+ @Test
+ public void testRefreshedFirstChunkDoesNotBlockExpiryOfLaterEntries() throws Exception {
+ final String topicName = "persistent://my-property/my-ns/refreshedHeadExpiry";
+ @Cleanup
+ Consumer<String> consumer = pulsarClient.newConsumer(Schema.STRING)
+ .topic(topicName)
+ .subscriptionName("my-sub")
+ .maxPendingChunkedMessage(100)
+ .expireTimeOfIncompleteChunkedMessage(2, TimeUnit.SECONDS)
+ .subscribe();
+ @Cleanup
+ Producer<String> producer = pulsarClient.newProducer(Schema.STRING)
+ .topic(topicName)
+ .chunkMaxMessageSize(100)
+ .enableChunking(true)
+ .enableBatching(false)
+ .create();
+
+ ConsumerImpl<String> consumerImpl = (ConsumerImpl<String>) consumer;
+
+ // A arrives first, then B. Both incomplete. Queue: [A, B].
+ sendSingleChunk(producer, "A", 0, 2);
+ sendSingleChunk(producer, "B", 0, 2);
+ Awaitility.await().atMost(10, TimeUnit.SECONDS)
+ .untilAsserted(() -> assertEquals(consumerImpl.chunkedMessagesMap.size(), 2));
+
+ // Keep refreshing A's first chunk continuously so A's receivedTime is never older than the
+ // 2s expiry window -- A must never be eligible for expiry while we observe. We check B's
+ // removal WHILE still refreshing A: where the
+ // perpetually-refreshed head uuid actively shields the entry behind it. B is never refreshed,
+ // so once >2s pass it is expired -- unless A (left at the stale queue head without the fix)
+ // blocks the head-only expiry scan. Refresh every 400ms for up to ~12s, asserting B is gone.
+ long bArrivalNanos = System.nanoTime();
+ boolean bCollected = false;
+ for (int i = 0; i < 30 && !bCollected; i++) {
+ sendSingleChunk(producer, "A", 0, 2); // keep A's receivedTime fresh (head stays non-expired)
+ Thread.sleep(400);
+ // only meaningful once B is well past its 2s expiry window
+ if (System.nanoTime() - bArrivalNanos > TimeUnit.SECONDS.toNanos(4)) {
+ bCollected = consumerImpl.chunkedMessagesMap.get("B") == null;
+ }
+ }
+
+ // B must have been expired and removed while A was still being refreshed at the (old) queue
+ // head. On the buggy client B stays stuck behind the refreshed A indefinitely.
+ assertNull(consumerImpl.chunkedMessagesMap.get("B"),
Review Comment:
Expiry is set to an hour now and B’s receivedTime is set by hand
--
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][client] Replace chunked-message queue and counter with an insertion-ordered map in ConsumerImpl [pulsar]
Posted by "programmerahul (via GitHub) via commits" <co...@pulsar.apache.org>.
programmerahul commented on PR #26689:
URL: https://github.com/apache/pulsar/pull/26689#issuecomment-7075944802
> Thanks for merging master. The `ConsumerImpl` change is unchanged since my approval. With master's move of `MessageChunkingTest` to `SharedPulsarBaseTest`, though, the two tests this PR adds still use the old fixed namespace, which the shared cluster does not create. Details inline.
Updated , the tests
--
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] [fix][client]in chunk message consumer, pendingChunkedMessageCount is not synced with count of entries present in chunkedMessagesMap [pulsar]
Posted by "programmerahul (via GitHub)" <gi...@apache.org>.
programmerahul commented on PR #26689:
URL: https://github.com/apache/pulsar/pull/26689#issuecomment-6317897092
@lhotari @codelipenghui Please review this pr
--
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] [fix][client]in chunk message consumer, pendingChunkedMessageCount is not synced with count of entries present in chunkedMessagesMap [pulsar]
Posted by "programmerahul (via GitHub)" <gi...@apache.org>.
programmerahul commented on code in PR #26689:
URL: https://github.com/apache/pulsar/pull/26689#discussion_r4286527684
##########
pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerImpl.java:
##########
@@ -1628,25 +1639,43 @@ private ByteBuf processMessageChunk(ByteBuf compressedPayload, MessageMetadata m
}
});
}
- // The first chunk of a new chunked-message received before receiving other chunks of previous
- // chunked-message
- // so, remove previous chunked-message from map and release buffer
+ // The first chunk of a new chunked-message received before receiving the other chunks
+ // of the previous chunked-message with the SAME uuid (a resent/duplicated first
+ // chunk, or a producer restart reusing the sequenceId). Discard the previous context.
+ // This is a REPLACEMENT of an existing tracking slot: the uuid is already counted once
+ // in pendingChunkedMessageCount, so this branch must NOT increment the count -- only
+ // the new-uuid branch below does. Otherwise each duplicate first chunk would drift the
+ // count above the real chunkedMessagesMap size (triggering spurious eviction).
+ //
+ // The uuid must, however, be re-positioned in pendingChunkedMessageUuidQueue. The
+ // replacement context below gets a fresh receivedTime, so leaving the uuid at its
+ // original (older) position would make queue order no longer match expiry order:
+ // removeExpireIncompleteChunkedMessages() only inspects the head and returns at the
+ // first non-expired entry, so a repeatedly-refreshed head uuid would indefinitely
+ // block expiry of genuinely-expired entries behind it. Remove the stale entry and
+ // re-add it so its position reflects the refreshed receivedTime. The count is
+ // unchanged (one entry out, one back in).
if (chunkedMsgCtx.chunkedMsgBuffer != null) {
ReferenceCountUtil.safeRelease(chunkedMsgCtx.chunkedMsgBuffer);
}
chunkedMsgCtx.recycle();
chunkedMessagesMap.remove(msgMetadata.getUuid());
- }
- pendingChunkedMessageCount++;
- if (maxPendingChunkedMessage > 0 && pendingChunkedMessageCount > maxPendingChunkedMessage) {
- removeOldestPendingChunkedMessage();
+ pendingChunkedMessageUuidQueue.remove(msgMetadata.getUuid());
+ pendingChunkedMessageUuidQueue.add(msgMetadata.getUuid());
+ } else {
+ // Genuinely new uuid: count it and enqueue it exactly once. Eviction is only checked
+ // here because only a new uuid grows the number of in-flight chunked messages.
+ pendingChunkedMessageCount++;
Review Comment:
I have removed pendingChunkedMessageCount , and using the chunkedMessagesMap size instead
--
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] [fix][client]in chunk message consumer, pendingChunkedMessageCount is not synced with count of entries present in chunkedMessagesMap [pulsar]
Posted by "programmerahul (via GitHub)" <gi...@apache.org>.
programmerahul commented on PR #26689:
URL: https://github.com/apache/pulsar/pull/26689#issuecomment-6233386687
Please review @lhotari @Denovo1998
--
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] [fix][client]in chunk message consumer, pendingChunkedMessageCount is not synced with count of entries present in chunkedMessagesMap [pulsar]
Posted by "programmerahul (via GitHub)" <gi...@apache.org>.
programmerahul commented on PR #26689:
URL: https://github.com/apache/pulsar/pull/26689#issuecomment-6246570770
@void-ptr974 PTAL
--
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][client] Replace chunked-message queue and counter with an insertion-ordered map in ConsumerImpl [pulsar]
Posted by "lhotari (via GitHub) via commits" <co...@pulsar.apache.org>.
lhotari commented on code in PR #26689:
URL: https://github.com/apache/pulsar/pull/26689#discussion_r4655168708
##########
pulsar-broker/src/test/java/org/apache/pulsar/client/impl/MessageChunkingTest.java:
##########
@@ -961,6 +755,132 @@ public void testResendChunkMessages() throws Exception {
Assert.assertEquals(((ConsumerImpl<String>) consumer).getAvailablePermits(), 8);
}
+ /**
+ * A duplicate first chunk replaces the assembly with a fresh one, so for eviction purposes that
+ * uuid becomes the newest in-flight message. With maxPendingChunkedMessage=2 and chunks A0, B0,
+ * A0 (replacement), C0, the oldest in-flight message when C arrives is B, so B must be evicted,
+ * not the just-refreshed A.
+ */
+ @Test
+ public void testEvictionOrderFollowsReplacedFirstChunk() throws Exception {
+ final String topicName = "persistent://my-property/my-ns/evictionOrderAfterReplacement";
Review Comment:
**[BUG] the two new tests still use `my-property/my-ns`, which does not exist on the shared test cluster**
After the master merge this class extends `SharedPulsarBaseTest`. That base class creates the tenant `test-tenant` (`SharedPulsarCluster.TENANT_NAME`) and a fresh namespace for each test method, and nothing creates `my-property` or `my-property/my-ns` anymore. So `subscribe()` here, and in `testRefreshedFirstChunkDoesNotBlockExpiryOfLaterEntries` ([`pulsar-broker/src/test/java/org/apache/pulsar/client/impl/MessageChunkingTest.java:821`](https://github.com/apache/pulsar/blob/883abdb5b8964362dfa5eea045c1bdd2504babfc/pulsar-broker/src/test/java/org/apache/pulsar/client/impl/MessageChunkingTest.java#L821)), should fail because the namespace is not found. Every other test in the class, including `testExpirySkipsStaleQueueHeadFromDiscardPath`, which was converted in the merge, now uses `"persistent://" + getNamespace() + "/..."`.
Could you change both topic names that way? For consistency, you could also switch `pulsarClient` to the per-method `client`, as the neighbouring tests do (the shared one works too, since `@Cleanup` closes the handles).
--
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