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 2026/10/20 21:57:27 UTC

(pulsar) branch master updated: [fix][broker] Don't continue the REST topic listings that waited for a size estimate one after another on a metadata store thread (#27017)

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

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


The following commit(s) were added to refs/heads/master by this push:
     new 18ed987ae273 [fix][broker] Don't continue the REST topic listings that waited for a size estimate one after another on a metadata store thread (#27017)
18ed987ae273 is described below

commit 18ed987ae273c0690e4a53a64abbeb4830d53110
Author: Lari Hotari <lh...@users.noreply.github.com>
AuthorDate: Wed Oct 21 00:57:19 2026 +0300

    [fix][broker] Don't continue the REST topic listings that waited for a size estimate one after another on a metadata store thread (#27017)
---
 .../admin/impl/TopicListResponseMemoryLimiter.java | 14 +++-
 .../impl/TopicListResponseMemoryLimiterTest.java   | 87 ++++++++++++++++++++++
 .../semaphore/AsyncDualMemoryLimiterImpl.java      |  9 +++
 3 files changed, 107 insertions(+), 3 deletions(-)

diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/impl/TopicListResponseMemoryLimiter.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/impl/TopicListResponseMemoryLimiter.java
index 7f11764c0b7a..aeafdf781906 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/impl/TopicListResponseMemoryLimiter.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/impl/TopicListResponseMemoryLimiter.java
@@ -34,6 +34,7 @@ import org.apache.pulsar.broker.topiclistlimit.TopicListing;
 import org.apache.pulsar.broker.web.RestException;
 import org.apache.pulsar.common.semaphore.AsyncDualMemoryLimiter;
 import org.apache.pulsar.common.semaphore.AsyncDualMemoryLimiter.AsyncDualMemoryLimiterPermit;
+import org.apache.pulsar.common.semaphore.AsyncDualMemoryLimiterImpl;
 import org.apache.pulsar.common.semaphore.AsyncDualMemoryLimiterUtil;
 import org.apache.pulsar.common.semaphore.AsyncSemaphore;
 import org.apache.pulsar.common.util.FutureUtil;
@@ -117,10 +118,17 @@ public final class TopicListResponseMemoryLimiter {
             Function<CollectedT, CompletableFuture<List<String>>> topicsSupplier) {
         TopicListSizeResultCache sizeCache = brokerService.getTopicListSizeResultCache();
         TopicListSizeResultCache.ResultHolder listSizeHolder = sizeCache.getTopicListSize(listing, properties);
-        ResponsePermits permits =
-                new ResponsePermits(brokerService.getMaxTopicListInFlightLimiter(), response, listSizeHolder);
+        AsyncDualMemoryLimiterImpl limiter = brokerService.getMaxTopicListInFlightLimiter();
+        ResponsePermits permits = new ResponsePermits(limiter, response, listSizeHolder);
         response.register(permits);
-        return listSizeHolder.getSizeAsync()
+        CompletableFuture<Long> sizeFuture = listSizeHolder.getSizeAsync();
+        if (!sizeFuture.isDone()) {
+            // The concurrent requests of a listing without a size estimate wait for the first request's estimate.
+            // When it completes, on a metadata store thread, their continuations would run one after another on
+            // that thread, so continue on the limiter's completion executor instead.
+            sizeFuture = sizeFuture.thenApplyAsync(Function.identity(), limiter.getCompletionExecutor());
+        }
+        return sizeFuture
                 .thenCompose(initialSize -> {
                     if (initialSize > sizeCache.getSizeLimit()) {
                         // the permits can't be granted, skip collecting
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/impl/TopicListResponseMemoryLimiterTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/impl/TopicListResponseMemoryLimiterTest.java
index 0fa068c70c55..2d02687171ff 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/impl/TopicListResponseMemoryLimiterTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/impl/TopicListResponseMemoryLimiterTest.java
@@ -22,7 +22,9 @@ import static org.assertj.core.api.Assertions.assertThat;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyLong;
 import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
@@ -30,8 +32,12 @@ import jakarta.ws.rs.container.AsyncResponse;
 import jakarta.ws.rs.container.CompletionCallback;
 import jakarta.ws.rs.core.Response;
 import java.time.Duration;
+import java.util.ArrayList;
 import java.util.List;
+import java.util.Queue;
 import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.Executor;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicInteger;
@@ -116,6 +122,87 @@ public class TopicListResponseMemoryLimiterTest {
         assertThat(acquiredHeapPermits()).isZero();
     }
 
+    @Test
+    public void testRequestsWaitingForTheSizeEstimateContinueOnTheCompletionExecutor() {
+        // the first request lists the topics without a size estimate, the concurrent requests wait for its estimate
+        CompletableFuture<List<String>> firstListing = new CompletableFuture<>();
+        CompletableFuture<List<String>> first = listTopics(() -> firstListing);
+        List<CompletableFuture<String>> listingThreads = new ArrayList<>();
+        List<CompletableFuture<List<String>>> waiting = new ArrayList<>();
+        for (int i = 0; i < 3; i++) {
+            CompletableFuture<String> listingThread = new CompletableFuture<>();
+            listingThreads.add(listingThread);
+            waiting.add(listTopics(() -> {
+                listingThread.complete(Thread.currentThread().getName());
+                return CompletableFuture.completedFuture(TOPICS);
+            }));
+        }
+
+        // completing the first listing, here on the test thread, completes the size estimate
+        firstListing.complete(TOPICS);
+
+        assertThat(first).succeedsWithin(Duration.ofSeconds(5)).isEqualTo(TOPICS);
+        String testThread = Thread.currentThread().getName();
+        for (int i = 0; i < waiting.size(); i++) {
+            assertThat(waiting.get(i)).succeedsWithin(Duration.ofSeconds(5)).isEqualTo(TOPICS);
+            // the waiting requests don't continue one after another on the thread that completed the estimate
+            assertThat(listingThreads.get(i)).isCompleted();
+            assertThat(listingThreads.get(i).join()).isNotEqualTo(testThread)
+                    .startsWith("async-dual-memory-limiter-completion");
+        }
+    }
+
+    @Test
+    public void testDoesNotListTopicsWhenResponseCompletesWhileWaitingForTheCompletionExecutor() {
+        // gate the completion executor so that the continuation of a request waiting for the size estimate stays
+        // queued until the test runs it
+        Queue<Runnable> queuedTasks = new ConcurrentLinkedQueue<>();
+        AsyncDualMemoryLimiterImpl gatedLimiter = spy(limiter);
+        doReturn((Executor) queuedTasks::add).when(gatedLimiter).getCompletionExecutor();
+        when(brokerService.getMaxTopicListInFlightLimiter()).thenReturn(gatedLimiter);
+
+        // the first request lists the topics without a size estimate, the second request waits for its estimate
+        CompletableFuture<List<String>> firstListing = new CompletableFuture<>();
+        CompletableFuture<List<String>> first = listTopics(() -> firstListing);
+        CompletionCallback firstCompletionCallback = completionCallback.get();
+        AsyncResponse waitingResponse = mock(AsyncResponse.class);
+        AtomicBoolean waitingResponseDone = new AtomicBoolean();
+        AtomicReference<CompletionCallback> waitingCompletionCallback = new AtomicReference<>();
+        when(waitingResponse.isDone()).thenAnswer(__ -> waitingResponseDone.get());
+        doAnswer(invocation -> {
+            waitingCompletionCallback.set(invocation.getArgument(0));
+            return List.of();
+        }).when(waitingResponse).register(any(Object.class));
+        AtomicInteger listingCalls = new AtomicInteger();
+        CompletableFuture<List<String>> waiting = TopicListResponseMemoryLimiter.listTopics(brokerService,
+                waitingResponse, TopicListing.namespaceTopics(NAMESPACE, Mode.PERSISTENT), null, () -> {
+                    listingCalls.incrementAndGet();
+                    return CompletableFuture.completedFuture(TOPICS);
+                });
+
+        // completing the first listing completes the size estimate and queues the waiting request's continuation
+        firstListing.complete(TOPICS);
+        assertThat(first).succeedsWithin(Duration.ofSeconds(5)).isEqualTo(TOPICS);
+        assertThat(queuedTasks).hasSize(1);
+        assertThat(waiting).isNotDone();
+
+        // the waiting request's response times out before its continuation runs
+        waitingResponseDone.set(true);
+        waitingCompletionCallback.get().onComplete(null);
+        Runnable task;
+        while ((task = queuedTasks.poll()) != null) {
+            task.run();
+        }
+
+        assertThat(waiting).failsWithin(Duration.ofSeconds(5));
+        assertThat(listingCalls).hasValue(0);
+        // only the first request holds permits until its response completes
+        assertThat(acquiredHeapPermits()).isEqualTo(TopicListMemoryLimiter.estimateTopicListSize(TOPICS));
+        responseDone.set(true);
+        firstCompletionCallback.onComplete(null);
+        assertThat(acquiredHeapPermits()).isZero();
+    }
+
     @Test
     public void testDoesNotListTopicsWhenResponseIsAlreadyDone() {
         responseDone.set(true);
diff --git a/pulsar-common/src/main/java/org/apache/pulsar/common/semaphore/AsyncDualMemoryLimiterImpl.java b/pulsar-common/src/main/java/org/apache/pulsar/common/semaphore/AsyncDualMemoryLimiterImpl.java
index 5e24190790e2..4551457f510a 100644
--- a/pulsar-common/src/main/java/org/apache/pulsar/common/semaphore/AsyncDualMemoryLimiterImpl.java
+++ b/pulsar-common/src/main/java/org/apache/pulsar/common/semaphore/AsyncDualMemoryLimiterImpl.java
@@ -21,6 +21,7 @@ package org.apache.pulsar.common.semaphore;
 import com.google.common.annotations.VisibleForTesting;
 import io.netty.util.concurrent.DefaultThreadFactory;
 import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.Executor;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
 import java.util.concurrent.ScheduledExecutorService;
@@ -147,6 +148,14 @@ public class AsyncDualMemoryLimiterImpl implements AsyncDualMemoryLimiter, AutoC
 
     }
 
+    /**
+     * Returns the executor that completes the requests that had to wait for permits. Continuations that would
+     * otherwise run one after another on a single thread can be moved to this executor.
+     */
+    public Executor getCompletionExecutor() {
+        return completionExecutor;
+    }
+
     @Override
     public void close() {
         heapLimiter.close();