You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pulsar.apache.org by lh...@apache.org on 2025/10/28 17:30:09 UTC

(pulsar) branch branch-3.0 updated (fe84bdb3f32 -> 3f9824ac655)

This is an automated email from the ASF dual-hosted git repository.

lhotari pushed a change to branch branch-3.0
in repository https://gitbox.apache.org/repos/asf/pulsar.git


    from fe84bdb3f32 [fix][test] Stabilize SequenceIdWithErrorTest by fencing after first publish to avoid empty-ledger deletion and send timeout (#24861)
     new 37c024c1167 [fix][test] Fix flaky SubscriptionSeekTest.testSeekWillNotEncounteredFencedError by counting subscription is fenced only after seek (#24865)
     new 0d35acaeda2 [fix][broker] Stop to retry to read entries if the replicator has terminated (#24880)
     new 79784c00154 [improve][client]Add null check for Pulsar client clock configuration (#24848)
     new 048df0dbe81 [fix][broker] Fix totalAvailablePermits not reduced when removing consumer from non-persistent dispatcher (#24885)
     new 3f9824ac655 [fix][test] Fix flaky ReplicatorTest.testResumptionAfterBacklogRelaxed (#24904)

The 5 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 .../NonPersistentDispatcherMultipleConsumers.java  |   2 +
 .../service/persistent/PersistentReplicator.java   |  12 ++-
 .../pulsar/broker/service/ReplicatorTest.java      | 101 ++++++++++-----------
 .../broker/service/SubscriptionSeekTest.java       |  11 ++-
 ...ntStickyKeyDispatcherMultipleConsumersTest.java |  26 ++++++
 .../PersistentReplicatorInflightTaskTest.java      |  42 ++++++++-
 .../client/api/SimpleProducerConsumerTest.java     |  11 +++
 .../pulsar/client/impl/ClientBuilderImpl.java      |   1 +
 8 files changed, 146 insertions(+), 60 deletions(-)


(pulsar) 02/05: [fix][broker] Stop to retry to read entries if the replicator has terminated (#24880)

Posted by lh...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

lhotari pushed a commit to branch branch-3.0
in repository https://gitbox.apache.org/repos/asf/pulsar.git

commit 0d35acaeda21d722bd4755800d886b0cd3e1af75
Author: fengyubiao <yu...@streamnative.io>
AuthorDate: Fri Oct 24 16:10:41 2025 +0800

    [fix][broker] Stop to retry to read entries if the replicator has terminated (#24880)
    
    (cherry picked from commit 313ae974ef01b7ed295a03c93906ccf9daf82fd5)
---
 .../service/persistent/PersistentReplicator.java   | 12 ++++++-
 .../PersistentReplicatorInflightTaskTest.java      | 42 +++++++++++++++++++++-
 2 files changed, 52 insertions(+), 2 deletions(-)

diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/persistent/PersistentReplicator.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/persistent/PersistentReplicator.java
index b48d31ec364..4661ece815a 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/persistent/PersistentReplicator.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/persistent/PersistentReplicator.java
@@ -274,6 +274,9 @@ public abstract class PersistentReplicator extends AbstractReplicator
     }
 
     protected void readMoreEntries() {
+        if (state.equals(Terminated) || state.equals(Terminating)) {
+            return;
+        }
         // Acquire permits and check state of producer.
         InFlightTask newInFlightTask = acquirePermitsIfNotFetchingSchema();
         if (newInFlightTask == null) {
@@ -953,7 +956,9 @@ public abstract class PersistentReplicator extends AbstractReplicator
     protected boolean hasPendingRead() {
         synchronized (inFlightTasks) {
             for (InFlightTask task : inFlightTasks) {
-                if (task.readPos != null && task.entries == null) {
+                // The purpose of calling "getReadPos" instead of calling "readPos" is to make the test
+                // "testReplicationTaskStoppedAfterTopicClosed" can counter the calling times of "readMoreEntries".
+                if (task.getReadPos() != null && task.entries == null) {
                     // Skip the current reading if there is a pending cursor reading.
                     return true;
                 }
@@ -961,4 +966,9 @@ public abstract class PersistentReplicator extends AbstractReplicator
         }
         return false;
     }
+
+    @VisibleForTesting
+    String getReplicatorId() {
+        return  replicatorId;
+    }
 }
\ No newline at end of file
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/persistent/PersistentReplicatorInflightTaskTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/persistent/PersistentReplicatorInflightTaskTest.java
index 0d56d6fda29..31970f499fd 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/persistent/PersistentReplicatorInflightTaskTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/persistent/PersistentReplicatorInflightTaskTest.java
@@ -18,13 +18,17 @@
  */
 package org.apache.pulsar.broker.service.persistent;
 
+import static org.mockito.Mockito.doAnswer;
 import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertTrue;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.LinkedList;
 import java.util.List;
-
+import java.util.concurrent.atomic.AtomicInteger;
 import lombok.extern.slf4j.Slf4j;
 import org.apache.bookkeeper.mledger.Entry;
 import org.apache.bookkeeper.mledger.impl.PositionImpl;
@@ -34,6 +38,8 @@ import org.apache.pulsar.broker.service.BrokerServiceInternalMethodInvoker;
 import org.apache.pulsar.broker.service.OneWayReplicatorTestBase;
 import org.apache.pulsar.broker.service.persistent.PersistentReplicator.InFlightTask;
 import org.apache.pulsar.client.api.MessageId;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
 import org.testng.Assert;
 import org.testng.annotations.AfterClass;
 import org.testng.annotations.BeforeClass;
@@ -66,6 +72,40 @@ public class PersistentReplicatorInflightTaskTest extends OneWayReplicatorTestBa
         admin1.topics().createSubscription(topicName, subscriptionName, MessageId.earliest);
     }
 
+    @Test
+    public void testReplicationTaskStoppedAfterTopicClosed() throws Exception {
+        // Close a topic, which has enabled replication.
+        final String topicName = BrokerTestUtil.newUniqueName("persistent://" + replicatedNamespace + "/tp_");
+        admin1.topics().createNonPartitionedTopic(topicName);
+        waitReplicatorStarted(topicName);
+        PersistentTopic topic = (PersistentTopic) pulsar1.getBrokerService().getTopic(topicName, false)
+                .join().get();
+        PersistentReplicator replicator = (PersistentReplicator) topic.getReplicators().get(cluster2);
+        admin1.topics().unload(topicName);
+
+        // Inject a task into the "inFlightTasks" to calculate how many times the method "replicator.readMoreEntries"
+        // has been called.
+        AtomicInteger counter = new AtomicInteger();
+        InFlightTask injectedTask = new InFlightTask(PositionImpl.get(1, 1), 1, replicator.getReplicatorId());
+        injectedTask.setEntries(Collections.emptyList());
+        InFlightTask spyTask = spy(injectedTask);
+        replicator.inFlightTasks.add(spyTask);
+        doAnswer(new Answer() {
+            @Override
+            public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
+                counter.incrementAndGet();
+                return invocationOnMock.callRealMethod();
+            }
+        }).when(spyTask).getReadPos();
+
+        // Verify: there is no scheduled task to retry to read entries to replicate.
+        // Call "readMoreEntries" to make the issue happen.
+        replicator.readMoreEntries();
+        Thread.sleep(PersistentTopic.MESSAGE_RATE_BACKOFF_MS * 10);
+        assertEquals(replicator.getState(), AbstractReplicator.State.Terminated);
+        assertTrue(counter.get() <= 1);
+    }
+
     @Test
     public void testCreateOrRecycleInFlightTaskIntoQueue() throws Exception {
         log.info("Starting testCreateOrRecycleInFlightTaskIntoQueue");


(pulsar) 03/05: [improve][client]Add null check for Pulsar client clock configuration (#24848)

Posted by lh...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

lhotari pushed a commit to branch branch-3.0
in repository https://gitbox.apache.org/repos/asf/pulsar.git

commit 79784c00154a33b9d01e8c28c8860918fedf977f
Author: Ruimin MA <ma...@gmail.com>
AuthorDate: Mon Oct 27 22:37:40 2025 +0800

    [improve][client]Add null check for Pulsar client clock configuration (#24848)
    
    (cherry picked from commit 54db7f2828fbc38a9e341b11a263716bf52fb55a)
---
 .../apache/pulsar/client/api/SimpleProducerConsumerTest.java  | 11 +++++++++++
 .../java/org/apache/pulsar/client/impl/ClientBuilderImpl.java |  1 +
 2 files changed, 12 insertions(+)

diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/client/api/SimpleProducerConsumerTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/client/api/SimpleProducerConsumerTest.java
index ad2a285c6aa..662f03de2fb 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/client/api/SimpleProducerConsumerTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/client/api/SimpleProducerConsumerTest.java
@@ -306,6 +306,17 @@ public class SimpleProducerConsumerTest extends ProducerConsumerBase {
         });
     }
 
+    @Test(timeOut = 5000)
+    public void pulsarClientClockCheckTest() {
+        assertThatThrownBy(
+                () -> PulsarClient.builder()
+                    .serviceUrl(lookupUrl.toString())
+                    .clock(null)
+                    .build()
+        ).isInstanceOf(IllegalArgumentException.class)
+                .hasMessage("clock must not be null");
+    }
+
     @Test(timeOut = 100000)
     public void testPublishTimestampBatchEnabled() throws Exception {
 
diff --git a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ClientBuilderImpl.java b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ClientBuilderImpl.java
index a9e42de1922..f801bf27b13 100644
--- a/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ClientBuilderImpl.java
+++ b/pulsar-client/src/main/java/org/apache/pulsar/client/impl/ClientBuilderImpl.java
@@ -365,6 +365,7 @@ public class ClientBuilderImpl implements ClientBuilder {
 
     @Override
     public ClientBuilder clock(Clock clock) {
+        checkArgument(clock != null, "clock must not be null");
         conf.setClock(clock);
         return this;
     }


(pulsar) 04/05: [fix][broker] Fix totalAvailablePermits not reduced when removing consumer from non-persistent dispatcher (#24885)

Posted by lh...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

lhotari pushed a commit to branch branch-3.0
in repository https://gitbox.apache.org/repos/asf/pulsar.git

commit 048df0dbe8185f80d86a47a8de63a3b7c6901971
Author: Ruimin MA <ma...@gmail.com>
AuthorDate: Tue Oct 28 10:50:18 2025 +0800

    [fix][broker] Fix totalAvailablePermits not reduced when removing consumer from non-persistent dispatcher (#24885)
    
    (cherry picked from commit ebfff5814ed21811bc3f6ae076fb265c7266c2d8)
---
 .../NonPersistentDispatcherMultipleConsumers.java  |  2 ++
 ...ntStickyKeyDispatcherMultipleConsumersTest.java | 26 ++++++++++++++++++++++
 2 files changed, 28 insertions(+)

diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/nonpersistent/NonPersistentDispatcherMultipleConsumers.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/nonpersistent/NonPersistentDispatcherMultipleConsumers.java
index bfb7785a4f5..ab0ca14e068 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/nonpersistent/NonPersistentDispatcherMultipleConsumers.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/nonpersistent/NonPersistentDispatcherMultipleConsumers.java
@@ -101,6 +101,8 @@ public class NonPersistentDispatcherMultipleConsumers extends AbstractDispatcher
                     closeFuture.complete(null);
                 }
                 TOTAL_AVAILABLE_PERMITS_UPDATER.set(this, 0);
+            } else {
+                TOTAL_AVAILABLE_PERMITS_UPDATER.addAndGet(this, -consumer.getAvailablePermits());
             }
         } else {
             if (log.isDebugEnabled()) {
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/nonpersistent/NonPersistentStickyKeyDispatcherMultipleConsumersTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/nonpersistent/NonPersistentStickyKeyDispatcherMultipleConsumersTest.java
index b2638d53ab1..43ae6760884 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/nonpersistent/NonPersistentStickyKeyDispatcherMultipleConsumersTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/nonpersistent/NonPersistentStickyKeyDispatcherMultipleConsumersTest.java
@@ -106,6 +106,32 @@ public class NonPersistentStickyKeyDispatcherMultipleConsumersTest {
         assertTrue(selector.getConsumerKeyHashRanges().isEmpty());
     }
 
+    @Test(timeOut = 10000)
+    public void testTotalAvailablePermitsWhenRemoveConsumer() throws Exception {
+        final int permits = 10;
+        // add 2 consumers to dispatcher
+        Consumer consumerMock = mock(Consumer.class);
+        when(consumerMock.getAvailablePermits()).thenReturn(permits);
+        nonpersistentDispatcher.addConsumer(consumerMock);
+        Consumer consumerMock2 = mock(Consumer.class);
+        when(consumerMock2.getAvailablePermits()).thenReturn(permits);
+        when(consumerMock2.isWritable()).thenReturn(true);
+        nonpersistentDispatcher.addConsumer(consumerMock2);
+
+        // add 10 flow permits to the dispatcher, so TOTAL_AVAILABLE_PERMITS_UPDATER will be 10
+        nonpersistentDispatcher.consumerFlow(consumerMock2, permits);
+        assertEquals(NonPersistentDispatcherMultipleConsumers
+                        .TOTAL_AVAILABLE_PERMITS_UPDATER.get(nonpersistentDispatcher), 10);
+        // add another 10 flow permits to the dispatcher, so TOTAL_AVAILABLE_PERMITS_UPDATER will be 20
+        nonpersistentDispatcher.consumerFlow(consumerMock, permits);
+        assertEquals(NonPersistentDispatcherMultipleConsumers.
+                        TOTAL_AVAILABLE_PERMITS_UPDATER.get(nonpersistentDispatcher), 20);
+        // remove one consumer, so the TOTAL_AVAILABLE_PERMITS_UPDATER of the dispatcher will be reduced to 10
+        nonpersistentDispatcher.removeConsumer(consumerMock);
+        assertEquals(NonPersistentDispatcherMultipleConsumers.
+                TOTAL_AVAILABLE_PERMITS_UPDATER.get(nonpersistentDispatcher), 10);
+    }
+
     @Test(timeOut = 10000)
     public void testSendMessage() throws BrokerServiceException {
         Consumer consumerMock = mock(Consumer.class);


(pulsar) 05/05: [fix][test] Fix flaky ReplicatorTest.testResumptionAfterBacklogRelaxed (#24904)

Posted by lh...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

lhotari pushed a commit to branch branch-3.0
in repository https://gitbox.apache.org/repos/asf/pulsar.git

commit 3f9824ac655a8e146013b999e31840bb35378274
Author: Lari Hotari <lh...@apache.org>
AuthorDate: Tue Oct 28 19:10:36 2025 +0200

    [fix][test] Fix flaky ReplicatorTest.testResumptionAfterBacklogRelaxed (#24904)
    
    (cherry picked from commit 3f80cd5f6587df457dfa83aca437abb659284c0a)
---
 .../pulsar/broker/service/ReplicatorTest.java      | 101 ++++++++++-----------
 1 file changed, 47 insertions(+), 54 deletions(-)

diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/ReplicatorTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/ReplicatorTest.java
index 5820ef3d8e4..a5b7b4f3e6b 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/ReplicatorTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/ReplicatorTest.java
@@ -99,6 +99,7 @@ import org.apache.pulsar.common.policies.data.BacklogQuota;
 import org.apache.pulsar.common.policies.data.BacklogQuota.RetentionPolicy;
 import org.apache.pulsar.common.policies.data.ClusterData;
 import org.apache.pulsar.common.policies.data.PartitionedTopicStats;
+import org.apache.pulsar.common.policies.data.Policies;
 import org.apache.pulsar.common.policies.data.ReplicatorStats;
 import org.apache.pulsar.common.policies.data.SchemaCompatibilityStrategy;
 import org.apache.pulsar.common.policies.data.TopicStats;
@@ -911,6 +912,10 @@ public class ReplicatorTest extends ReplicatorTestBase {
         assertTrue(remoteClusters.contains("r1"));
     }
 
+    @DataProvider(name = "retentionPolicies")
+    public static Object[][] retentionPolicies() {
+        return new Object[][] { { RetentionPolicy.producer_exception }, { RetentionPolicy.producer_request_hold } };
+    }
 
     /**
      * Issue #199
@@ -921,73 +926,61 @@ public class ReplicatorTest extends ReplicatorTestBase {
      * @throws Exception
      */
 
-    @Test(timeOut = 60000, priority = -1)
-    public void testResumptionAfterBacklogRelaxed() throws Exception {
-        List<RetentionPolicy> policies = new ArrayList<>();
-        policies.add(RetentionPolicy.producer_exception);
-        policies.add(RetentionPolicy.producer_request_hold);
-
-        for (RetentionPolicy policy : policies) {
-            // Use 1Mb quota by default
-            admin1.namespaces().setBacklogQuota("pulsar/ns1", BacklogQuota.builder()
-                    .limitSize(1 * 1024 * 1024)
-                    .retentionPolicy(policy)
-                    .build());
-            Thread.sleep(200);
-
-            TopicName dest = TopicName
-                    .get(BrokerTestUtil.newUniqueName("persistent://pulsar/ns1/%s-" + policy));
-
-            // Producer on r1
-            @Cleanup
-            MessageProducer producer1 = new MessageProducer(url1, dest);
+    @Test(timeOut = 60000, priority = -1, dataProvider = "retentionPolicies")
+    public void testResumptionAfterBacklogRelaxed(RetentionPolicy policy) throws Exception {
+        // create a unique namespace for this test case to avoid flakiness
+        String namespace = newUniqueName("pulsar/testResumptionAfterBacklogRelaxed");
+        Policies policies = new Policies();
+        policies.backlog_quota_map = Map.of(BacklogQuota.BacklogQuotaType.destination_storage, BacklogQuota.builder()
+                // Use 1Mb quota by default
+                .limitSize(1 * 1024 * 1024)
+                .retentionPolicy(policy)
+                .build());
+        policies.replication_clusters = Set.of("r1", "r2");
+        admin1.namespaces().createNamespace(namespace, policies);
+
+        TopicName dest = TopicName.get("persistent://" + namespace + "/" + policy);
 
-            // Consumer on r2
-            @Cleanup
-            MessageConsumer consumer2 = new MessageConsumer(url2, dest);
-
-            // Replicator for r1 -> r2
-            PersistentTopic topic = (PersistentTopic) pulsar1.getBrokerService().getTopicReference(dest.toString()).get();
-            Replicator replicator = topic.getPersistentReplicator("r2");
+        // Producer on r1
+        @Cleanup
+        MessageProducer producer1 = new MessageProducer(url1, dest);
 
-            // Produce 1 message in r1. This message will be replicated immediately into r2 and it will become part of
-            // local backlog
-            producer1.produce(1);
+        // Consumer on r2
+        @Cleanup
+        MessageConsumer consumer2 = new MessageConsumer(url2, dest);
 
-            Thread.sleep(500);
+        // Replicator for r1 -> r2
+        PersistentTopic topic = (PersistentTopic) pulsar1.getBrokerService()
+                .getTopicReference(dest.toString()).get();
+        Replicator replicator = topic.getPersistentReplicator("r2");
 
-            // Restrict backlog quota limit to 1 byte to stop replication
-            admin1.namespaces().setBacklogQuota("pulsar/ns1", BacklogQuota.builder()
-                    .limitSize(1)
-                    .retentionPolicy(policy)
-                    .build());
+        // Produce 1 message in r1. This message will be replicated immediately into r2 and it will become part of
+        // local backlog
+        producer1.produce(1);
 
-            Thread.sleep((TIME_TO_CHECK_BACKLOG_QUOTA + 1) * 1000);
+        Awaitility.await().untilAsserted(() -> assertEquals(replicator.getStats().replicationBacklog, 0));
 
-            assertEquals(replicator.getStats().replicationBacklog, 0);
+        // Restrict backlog quota limit to 1 byte to stop replication
+        admin1.namespaces().setBacklogQuota(namespace, BacklogQuota.builder()
+                .limitSize(1)
+                .retentionPolicy(policy)
+                .build());
 
-            // Next message will not be replicated, because r2 has reached the quota
-            producer1.produce(1);
+        Thread.sleep((TIME_TO_CHECK_BACKLOG_QUOTA + 1) * 1000);
 
-            Thread.sleep(500);
 
-            assertEquals(replicator.getStats().replicationBacklog, 1);
+        // Next message will not be replicated, because r2 has reached the quota
+        producer1.produce(1);
 
-            // Consumer will now drain 1 message and the replication backlog will be cleared
-            consumer2.receive(1);
+        Awaitility.await().untilAsserted(() -> assertEquals(replicator.getStats().replicationBacklog, 1));
 
-            // Wait until the 2nd message got delivered to consumer
-            consumer2.receive(1);
+        // Consumer will now drain 1 message and the replication backlog will be cleared
+        consumer2.receive(1);
 
-            int retry = 10;
-            for (int i = 0; i < retry && replicator.getStats().replicationBacklog > 0; i++) {
-                if (i != retry - 1) {
-                    Thread.sleep(100);
-                }
-            }
+        // Wait until the 2nd message got delivered to consumer
+        consumer2.receive(1);
 
-            assertEquals(replicator.getStats().replicationBacklog, 0);
-        }
+        Awaitility.await().untilAsserted(() -> assertEquals(replicator.getStats().replicationBacklog, 0));
     }
 
     /**


(pulsar) 01/05: [fix][test] Fix flaky SubscriptionSeekTest.testSeekWillNotEncounteredFencedError by counting subscription is fenced only after seek (#24865)

Posted by lh...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

lhotari pushed a commit to branch branch-3.0
in repository https://gitbox.apache.org/repos/asf/pulsar.git

commit 37c024c1167c62ed204194ab1fca55f871e89ad8
Author: sinan liu <li...@gmail.com>
AuthorDate: Sat Oct 18 03:22:32 2025 +0800

    [fix][test] Fix flaky SubscriptionSeekTest.testSeekWillNotEncounteredFencedError by counting subscription is fenced only after seek (#24865)
    
    (cherry picked from commit 678db6b34587b0042235f0d31e4c406bb0263bcd)
---
 .../apache/pulsar/broker/service/SubscriptionSeekTest.java    | 11 +++++++----
 1 file changed, 7 insertions(+), 4 deletions(-)

diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/SubscriptionSeekTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/SubscriptionSeekTest.java
index fb3f0dc4302..a06716d54b9 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/SubscriptionSeekTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/SubscriptionSeekTest.java
@@ -38,6 +38,7 @@ import java.util.UUID;
 import java.util.concurrent.CompletableFuture;
 import java.util.concurrent.ExecutionException;
 import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicInteger;
 import java.util.function.Function;
 import lombok.Cleanup;
@@ -1035,11 +1036,14 @@ public class SubscriptionSeekTest extends BrokerTestBase {
         // Create a pulsar client with a subscription fenced counter.
         ClientBuilderImpl clientBuilder = (ClientBuilderImpl) PulsarClient.builder().serviceUrl(lookupUrl.toString());
         AtomicInteger receivedFencedErrorCounter = new AtomicInteger();
+        // Count switch: Default off, turn on again before seek starts.
+        final AtomicBoolean countAfterSeek = new AtomicBoolean(false);
         @Cleanup
         PulsarClient client = InjectedClientCnxClientBuilder.create(clientBuilder, (conf, eventLoopGroup) ->
                 new ClientCnx(conf, eventLoopGroup) {
                     protected void handleError(CommandError error) {
-                        if (error.getMessage() != null && error.getMessage().contains("Subscription is fenced")) {
+                        if (error.getMessage() != null && error.getMessage().contains("Subscription is fenced")
+                                && countAfterSeek.get()) {
                             receivedFencedErrorCounter.incrementAndGet();
                         }
                         super.handleError(error);
@@ -1076,10 +1080,9 @@ public class SubscriptionSeekTest extends BrokerTestBase {
             assertNotNull(msg);
             consumer.acknowledge(msg);
         }
+        countAfterSeek.set(true);
         consumer.seek(msgId1);
-        Awaitility.await().untilAsserted(() -> {
-            assertTrue(consumer.isConnected());
-        });
+        Awaitility.await().untilAsserted(() -> assertTrue(consumer.isConnected()));
         assertEquals(receivedFencedErrorCounter.get(), 0);
 
         // cleanup.