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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to