You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pulsar.apache.org by "Dream95 (via GitHub)" <gi...@apache.org> on 2026/09/16 12:47:19 UTC

[PR] [fix][test] Make KeyShared draining-hashes delivery test deterministic [pulsar]

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

   <!--
   ### 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 #26568
   
   <!-- 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
   
   CI fails in `KeySharedSubscriptionTest.resetDefaultNamespace` with:
   Topic has 8005 clients connected Including 8004 consumers, 0 producers, and 0 replicators.
   
   
   Example: https://github.com/apache/pulsar/actions/runs/34130276934/job/101987362625
   
   The leftover clients come from `testMessageDeliveredFromDrainingHashes`. That test used `addConsumersUntilOwnerChanged`, which kept creating Key_Shared consumers until consistent hashing moved `testMessageKey` off the original owner.
   With `subscriptionKeySharedConsistentHashingReplicaPoints=100` and a large hash space, a randomly named consumer often does not steal that hash. The loop can create thousands of consumers (8004 in the failure). The test then cannot finish cleanup before `@AfterMethod`, so `resetDefaultNamespace` cannot delete the topic.
   
   
   <!-- Explain here the context, and why you're making that change. What is the problem you're trying to solve. -->
   
   ### Modifications
   
   Replace `addConsumersUntilOwnerChanged` with `addConsumerThatTakesOverHash`. It picks a consumer name (`takeover-N`) that will own the target hash, subscribes that one consumer, and fails if the owner did not change.
   `findConsumerNameThatTakesHash` builds a local `ConsistentHashingStickyKeyConsumerSelector` with the live replica-point count and `selector.getKeyHashRange().getEnd()`. 
   Cleanup only has that extra consumer to close. `findOwnerName` uses `selector.select(hash)`.
   
   
   <!-- Describe the modifications you've done. -->
   
   ### Verifying this change
   
   - [x] Make sure that the change passes the CI checks.
   
   This change is already covered by existing tests, such as`KeySharedSubscriptionTest.testMessageDeliveredFromDrainingHashes`.
   Ran that method locally 500 times. All passed.
   
   ### 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][test] Make KeyShared draining-hashes delivery test deterministic [pulsar]

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


##########
pulsar-broker/src/test/java/org/apache/pulsar/client/api/KeySharedSubscriptionTest.java:
##########
@@ -978,75 +977,92 @@ void testMessageDeliveredFromDrainingHashes() throws PulsarClientException {
         StickyKeyConsumerSelector selector = dispatcher.getSelector();
         int messageKeyHash = selector.makeStickyKeyHash(messageKey.getBytes(StandardCharsets.UTF_8));
 
+        Consumer<Integer> newOwner = null;
         try {
-            // add new consumers until hash range of the initial message owner moved
-            Pair<String, List<Consumer<Integer>>> addedConsumers = addConsumersUntilOwnerChanged(
-                    topic, initialOwnerName, messageKeyHash, selector
-            );
-            String currentOwnerName = addedConsumers.getKey();
-            consumers.addAll(addedConsumers.getValue());
+            // move the hash of the message key away from the initial owner
+            newOwner = addConsumerThatTakesOverHash(topic, initialOwnerName, messageKeyHash, selector);
 
             // returning hash range to the initial owner
-            for (int i = consumers.size() - 1; i > -1 && !initialOwnerName.equals(currentOwnerName); i--) {
-                consumers.remove(i).close();
-                currentOwnerName = findOwnerName(selector, messageKeyHash);
-            }
+            newOwner.close();
+            assertThat(findOwnerName(selector, messageKeyHash)).isEqualTo(initialOwnerName);
 
-            // add new consumers until hash range of the initial message owner moved
-            Pair<String, List<Consumer<Integer>>> addedConsumersAfter = addConsumersUntilOwnerChanged(
-                    topic, initialOwnerName, messageKeyHash, selector
-            );
-
-            String currentOwnerNameAfter = addedConsumersAfter.getKey();
-            consumers.addAll(addedConsumersAfter.getValue());
+            // move the hash of the message key away from the initial owner again
+            newOwner = addConsumerThatTakesOverHash(topic, initialOwnerName, messageKeyHash, selector);
 
             // remove the initial owner
             consumer.close();
 
             // verify the message sent to new consumer which owns hash range
-            Optional<Consumer<Integer>> theNewOwnerMaybe = consumers
-                    .stream()
-                    .filter(c -> c.getConsumerName().equals(currentOwnerNameAfter))
-                    .findAny();
-
-            assertThat(theNewOwnerMaybe).isPresent();
-
-            Consumer<Integer> theNewOwner = theNewOwnerMaybe.get();
-
-            Message<Integer> message = theNewOwner.receive(5, TimeUnit.SECONDS);
+            Message<Integer> message = newOwner.receive(5, TimeUnit.SECONDS);
             assertThat(message).describedAs("Message with key " + messageKey
-                    + " expected to be delivered to consumer " + theNewOwner.getConsumerName()).isNotNull();
+                    + " expected to be delivered to consumer " + newOwner.getConsumerName()).isNotNull();
             assertThat(message.getKey()).isEqualTo(messageKey);
         } finally {
-            for (Consumer<Integer> c : consumers) {
-                c.close();
+            if (newOwner != null) {
+                newOwner.close();
             }
         }
     }
 
-    private Pair<String, List<Consumer<Integer>>> addConsumersUntilOwnerChanged(
+    private Consumer<Integer> addConsumerThatTakesOverHash(
             String topic,
             String initialOwnerName,
             int messageKeyHash,
             StickyKeyConsumerSelector selector
     ) throws PulsarClientException {
-        String currentOwnerName;
-        List<Consumer<Integer>> consumers = new ArrayList<>();
-        do {
-            Consumer<Integer> addedC = createConsumer(topic);
-            consumers.add(addedC);
-            currentOwnerName = findOwnerName(selector, messageKeyHash);
-        } while (initialOwnerName.equals(currentOwnerName));
-        return Pair.of(currentOwnerName, consumers);
+        String takeoverName = findConsumerNameThatTakesHash(selector, initialOwnerName, messageKeyHash);
+        Consumer<Integer> added = createConsumerWithName(topic, takeoverName);
+        String currentOwnerName = findOwnerName(selector, messageKeyHash);
+        if (!takeoverName.equals(currentOwnerName)) {
+            added.close();
+            fail("Consumer " + takeoverName + " was expected to take over the hash " + messageKeyHash
+                    + ", but the owner is " + currentOwnerName);
+        }
+        return added;
+    }
+
+    /**
+     * Predicts which consumer name will take over the given hash from its current owner once a
+     * consumer with that name joins the subscription.
+     */
+    private String findConsumerNameThatTakesHash(StickyKeyConsumerSelector selector, String initialOwnerName,
+                                                 int messageKeyHash) {
+        Range range = selector.getKeyHashRange();
+        ConsistentHashingStickyKeyConsumerSelector probe = new ConsistentHashingStickyKeyConsumerSelector(
+                conf.getSubscriptionKeySharedConsistentHashingReplicaPoints(), false, range.getEnd());
+        Set<String> existingNames = new HashSet<>();
+        for (var existing : selector.getConsumerKeyHashRanges().keySet()) {
+            existingNames.add(existing.consumerName());
+            probe.addConsumer(mockBrokerConsumer(existing.consumerName())).join();
+        }
+        for (int i = 0; ; i++) {
+            String name = "takeover-" + i;
+            if (!existingNames.add(name)) {
+                continue;
+            }

Review Comment:
   **[INTENT MISMATCH] Choose a suitable initial name and bound the takeover search**
   
   The initial consumer still gets a random five-character name. With the valid name `00807`, the modern selector's replica point 78 (`00807` + NUL + `0` + NUL + `78`) and `testMessageKey` both hash to slot **21672** with the default 100 points and range 1..65535. The existing ring point always wins: `putIfAbsent` retains its owner, and `select` uses `ceilingEntry`. No `takeover-N` can therefore succeed. This loop never terminates, and `existingNames` keeps every attempted name.
   
   The collision also affected the old loop, but moving the search into a probe does not resolve this case of the flaky test. Please give the initial consumer a fixed suitable name (or choose a compatible pair), bound the search, and cover the exact-point case.



-- 
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][test] Make KeyShared draining-hashes delivery test deterministic [pulsar]

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


##########
pulsar-broker/src/test/java/org/apache/pulsar/client/api/KeySharedSubscriptionTest.java:
##########
@@ -978,75 +979,98 @@ void testMessageDeliveredFromDrainingHashes() throws PulsarClientException {
         StickyKeyConsumerSelector selector = dispatcher.getSelector();
         int messageKeyHash = selector.makeStickyKeyHash(messageKey.getBytes(StandardCharsets.UTF_8));
 
+        Consumer<Integer> newOwner = null;
         try {
-            // add new consumers until hash range of the initial message owner moved
-            Pair<String, List<Consumer<Integer>>> addedConsumers = addConsumersUntilOwnerChanged(
-                    topic, initialOwnerName, messageKeyHash, selector
-            );
-            String currentOwnerName = addedConsumers.getKey();
-            consumers.addAll(addedConsumers.getValue());
+            // move the hash of the message key away from the initial owner
+            newOwner = addConsumerThatTakesOverHash(topic, initialOwnerName, messageKeyHash, selector);
 
             // returning hash range to the initial owner
-            for (int i = consumers.size() - 1; i > -1 && !initialOwnerName.equals(currentOwnerName); i--) {
-                consumers.remove(i).close();
-                currentOwnerName = findOwnerName(selector, messageKeyHash);
-            }
-
-            // add new consumers until hash range of the initial message owner moved
-            Pair<String, List<Consumer<Integer>>> addedConsumersAfter = addConsumersUntilOwnerChanged(
-                    topic, initialOwnerName, messageKeyHash, selector
-            );
+            newOwner.close();
+            assertThat(findOwnerName(selector, messageKeyHash)).isEqualTo(initialOwnerName);
 
-            String currentOwnerNameAfter = addedConsumersAfter.getKey();
-            consumers.addAll(addedConsumersAfter.getValue());
+            // move the hash of the message key away from the initial owner again
+            newOwner = addConsumerThatTakesOverHash(topic, initialOwnerName, messageKeyHash, selector);
 
             // remove the initial owner
             consumer.close();
 
             // verify the message sent to new consumer which owns hash range
-            Optional<Consumer<Integer>> theNewOwnerMaybe = consumers
-                    .stream()
-                    .filter(c -> c.getConsumerName().equals(currentOwnerNameAfter))
-                    .findAny();
-
-            assertThat(theNewOwnerMaybe).isPresent();
-
-            Consumer<Integer> theNewOwner = theNewOwnerMaybe.get();
-
-            Message<Integer> message = theNewOwner.receive(5, TimeUnit.SECONDS);
+            Message<Integer> message = newOwner.receive(5, TimeUnit.SECONDS);
             assertThat(message).describedAs("Message with key " + messageKey
-                    + " expected to be delivered to consumer " + theNewOwner.getConsumerName()).isNotNull();
+                    + " expected to be delivered to consumer " + newOwner.getConsumerName()).isNotNull();
             assertThat(message.getKey()).isEqualTo(messageKey);
         } finally {
-            for (Consumer<Integer> c : consumers) {
-                c.close();
+            if (newOwner != null) {
+                newOwner.close();
             }
         }
     }
 
-    private Pair<String, List<Consumer<Integer>>> addConsumersUntilOwnerChanged(
+    private Consumer<Integer> addConsumerThatTakesOverHash(
             String topic,
             String initialOwnerName,
             int messageKeyHash,
             StickyKeyConsumerSelector selector
     ) throws PulsarClientException {
-        String currentOwnerName;
-        List<Consumer<Integer>> consumers = new ArrayList<>();
-        do {
-            Consumer<Integer> addedC = createConsumer(topic);
-            consumers.add(addedC);
-            currentOwnerName = findOwnerName(selector, messageKeyHash);
-        } while (initialOwnerName.equals(currentOwnerName));
-        return Pair.of(currentOwnerName, consumers);
+        String takeoverName = findConsumerNameThatTakesHash(selector, initialOwnerName, messageKeyHash);
+        Consumer<Integer> added = createConsumerWithName(topic, takeoverName);
+        String currentOwnerName = findOwnerName(selector, messageKeyHash);
+        if (!takeoverName.equals(currentOwnerName)) {
+            added.close();
+            fail("Consumer " + takeoverName + " was expected to take over the hash " + messageKeyHash
+                    + ", but the owner is " + currentOwnerName);
+        }
+        return added;
+    }
+
+    /**
+     * Predicts which consumer name will take over the given hash from its current owner once a
+     * consumer with that name joins the subscription.
+     */
+    private String findConsumerNameThatTakesHash(StickyKeyConsumerSelector selector, String initialOwnerName,
+                                                 int messageKeyHash) {
+        Range range = selector.getKeyHashRange();
+        ConsistentHashingStickyKeyConsumerSelector probe = new ConsistentHashingStickyKeyConsumerSelector(
+                conf.getSubscriptionKeySharedConsistentHashingReplicaPoints(), false, range.getEnd());
+        Set<String> existingNames = new HashSet<>();
+        for (var existing : selector.getConsumerKeyHashRanges().keySet()) {
+            existingNames.add(existing.consumerName());
+            probe.addConsumer(mockBrokerConsumer(existing.consumerName())).join();
+        }
+        // Search the whole hash-key space. If no name takes over the hash once it's exhausted, an exact
+        // hash-point collision means takeover can't happen, so fail fast instead of looping.
+        int maxAttempts = selector.getKeyHashRange().getEnd();
+        for (int i = 0; i <maxAttempts ; i++) {

Review Comment:
   **[BUG] checkstyle fails on the new lines**
   
   `./gradlew :pulsar-broker:checkstyleTest` reports 3 errors in this file: `topic,"initial-owner"` at line 967 needs a space after the comma, and this line needs `i < maxAttempts; i++`. Please also add the missing space in the failure message (`"slots)"` renders as `65535slots)`). `./gradlew quickCheck` runs the same check.



##########
pulsar-broker/src/test/java/org/apache/pulsar/client/api/KeySharedSubscriptionTest.java:
##########
@@ -978,75 +979,98 @@ void testMessageDeliveredFromDrainingHashes() throws PulsarClientException {
         StickyKeyConsumerSelector selector = dispatcher.getSelector();
         int messageKeyHash = selector.makeStickyKeyHash(messageKey.getBytes(StandardCharsets.UTF_8));
 
+        Consumer<Integer> newOwner = null;
         try {
-            // add new consumers until hash range of the initial message owner moved
-            Pair<String, List<Consumer<Integer>>> addedConsumers = addConsumersUntilOwnerChanged(
-                    topic, initialOwnerName, messageKeyHash, selector
-            );
-            String currentOwnerName = addedConsumers.getKey();
-            consumers.addAll(addedConsumers.getValue());
+            // move the hash of the message key away from the initial owner
+            newOwner = addConsumerThatTakesOverHash(topic, initialOwnerName, messageKeyHash, selector);
 
             // returning hash range to the initial owner
-            for (int i = consumers.size() - 1; i > -1 && !initialOwnerName.equals(currentOwnerName); i--) {
-                consumers.remove(i).close();
-                currentOwnerName = findOwnerName(selector, messageKeyHash);
-            }
-
-            // add new consumers until hash range of the initial message owner moved
-            Pair<String, List<Consumer<Integer>>> addedConsumersAfter = addConsumersUntilOwnerChanged(
-                    topic, initialOwnerName, messageKeyHash, selector
-            );
+            newOwner.close();
+            assertThat(findOwnerName(selector, messageKeyHash)).isEqualTo(initialOwnerName);
 
-            String currentOwnerNameAfter = addedConsumersAfter.getKey();
-            consumers.addAll(addedConsumersAfter.getValue());
+            // move the hash of the message key away from the initial owner again
+            newOwner = addConsumerThatTakesOverHash(topic, initialOwnerName, messageKeyHash, selector);
 
             // remove the initial owner
             consumer.close();
 
             // verify the message sent to new consumer which owns hash range
-            Optional<Consumer<Integer>> theNewOwnerMaybe = consumers
-                    .stream()
-                    .filter(c -> c.getConsumerName().equals(currentOwnerNameAfter))
-                    .findAny();
-
-            assertThat(theNewOwnerMaybe).isPresent();
-
-            Consumer<Integer> theNewOwner = theNewOwnerMaybe.get();
-
-            Message<Integer> message = theNewOwner.receive(5, TimeUnit.SECONDS);
+            Message<Integer> message = newOwner.receive(5, TimeUnit.SECONDS);
             assertThat(message).describedAs("Message with key " + messageKey
-                    + " expected to be delivered to consumer " + theNewOwner.getConsumerName()).isNotNull();
+                    + " expected to be delivered to consumer " + newOwner.getConsumerName()).isNotNull();
             assertThat(message.getKey()).isEqualTo(messageKey);
         } finally {
-            for (Consumer<Integer> c : consumers) {
-                c.close();
+            if (newOwner != null) {
+                newOwner.close();
             }
         }
     }
 
-    private Pair<String, List<Consumer<Integer>>> addConsumersUntilOwnerChanged(
+    private Consumer<Integer> addConsumerThatTakesOverHash(
             String topic,
             String initialOwnerName,
             int messageKeyHash,
             StickyKeyConsumerSelector selector
     ) throws PulsarClientException {
-        String currentOwnerName;
-        List<Consumer<Integer>> consumers = new ArrayList<>();
-        do {
-            Consumer<Integer> addedC = createConsumer(topic);
-            consumers.add(addedC);
-            currentOwnerName = findOwnerName(selector, messageKeyHash);
-        } while (initialOwnerName.equals(currentOwnerName));
-        return Pair.of(currentOwnerName, consumers);
+        String takeoverName = findConsumerNameThatTakesHash(selector, initialOwnerName, messageKeyHash);
+        Consumer<Integer> added = createConsumerWithName(topic, takeoverName);
+        String currentOwnerName = findOwnerName(selector, messageKeyHash);
+        if (!takeoverName.equals(currentOwnerName)) {
+            added.close();
+            fail("Consumer " + takeoverName + " was expected to take over the hash " + messageKeyHash
+                    + ", but the owner is " + currentOwnerName);
+        }
+        return added;
+    }
+
+    /**
+     * Predicts which consumer name will take over the given hash from its current owner once a
+     * consumer with that name joins the subscription.
+     */
+    private String findConsumerNameThatTakesHash(StickyKeyConsumerSelector selector, String initialOwnerName,
+                                                 int messageKeyHash) {
+        Range range = selector.getKeyHashRange();
+        ConsistentHashingStickyKeyConsumerSelector probe = new ConsistentHashingStickyKeyConsumerSelector(
+                conf.getSubscriptionKeySharedConsistentHashingReplicaPoints(), false, range.getEnd());
+        Set<String> existingNames = new HashSet<>();
+        for (var existing : selector.getConsumerKeyHashRanges().keySet()) {
+            existingNames.add(existing.consumerName());
+            probe.addConsumer(mockBrokerConsumer(existing.consumerName())).join();
+        }
+        // Search the whole hash-key space. If no name takes over the hash once it's exhausted, an exact
+        // hash-point collision means takeover can't happen, so fail fast instead of looping.
+        int maxAttempts = selector.getKeyHashRange().getEnd();

Review Comment:
   **[NIT] the search bound is larger than needed and the comment overstates what a failure proves**
   
   `getKeyHashRange().getEnd()` is 65535 names, each adding and removing 100 replica points on a mock. That is the worst case, and the test needs only three names today. Exhausting 65535 names also does not prove an exact-point collision, so the comment is not quite right. A small fixed budget such as 1000 attempts, with a message that says no name took over the hash, would fail faster and say the same thing.



##########
pulsar-broker/src/test/java/org/apache/pulsar/client/api/KeySharedSubscriptionTest.java:
##########
@@ -978,75 +977,92 @@ void testMessageDeliveredFromDrainingHashes() throws PulsarClientException {
         StickyKeyConsumerSelector selector = dispatcher.getSelector();
         int messageKeyHash = selector.makeStickyKeyHash(messageKey.getBytes(StandardCharsets.UTF_8));
 
+        Consumer<Integer> newOwner = null;
         try {
-            // add new consumers until hash range of the initial message owner moved
-            Pair<String, List<Consumer<Integer>>> addedConsumers = addConsumersUntilOwnerChanged(
-                    topic, initialOwnerName, messageKeyHash, selector
-            );
-            String currentOwnerName = addedConsumers.getKey();
-            consumers.addAll(addedConsumers.getValue());
+            // move the hash of the message key away from the initial owner
+            newOwner = addConsumerThatTakesOverHash(topic, initialOwnerName, messageKeyHash, selector);
 
             // returning hash range to the initial owner
-            for (int i = consumers.size() - 1; i > -1 && !initialOwnerName.equals(currentOwnerName); i--) {
-                consumers.remove(i).close();
-                currentOwnerName = findOwnerName(selector, messageKeyHash);
-            }
+            newOwner.close();
+            assertThat(findOwnerName(selector, messageKeyHash)).isEqualTo(initialOwnerName);
 
-            // add new consumers until hash range of the initial message owner moved
-            Pair<String, List<Consumer<Integer>>> addedConsumersAfter = addConsumersUntilOwnerChanged(
-                    topic, initialOwnerName, messageKeyHash, selector
-            );
-
-            String currentOwnerNameAfter = addedConsumersAfter.getKey();
-            consumers.addAll(addedConsumersAfter.getValue());
+            // move the hash of the message key away from the initial owner again
+            newOwner = addConsumerThatTakesOverHash(topic, initialOwnerName, messageKeyHash, selector);
 
             // remove the initial owner
             consumer.close();
 
             // verify the message sent to new consumer which owns hash range
-            Optional<Consumer<Integer>> theNewOwnerMaybe = consumers
-                    .stream()
-                    .filter(c -> c.getConsumerName().equals(currentOwnerNameAfter))
-                    .findAny();
-
-            assertThat(theNewOwnerMaybe).isPresent();
-
-            Consumer<Integer> theNewOwner = theNewOwnerMaybe.get();
-
-            Message<Integer> message = theNewOwner.receive(5, TimeUnit.SECONDS);
+            Message<Integer> message = newOwner.receive(5, TimeUnit.SECONDS);
             assertThat(message).describedAs("Message with key " + messageKey
-                    + " expected to be delivered to consumer " + theNewOwner.getConsumerName()).isNotNull();
+                    + " expected to be delivered to consumer " + newOwner.getConsumerName()).isNotNull();
             assertThat(message.getKey()).isEqualTo(messageKey);
         } finally {
-            for (Consumer<Integer> c : consumers) {
-                c.close();
+            if (newOwner != null) {
+                newOwner.close();
             }
         }
     }
 
-    private Pair<String, List<Consumer<Integer>>> addConsumersUntilOwnerChanged(
+    private Consumer<Integer> addConsumerThatTakesOverHash(
             String topic,
             String initialOwnerName,
             int messageKeyHash,
             StickyKeyConsumerSelector selector
     ) throws PulsarClientException {
-        String currentOwnerName;
-        List<Consumer<Integer>> consumers = new ArrayList<>();
-        do {
-            Consumer<Integer> addedC = createConsumer(topic);
-            consumers.add(addedC);
-            currentOwnerName = findOwnerName(selector, messageKeyHash);
-        } while (initialOwnerName.equals(currentOwnerName));
-        return Pair.of(currentOwnerName, consumers);
+        String takeoverName = findConsumerNameThatTakesHash(selector, initialOwnerName, messageKeyHash);
+        Consumer<Integer> added = createConsumerWithName(topic, takeoverName);
+        String currentOwnerName = findOwnerName(selector, messageKeyHash);
+        if (!takeoverName.equals(currentOwnerName)) {
+            added.close();
+            fail("Consumer " + takeoverName + " was expected to take over the hash " + messageKeyHash
+                    + ", but the owner is " + currentOwnerName);
+        }
+        return added;
+    }
+
+    /**
+     * Predicts which consumer name will take over the given hash from its current owner once a
+     * consumer with that name joins the subscription.
+     */
+    private String findConsumerNameThatTakesHash(StickyKeyConsumerSelector selector, String initialOwnerName,
+                                                 int messageKeyHash) {
+        Range range = selector.getKeyHashRange();
+        ConsistentHashingStickyKeyConsumerSelector probe = new ConsistentHashingStickyKeyConsumerSelector(
+                conf.getSubscriptionKeySharedConsistentHashingReplicaPoints(), false, range.getEnd());
+        Set<String> existingNames = new HashSet<>();
+        for (var existing : selector.getConsumerKeyHashRanges().keySet()) {
+            existingNames.add(existing.consumerName());
+            probe.addConsumer(mockBrokerConsumer(existing.consumerName())).join();
+        }
+        for (int i = 0; ; i++) {
+            String name = "takeover-" + i;
+            if (!existingNames.add(name)) {
+                continue;
+            }

Review Comment:
   Thanks, the fixed name resolves the non-terminating case. I checked the replica points: `initial-owner` has no point at slot 21672, and `takeover-2` wins in both rounds, so the test is now deterministic. The bounded loop with `fail(...)` is also good. The exact-point case is avoided by the name choice rather than covered, which I am fine with for this test. Please fix the checkstyle errors I listed in the new comment and I think this is ready.



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