You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pulsar.apache.org by "ChimdumebiNebolisa (via GitHub)" <gi...@apache.org> on 2026/02/04 11:23:06 UTC

[PR] Fix 25204 consumer epoch [pulsar]

ChimdumebiNebolisa opened a new pull request, #25210:
URL: https://github.com/apache/pulsar/pull/25210

   <!--
   ### Contribution Checklist
     
     - PR title format should be *[type][component] summary*. 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.
     
     - 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
   
     - 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 an issue, -->
   
   Fixes #xyz
   
   <!-- or this PR is one task of an issue -->
   
   Main Issue: #xyz
   
   <!-- If the PR belongs to a PIP, please add the PIP link here -->
   
   PIP: #xyz 
   
   <!-- Details of when a PIP is required and how the PIP process work, please see: https://github.com/apache/pulsar/blob/master/pip/README.md -->
   
   ### Motivation
   
   <!-- Explain here the context, and why you're making that change. What is the problem you're trying to solve. -->
   
   ### Modifications
   
   <!-- Describe the modifications you've done. -->
   
   ### Verifying this change
   
   - [ ] Make sure that the change passes the CI checks.
   
   *(Please pick either of the following options)*
   
   This change is a trivial rework / code cleanup without any test coverage.
   
   *(or)*
   
   This change is already covered by existing tests, such as *(please describe tests)*.
   
   *(or)*
   
   This change added tests and can be verified as follows:
   
   *(example:)*
     - *Added integration tests for end-to-end deployment with large payloads (10MB)*
     - *Extended integration test for recovery after broker failure*
   
   ### 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
   
   ### Documentation
   
   <!-- DO NOT REMOVE THIS SECTION. CHECK THE PROPER BOX ONLY. -->
   
   - [ ] `doc` <!-- Your PR contains doc changes. -->
   - [ ] `doc-required` <!-- Your PR changes impact docs and you will update later -->
   - [ ] `doc-not-needed` <!-- Your PR changes do not impact docs -->
   - [ ] `doc-complete` <!-- Docs have been already added -->
   
   ### Matching PR in forked repository
   
   PR in forked repository: <!-- ENTER URL HERE -->
   
   <!--
   After opening this PR, the build in apache/pulsar will fail and instructions will
   be provided for opening a PR in the PR author's forked repository.
   
   apache/pulsar pull requests should be first tested in your own fork since the 
   apache/pulsar CI based on GitHub Actions has constrained resources and quota.
   GitHub Actions provides separate quota for pull requests that are executed in 
   a forked repository.
   
   The tests will be run in the forked repository until all PR review comments have
   been handled, the tests pass and the PR is approved by a reviewer.
   -->
   


-- 
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] Prevent epoch race in MultiTopicsConsumer batch receive [pulsar]

Posted by "ChimdumebiNebolisa (via GitHub)" <gi...@apache.org>.
ChimdumebiNebolisa commented on PR #25210:
URL: https://github.com/apache/pulsar/pull/25210#issuecomment-3865181468

   Thank you for the review. To my knowledge, `receiveMessageFromConsumer` is `private` in `MultiTopicsConsumerImpl`, which makes it difficult to drive the batch receive path deterministically without either reflection or a small visibility adjustment.
   
   Will it be ok to change `receiveMessageFromConsumer` from `private` to `protected` solely so a test subclass can invoke the existing logic (no new methods, no `@VisibleForTesting`)? If not, I will rework the regression to drive the path via the public subscribe flow.
   


-- 
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] Prevent epoch race in MultiTopicsConsumer batch receive [pulsar]

Posted by "BewareMyPower (via GitHub)" <gi...@apache.org>.
BewareMyPower commented on code in PR #25210:
URL: https://github.com/apache/pulsar/pull/25210#discussion_r2772131903


##########
docs/investigations/25204-consumer-epoch.md:
##########
@@ -0,0 +1,185 @@
+# Investigation: GitHub issue #25204 – MultiTopicsConsumer receives message with older ConsumerEpoch after redeliverUnacknowledgedMessages()

Review Comment:
   You should not commit the investigation document to the code base. You can post it to Gist and share the link in the PR description



-- 
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 25204 consumer epoch [pulsar]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #25210:
URL: https://github.com/apache/pulsar/pull/25210#issuecomment-3846870999

   @ChimdumebiNebolisa Please add the following content to your PR description and select a checkbox:
   ```
   - [ ] `doc` <!-- Your PR contains doc changes -->
   - [ ] `doc-required` <!-- Your PR changes impact docs and you will update later -->
   - [ ] `doc-not-needed` <!-- Your PR changes do not impact docs -->
   - [ ] `doc-complete` <!-- Docs have been already added -->
   ```


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@pulsar.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [fix][client] Prevent epoch race in MultiTopicsConsumer batch receive [pulsar]

Posted by "BewareMyPower (via GitHub)" <gi...@apache.org>.
BewareMyPower commented on code in PR #25210:
URL: https://github.com/apache/pulsar/pull/25210#discussion_r2772146142


##########
pulsar-client/src/test/java/org/apache/pulsar/client/impl/MultiTopicsConsumerEpochRaceTest.java:
##########
@@ -0,0 +1,289 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pulsar.client.impl;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertTrue;
+import io.netty.util.concurrent.DefaultThreadFactory;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.nio.ByteBuffer;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import org.apache.pulsar.client.api.Consumer;
+import org.apache.pulsar.client.api.Messages;
+import org.apache.pulsar.client.api.Schema;
+import org.apache.pulsar.client.api.SubscriptionType;
+import org.apache.pulsar.client.impl.conf.ConsumerConfigurationData;
+import org.apache.pulsar.client.util.ExecutorProvider;
+import org.apache.pulsar.common.api.proto.MessageMetadata;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+/**
+ * Deterministic regression test for GitHub issue #25204: MultiTopicsConsumer can deliver one message
+ * with old consumerEpoch while other messages in the same batch are filtered, due to a race when
+ * redeliverUnacknowledgedMessages() runs between batch message iterations.
+ *
+ * <p>Uses a test-only subclass of MultiTopicsConsumerImpl that overrides isValidConsumerEpoch to
+ * block after the first validation (latch1/latch2). With a 2-thread internal executor, the test
+ * triggers redeliverUnacknowledgedMessages() while the receive thread is blocked between the two
+ * validations, so the epoch changes mid-batch. Without the fix, exactly one message is delivered
+ * (bug). The test asserts totalDelivered != 1.
+ */
+@Test(groups = "flaky")

Review Comment:
   Why is it flaky? If the bug is fixed, this test should not be flaky



##########
pulsar-client/src/test/java/org/apache/pulsar/client/impl/MultiTopicsConsumerEpochRaceTest.java:
##########
@@ -0,0 +1,289 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pulsar.client.impl;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertTrue;
+import io.netty.util.concurrent.DefaultThreadFactory;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.nio.ByteBuffer;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import org.apache.pulsar.client.api.Consumer;
+import org.apache.pulsar.client.api.Messages;
+import org.apache.pulsar.client.api.Schema;
+import org.apache.pulsar.client.api.SubscriptionType;
+import org.apache.pulsar.client.impl.conf.ConsumerConfigurationData;
+import org.apache.pulsar.client.util.ExecutorProvider;
+import org.apache.pulsar.common.api.proto.MessageMetadata;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+/**
+ * Deterministic regression test for GitHub issue #25204: MultiTopicsConsumer can deliver one message
+ * with old consumerEpoch while other messages in the same batch are filtered, due to a race when
+ * redeliverUnacknowledgedMessages() runs between batch message iterations.
+ *
+ * <p>Uses a test-only subclass of MultiTopicsConsumerImpl that overrides isValidConsumerEpoch to
+ * block after the first validation (latch1/latch2). With a 2-thread internal executor, the test
+ * triggers redeliverUnacknowledgedMessages() while the receive thread is blocked between the two
+ * validations, so the epoch changes mid-batch. Without the fix, exactly one message is delivered
+ * (bug). The test asserts totalDelivered != 1.
+ */
+@Test(groups = "flaky")
+public class MultiTopicsConsumerEpochRaceTest {
+
+    private static final String TOPIC_NAME = "topic-25204";
+    private static final int AWAIT_SECONDS = 15;
+
+    private ExecutorProvider executorProvider;
+    private ExecutorService internalExecutor;
+    private PulsarClientImpl clientMock;
+
+    @BeforeMethod(alwaysRun = true)
+    public void setUp() {
+        executorProvider = new ExecutorProvider(2, "MultiTopicsConsumerEpochRaceTest");
+        internalExecutor = Executors.newFixedThreadPool(2,
+                new DefaultThreadFactory("internal-executor", true));
+        clientMock = ClientTestFixtures.createPulsarClientMockWithMockedClientCnx(
+                executorProvider, internalExecutor);
+    }
+
+    @AfterMethod(alwaysRun = true)
+    public void cleanUp() {
+        if (executorProvider != null) {
+            executorProvider.shutdownNow();
+        }
+        if (internalExecutor != null) {
+            internalExecutor.shutdownNow();
+        }
+    }
+
+    /**
+     * Deterministic reproduction: test subclass blocks inside isValidConsumerEpoch on the first
+     * call; test thread triggers redeliver (epoch increments on another executor thread), then
+     * unblocks. Second message is validated with new epoch and filtered. Outcome: exactly one
+     * message delivered. Assertion: totalDelivered must not be 1.
+     */
+    @Test(timeOut = 15000, description = "Issue 25204: redeliver blocked by lock during batch; acceptedByEpochCount == 2")
+    @SuppressWarnings("unchecked")
+    public void testEpochConsistencyWhenRedeliverRunsMidBatch() throws Exception {
+        CountDownLatch afterFirstValidationLatch = new CountDownLatch(1);
+        CountDownLatch releaseValidationLatch = new CountDownLatch(1);
+        CountDownLatch redeliverDoneLatch = new CountDownLatch(1);
+        CountDownLatch forEachCompleteLatch = new CountDownLatch(1);
+        AtomicInteger validationCallCount = new AtomicInteger(0);
+        AtomicInteger acceptedByEpochCount = new AtomicInteger(0);
+
+        ConsumerConfigurationData<byte[]> conf = new ConsumerConfigurationData<>();
+        conf.setTopicNames(Collections.emptySet());
+        conf.setSubscriptionName("sub-25204");
+        conf.setSubscriptionType(SubscriptionType.Exclusive);
+        conf.setReceiverQueueSize(10);
+        conf.setMessageListener((consumer, msg) -> { });
+
+        CompletableFuture<Consumer<byte[]>> subscribeFuture = new CompletableFuture<>();
+        TestableMultiTopicsConsumerImpl multiConsumer = new TestableMultiTopicsConsumerImpl(
+                clientMock, conf, executorProvider, subscribeFuture, Schema.BYTES, null, true);
+        multiConsumer.setEpochRaceTestLatches(
+                afterFirstValidationLatch, releaseValidationLatch, redeliverDoneLatch,
+                forEachCompleteLatch, validationCallCount, acceptedByEpochCount);
+
+        subscribeFuture.get(AWAIT_SECONDS, TimeUnit.SECONDS);
+        assertTrue(multiConsumer.getConsumers().isEmpty(), "Empty topic set gives 0 consumers");
+
+        ConsumerImpl<byte[]> mockConsumer = mock(ConsumerImpl.class);
+        when(mockConsumer.getTopic()).thenReturn(TOPIC_NAME);
+        doNothing().when(mockConsumer).increaseAvailablePermits(any(ClientCnx.class));
+        ClientCnx cnxMock = mock(ClientCnx.class);
+        org.apache.pulsar.client.impl.ConnectionHandler connectionHandlerMock =
+                mock(org.apache.pulsar.client.impl.ConnectionHandler.class);
+        when(connectionHandlerMock.cnx()).thenReturn(cnxMock);
+        when(mockConsumer.getConnectionHandler()).thenReturn(connectionHandlerMock);
+        when(mockConsumer.getCurrentReceiverQueueSize()).thenReturn(10);
+
+        CompletableFuture<Messages<byte[]>> batchFuture = new CompletableFuture<>();
+        when(mockConsumer.batchReceiveAsync()).thenReturn(batchFuture);
+
+        Field consumersField = MultiTopicsConsumerImpl.class.getDeclaredField("consumers");
+        consumersField.setAccessible(true);
+        java.util.Map<String, ConsumerImpl<byte[]>> consumersMap =
+                (java.util.Map<String, ConsumerImpl<byte[]>>) consumersField.get(multiConsumer);

Review Comment:
   Don't use reflection. `consumers` is a `protected` field, you can access `consumers` directly
   
   In addition, AI tends to use full qualified type name (`java.util.Map`) rather than `Map` with `import java.util.Map`. You can customize the AGENTS.md or manually review the AI generated code.



-- 
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] Prevent epoch race in MultiTopicsConsumer batch receive [pulsar]

Posted by "merlimat (via GitHub)" <gi...@apache.org>.
merlimat commented on PR #25210:
URL: https://github.com/apache/pulsar/pull/25210#issuecomment-6229834018

   Thanks @ChimdumebiNebolisa for digging into this. Looking at current master, the batch loop in `receiveMessageFromConsumer` and `redeliverUnacknowledgedMessages()` both run on the consumer's `internalPinnedExecutor`, which is single-threaded, so the epoch can't change mid-batch. The test only reproduces it by injecting a 2-thread pool as the pinned executor. I think #25204 is caused by something else: `redeliverUnacknowledgedMessages()` just enqueues the work and returns, so a following `receive()` can still return old-epoch messages already in `incomingMessages`. I'm going to close this one. If you'd like to pursue the real gap (e.g. having `internalReceive`/`batchReceive` filter by epoch, or making redeliver take effect before it returns), a new PR with a test against the real executor would be very welcome.
   


-- 
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] Prevent epoch race in MultiTopicsConsumer batch receive [pulsar]

Posted by "merlimat (via GitHub)" <gi...@apache.org>.
merlimat closed pull request #25210: [fix][client] Prevent epoch race in MultiTopicsConsumer batch receive
URL: https://github.com/apache/pulsar/pull/25210


-- 
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