GV

GeezerVison

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

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

On this site

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

This view

  • Original page
  • New address

GeezerVison is showing github.com — [fix][client] Don't return pre-redeliver messages from a multi-topics consumer's receive() by merlimat · Pull Request #27301 · apache/pulsar

Conversation

@merlimat

@merlimat merlimat commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

Fixes #25204

Replaces #27091, which can't be merged: GitHub counts a review thread from an account that no longer exists as unresolved, but hides it, so nobody can resolve it. codelipenghui approved #27091 at this same head commit, 8384e65.

Problem

MultiTopicsConsumerImpl.redeliverUnacknowledgedMessages() hands all its work to internalPinnedExecutor and returns right away. That work is bumping the epoch, the sub-consumer redelivers and clearing incomingMessages. Until that task runs, the synchronous receive() and receive(timeout, unit) take from incomingMessages on the caller's thread, with no epoch check. So a receive() right after the call can return a message that was queued before the redeliver. For Exclusive and Failover subscriptions the broker then delivers that message again, which explains the duplicates reported in the issue.

This affects multi-topic and partitioned-topic consumers. receiveAsync, batchReceive(Async) and the listener aren't affected: they run on the pinned executor, so they always wait behind the redeliver task. Shared and Key_Shared don't use epochs.

Example

Consumer<String> consumer = client.newConsumer(Schema.STRING)
        .topic(partitionedTopic)
        .subscriptionName("sub")
        .subscriptionType(SubscriptionType.Failover)
        .subscribe();
// messages are already queued in the consumer
consumer.redeliverUnacknowledgedMessages();
Message<String> msg = consumer.receive(); // can return a queued epoch-0 message
// before
public void redeliverUnacknowledgedMessages() {
    internalPinnedExecutor.execute(() -> {
        ...
        CONSUMER_EPOCH.incrementAndGet(this);
        ...
        clearIncomingMessages();
    });
}
protected Message<T> internalReceive() {
    ...
    message = incomingMessages.take(); // no epoch check

Change

  • redeliverUnacknowledgedMessages() now bumps CONSUMER_EPOCH before it returns. The sub-consumer redelivers and the queue clear still run on the pinned executor.
  • Both synchronous internalReceive variants skip queued messages from an older epoch, using the existing isValidConsumerEpoch, which releases them. They fix the queue size and don't restore permits, the same as clearIncomingMessages() would. The timed variant keeps its overall deadline.
  • The listener drain also takes messages through the timed variant, so with a listener the messages are kept. callMessageListener() gives back the permit that a listener's message holds, then drops the message if its epoch is older.
  • The hand-over from a sub-consumer, receiveMessageFromConsumer(), also checks the parent's epoch. With the earlier bump, it now drops the old-epoch messages that the queue clear used to drop. For those messages it gives a permit back ([fix][client] Fix failover consumer-listener stuck with cumulative ack and epoch time #23345). That's right for a listener's messages, but without a listener the sub-consumer already gave the permit back in messageProcessed(), so the broker got an extra one. The hand-over now gives the permit back only when there's a listener. Hand-overs that ran after the redeliver task already double-counted before this PR.
CONSUMER_EPOCH.incrementAndGet(this);
internalPinnedExecutor.execute(() -> { ... });
do {
    message = incomingMessages.take();
    decreaseIncomingMessageSize(message);
    checkState(message instanceof TopicMessageImpl);
} while (!isValidConsumerEpoch((TopicMessageImpl<T>) message));

Two alternatives were rejected:

  • Wait for the task to finish before returning: this deadlocks when the call comes from a callback running on the pinned thread.
  • Clear the queue on the caller's thread, as ConsumerImpl does: this splits state that only the pinned thread should touch across two threads.

Testing

  • New test: MessageRedeliveryTest.testMultiConsumerReceiveRightAfterRedeliverSkipsQueuedMessages.
    • It uses a Failover subscription on a topic with 2 partitions, with 10 messages queued.
    • It blocks the consumer's real internalPinnedExecutor with a task waiting on a latch, then calls redeliverUnacknowledgedMessages().
    • It asserts that receive(100 ms) returns null and the queue is empty.
    • It then releases the executor and checks that all 10 messages come back with epoch 1.
    • It uses no reflection, no sleeps and no stand-in executor.
  • New test: MultiTopicsConsumerImplTest.testListenerDrainGivesBackPermitsAfterRedeliver.
    • It runs on the real single-threaded pinned executor, with a direct listener executor so the listener runs inside the drain.
    • The listener requests a redelivery on the first drained message while 2 more are still queued.
    • It checks that all 3 drained messages give their permits back to the consumer that received them.
  • New test: MultiTopicsConsumerImplTest.testOldEpochMessageFromSubConsumerGivesBackPermitOnce, run with and without a listener.
    • It holds the real pinned executor, so that a sub-consumer's hand-over of an epoch-0 message queues ahead of the redeliver task and runs after the bump.
    • It checks that the hand-over gives the permit back only when there's a listener.
  • Results: without the fix, the redelivery test fails with expected [null] but found [TopicMessageImpl@…]. Without the listener exclusion, the listener test gets 1 permit back out of 3. Without the listener check at the hand-over, the no-listener case of the hand-over test gives a permit back (NeverWantedButInvoked). With the fix, MultiTopicsConsumerImplTest (13 tests), MessageRedeliveryTest (15 tests) and ./gradlew quickCheck pass.
  • Not covered: no test drives the blocking receive() path directly, because the test would block. That path uses the same filter as the timed one.

Sorry, something went wrong.

Uh oh!

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

All reactions
merlimat added 4 commits October 17, 2026 08:17
@merlimat
[fix][client] Don't return pre-redeliver messages from a multi-topics…
99cb861
… consumer's receive()

MultiTopicsConsumerImpl.redeliverUnacknowledgedMessages() bumped the
consumer epoch and cleared incomingMessages in a task on the internal
pinned executor, and returned before it ran. A synchronous receive()
right after the call took messages that were still queued, which for
Exclusive/Failover subscriptions the broker then delivers again.

Bump the epoch before returning, and have the synchronous receive paths
drop queued messages from an older epoch, as the pending clear would.

Fixes apache#25204
@merlimat
Give back the listener's permits for messages queued at a redelivery
8d7aa40
The listener drain takes messages through the timed internalReceive().
When a listener requested a redelivery during a drain, the epoch bump
made the drain drop the remaining queued messages without giving back
their permits, which callMessageListener() does for a listener's
messages. Repeated redeliveries could exhaust the permits and stall the
consumer.

Leave a listener's messages to callMessageListener(), which gives back
the permit before it drops the messages from an older epoch.
@merlimat
Give back a dropped old-epoch message's permit only with a listener
a1c355e
receiveMessageFromConsumer() checks the multi-topics consumer's epoch.
Since the epoch is now bumped before the redeliver task runs, it also
drops the old-epoch messages that the task's queue clear used to drop.
For each of them it gave back a permit, which only a listener's messages
still hold. Without a listener, the sub consumer already gave it back in
messageProcessed() when it handed the message over, so the broker got an
extra permit. Hand-overs that ran after the redeliver task already did
this before.

Give back the permit there only when the consumer has a listener.
@merlimat
Merge branch 'master' into mmerli/multi-topics-redeliver-epoch-gap
8384e65
@merlimat merlimat added this to the 5.1.0 milestone Nov 2, 2026
@merlimat
merlimat requested a review from codelipenghui November 2, 2026 18:14
codelipenghui
codelipenghui approved these changes Nov 3, 2026
View reviewed changes

@codelipenghui codelipenghui left a comment

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed 8384e65eb209decc28fb0a850901a79dec998bd7. No actionable findings identified within the reviewed scope.

The immediate epoch update and synchronous receive filtering address the race while preserving executor-ordered cleanup and listener permit accounting.

Validation: 3 focused client test cases and all 16 MessageRedeliveryTest cases passed. The new queued-message regression failed with pre-change production behavior (expected [null] but found [TopicMessageImpl]) and passed again after restoring the exact PR source. The baseline retained only the test-access visibility hook; Git HEAD was unchanged and the worktree was restored clean.

Remaining coverage gap: the stale-message filtering branch in blocking receive() is not directly exercised by the new deterministic regression.

Sorry, something went wrong.

Uh oh!

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

All reactions
@merlimat
merlimat merged commit ea2ad82 into apache:master Nov 3, 2026
86 checks passed

Uh oh!

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

lhotari pushed a commit that referenced this pull request Nov 4, 2026
@merlimat @lhotari
[fix][client] Don't return pre-redeliver messages from a multi-topics…
792e6e6
… consumer's receive() (#27301)

(cherry picked from commit ea2ad82)
@lhotari lhotari added release/5.0.2 cherry-picked/branch-5.0 labels Nov 4, 2026
merlimat added a commit to merlimat/pulsar that referenced this pull request Nov 6, 2026
@merlimat
Merge remote-tracking branch 'apache/master' into mmerli/multi-topics…
0b1e15e
…-selective-seek

Conflicts with apache#27278 and apache#27301:
- receiveMessageFromConsumer(): keep the seekingTopics check under the
  @VisibleForTesting signature that both sides add.
- discardIncomingMessage() from apache#27278 skipped the permit give-back during
  any seek, since afterSeek() refilled every consumer. Now it skips it only
  for a consumer that is seeking, the only kind that afterSeek() refills.
- testSelectiveSeekGivesBackPermitsOfSkippedPartitionOnce from apache#27278
  expected the skipped partition's message to be dropped and its consumer
  refilled. It becomes testSelectiveSeekGivesBackPermitsOfDroppedMessageOnce:
  the sought partition's message is dropped and its consumer refilled once,
  and the skipped partition's message stays queued with its permit.
- The partition consumer mocks of two tests from apache#27278 and apache#27301 now have
  a topic, which the seek state looks up.
This was referenced Nov 21, 2026
[improve][ci] Run CI for the 4.2.6 backports to branch-4.2 (do not merge) #27680
Closed
[improve][ci] Run CI for the 4.2.6 backports to branch-4.2 (do not merge) #27681
Closed
[improve][ci] Run CI for the 4.2.6 backports to branch-4.2 (do not merge) #27684
Closed
@lhotari lhotari added cherry-picked/branch-4.2 release/4.2.6 cherry-picked/branch-4.0 release/4.0.15 labels Nov 21, 2026
ascentstream-bot pushed a commit to ascentstream/pulsar that referenced this pull request Nov 24, 2026
@merlimat @lhotari
[fix][client] Don't return pre-redeliver messages from a multi-topics…
3b0ec1b
… consumer's receive() (apache#27301)

(cherry picked from commit ea2ad82)
poorbarcode pushed a commit to poorbarcode/pulsar that referenced this pull request Nov 26, 2026
@merlimat @lhotari
[fix][client] Don't return pre-redeliver messages from a multi-topics…
43444ff
… consumer's receive() (apache#27301)

(cherry picked from commit ea2ad82)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

@codelipenghui codelipenghui codelipenghui approved these changes

Uh oh!

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

Assignees

No one assigned

Labels

cherry-picked/branch-4.0 cherry-picked/branch-4.2 cherry-picked/branch-5.0 release/4.0.15 release/4.2.6 release/5.0.2

Projects

None yet

Milestone

5.1.0

Development

Successfully merging this pull request may close these issues.

[Bug] MultiTopicsConsumer still received message with older ConsumerEpoch after redeliverUnacknowledgeMessages()

Uh oh!

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

3 participants

@merlimat @codelipenghui @lhotari
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.