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/07/02 02:21:50 UTC
(pulsar) branch branch-4.0 updated (2b1d6a079f6 -> 88405242a01)
This is an automated email from the ASF dual-hosted git repository.
lhotari pushed a change to branch branch-4.0
in repository https://gitbox.apache.org/repos/asf/pulsar.git
from 2b1d6a079f6 [fix][test] Fix flaky SchemaServiceTest.testSchemaRegistryMetrics (#25645)
new 3c47859cafe [fix][test] Fix flaky PersistentTopicsTest setup caused by concurrent Mockito stubbing (#26083)
new 3c4948b613c [fix][test] Run makeReadEntryProbFail's errorOrNot on a caller-provided executor (#26123)
new 88405242a01 [fix][broker] Don't let a closing topic-policies reader abort a concurrent cache-init reload (#26132)
The 3 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:
.../bookkeeper/mledger/impl/ManagedLedgerTest.java | 21 ++--
.../SystemTopicBasedTopicPoliciesService.java | 108 ++++++++-------------
.../pulsar/broker/admin/PersistentTopicsTest.java | 49 +++++++---
.../broker/service/OneWayReplicatorTest.java | 4 +-
.../SystemTopicBasedTopicPoliciesServiceTest.java | 93 ++++++++++++++----
.../PersistentReplicatorInflightTaskTest.java | 21 +++-
6 files changed, 184 insertions(+), 112 deletions(-)
(pulsar) 01/03: [fix][test] Fix flaky PersistentTopicsTest setup caused by concurrent Mockito stubbing (#26083)
Posted by lh...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
lhotari pushed a commit to branch branch-4.0
in repository https://gitbox.apache.org/repos/asf/pulsar.git
commit 3c47859cafecccd262abe6ca7c6e1b69b75b8f18
Author: void-ptr974 <vo...@protonmail.com>
AuthorDate: Wed Jul 1 08:53:02 2026 +0800
[fix][test] Fix flaky PersistentTopicsTest setup caused by concurrent Mockito stubbing (#26083)
(cherry picked from commit aa2d1bc61f0fe82b50848ebcbb569992ef48918d)
---
.../pulsar/broker/admin/PersistentTopicsTest.java | 49 +++++++++++++++-------
1 file changed, 35 insertions(+), 14 deletions(-)
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/PersistentTopicsTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/PersistentTopicsTest.java
index 40df6b0b5ff..626805a7032 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/PersistentTopicsTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/admin/PersistentTopicsTest.java
@@ -30,7 +30,6 @@ import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertSame;
@@ -48,6 +47,7 @@ import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.Function;
import javax.servlet.ServletContext;
import javax.ws.rs.InternalServerErrorException;
import javax.ws.rs.WebApplicationException;
@@ -58,6 +58,7 @@ import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.apache.bookkeeper.mledger.ManagedCursor;
import org.apache.commons.collections4.MapUtils;
+import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.pulsar.broker.BrokerTestUtil;
import org.apache.pulsar.broker.admin.v2.ExtPersistentTopics;
import org.apache.pulsar.broker.admin.v2.NonPersistentTopics;
@@ -129,7 +130,8 @@ public class PersistentTopicsTest extends MockedPulsarServiceBaseTest {
protected Field uriField;
protected UriInfo uriInfo;
private NonPersistentTopics nonPersistentTopic;
- private NamespaceResources namespaceResources;
+ private volatile NamespaceResources namespaceResourcesOverride;
+ private volatile Function<NamespaceName, CompletableFuture<List<String>>> listPersistentTopicsAsyncHandler;
@BeforeClass
public void initPersistentTopics() throws Exception {
@@ -172,7 +174,6 @@ public class PersistentTopicsTest extends MockedPulsarServiceBaseTest {
nonPersistentTopic = spy(NonPersistentTopics.class);
nonPersistentTopic.setServletContext(mock(ServletContext.class));
nonPersistentTopic.setPulsar(pulsar);
- namespaceResources = mock(NamespaceResources.class);
doReturn(false).when(nonPersistentTopic).isRequestHttps();
doReturn(null).when(nonPersistentTopic).originalPrincipal();
doReturn("test").when(nonPersistentTopic).clientAppId();
@@ -180,10 +181,27 @@ public class PersistentTopicsTest extends MockedPulsarServiceBaseTest {
doNothing().when(nonPersistentTopic).validateAdminAccessForTenant(this.testTenant);
doReturn(mock(AuthenticationDataHttps.class)).when(nonPersistentTopic).clientAuthData();
- PulsarResources resources =
- spy(new PulsarResources(pulsar.getLocalMetadataStore(), pulsar.getConfigurationMetadataStore()));
- doReturn(spy(new TopicResources(pulsar.getLocalMetadataStore()))).when(resources).getTopicResources();
- doReturn(resources).when(pulsar).getPulsarResources();
+ TopicResources topicResources = BrokerTestUtil.spyWithoutRecordingInvocations(
+ new TopicResources(pulsar.getLocalMetadataStore()));
+ PulsarResources resources = BrokerTestUtil.spyWithoutRecordingInvocations(
+ new PulsarResources(pulsar.getLocalMetadataStore(), pulsar.getConfigurationMetadataStore()));
+ NamespaceResources namespaceResources = resources.getNamespaceResources();
+ doAnswer(invocation -> {
+ NamespaceResources override = namespaceResourcesOverride;
+ return override != null ? override : namespaceResources;
+ }).when(resources).getNamespaceResources();
+ doReturn(topicResources).when(resources).getTopicResources();
+ doAnswer(invocation -> {
+ Function<NamespaceName, CompletableFuture<List<String>>> handler = listPersistentTopicsAsyncHandler;
+ if (handler != null) {
+ CompletableFuture<List<String>> result = handler.apply(invocation.getArgument(0));
+ if (result != null) {
+ return result;
+ }
+ }
+ return invocation.callRealMethod();
+ }).when(topicResources).listPersistentTopicsAsync(any());
+ FieldUtils.writeField(pulsar, "pulsarResources", resources, true);
admin.clusters().createCluster("use", ClusterData.builder().serviceUrl("http://127.0.0.3:8082").build());
admin.clusters().createCluster("test", ClusterData.builder().serviceUrl(pulsar.getWebServiceAddress()).build());
@@ -199,6 +217,8 @@ public class PersistentTopicsTest extends MockedPulsarServiceBaseTest {
@Override
@AfterMethod(alwaysRun = true)
protected void cleanup() throws Exception {
+ namespaceResourcesOverride = null;
+ listPersistentTopicsAsyncHandler = null;
super.internalCleanup();
}
@@ -606,8 +626,8 @@ public class PersistentTopicsTest extends MockedPulsarServiceBaseTest {
CompletableFuture<Optional<Policies>> policyFuture = new CompletableFuture<>();
Policies policies = new Policies();
policyFuture.complete(Optional.of(policies));
- when(pulsar.getPulsarResources().getNamespaceResources()).thenReturn(namespaceResources);
- doReturn(policyFuture).when(namespaceResources).getPoliciesAsync(namespaceName);
+ namespaceResourcesOverride = mock(NamespaceResources.class);
+ doReturn(policyFuture).when(namespaceResourcesOverride).getPoliciesAsync(namespaceName);
AsyncResponse response = mock(AsyncResponse.class);
ArgumentCaptor<RestException> errCaptor = ArgumentCaptor.forClass(RestException.class);
persistentTopics.createPartitionedTopic(response, testTenant, testNamespace, topicName, 2, true);
@@ -619,7 +639,7 @@ public class PersistentTopicsTest extends MockedPulsarServiceBaseTest {
// Test policy not exist and return 'Namespace not found'
CompletableFuture<Optional<Policies>> policyFuture2 = new CompletableFuture<>();
policyFuture2.complete(Optional.empty());
- doReturn(policyFuture2).when(namespaceResources).getPoliciesAsync(namespaceName);
+ doReturn(policyFuture2).when(namespaceResourcesOverride).getPoliciesAsync(namespaceName);
response = mock(AsyncResponse.class);
errCaptor = ArgumentCaptor.forClass(RestException.class);
persistentTopics.createPartitionedTopic(response, testTenant, testNamespace, topicName, 2, true);
@@ -653,12 +673,13 @@ public class PersistentTopicsTest extends MockedPulsarServiceBaseTest {
final String nonPartitionTopicName2 = "special-topic-partition-123";
final String partitionedTopicName = "special-topic";
- when(pulsar.getPulsarResources().getTopicResources()
- .listPersistentTopicsAsync(NamespaceName.get("my-tenant/my-namespace")))
- .thenReturn(CompletableFuture.completedFuture(List.of(
+ NamespaceName namespaceName = NamespaceName.get("my-tenant/my-namespace");
+ listPersistentTopicsAsyncHandler = namespace -> namespaceName.equals(namespace)
+ ? CompletableFuture.completedFuture(List.of(
"persistent://my-tenant/my-namespace/" + nonPartitionTopicName1,
"persistent://my-tenant/my-namespace/" + nonPartitionTopicName2
- )));
+ ))
+ : null;
// doReturn(ImmutableSet.of(nonPartitionTopicName1, nonPartitionTopicName2)).when(mockZooKeeperChildrenCache)
// .get(anyString());
// doReturn(CompletableFuture.completedFuture(ImmutableSet.of(nonPartitionTopicName1, nonPartitionTopicName2))
(pulsar) 02/03: [fix][test] Run makeReadEntryProbFail's errorOrNot on a caller-provided executor (#26123)
Posted by lh...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
lhotari pushed a commit to branch branch-4.0
in repository https://gitbox.apache.org/repos/asf/pulsar.git
commit 3c4948b613ca90d3819edcfca8fab43ae7eb6f05
Author: Lari Hotari <lh...@users.noreply.github.com>
AuthorDate: Wed Jul 1 06:32:42 2026 +0300
[fix][test] Run makeReadEntryProbFail's errorOrNot on a caller-provided executor (#26123)
(cherry picked from commit 12d8aa9a9773f2546f58aca4678c65f6d506dd95)
---
.../bookkeeper/mledger/impl/ManagedLedgerTest.java | 21 ++++++++++++---------
.../pulsar/broker/service/OneWayReplicatorTest.java | 4 +++-
.../PersistentReplicatorInflightTaskTest.java | 21 ++++++++++++++++++---
3 files changed, 33 insertions(+), 13 deletions(-)
diff --git a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerTest.java b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerTest.java
index dff78eab2f3..6d5503244db 100644
--- a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerTest.java
+++ b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerTest.java
@@ -77,6 +77,7 @@ import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
+import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
@@ -187,19 +188,21 @@ public class ManagedLedgerTest extends MockedBookKeeperTestCase {
ml.currentLedger = spyLedgerHandle;
}
- public static void makeReadEntryProbFail(ManagedLedgerImpl ml, Supplier<ManagedLedgerException> errorOrNot)
- throws Exception {
+ public static void makeReadEntryProbFail(ManagedLedgerImpl ml, Supplier<ManagedLedgerException> errorOrNot,
+ Executor errorSupplierExecutor) throws Exception {
ml.entryCache.clear();
LedgerHandle currentLedger = ml.currentLedger;
final LedgerHandle spyLedgerHandle = spy(currentLedger);
doAnswer(invocation -> {
- long ledgerId = (long) invocation.getArguments()[0];
- long entryId = (long) invocation.getArguments()[1];
- ManagedLedgerException mightError = errorOrNot.get();
- if (mightError != null) {
- return CompletableFuture.failedFuture(mightError);
- }
- return currentLedger.readUnconfirmedAsync(ledgerId, entryId);
+ long ledgerId = invocation.getArgument(0);
+ long entryId = invocation.getArgument(1);
+ // Evaluate errorOrNot on errorSupplierExecutor. Pass a single-threaded executor when errorOrNot may
+ // block (e.g. it waits on a CountDownLatch) so it doesn't block the calling read thread; pass
+ // MoreExecutors.directExecutor() to evaluate it inline on the calling thread.
+ return CompletableFuture.supplyAsync(errorOrNot, errorSupplierExecutor)
+ .thenCompose(mightError -> mightError != null
+ ? CompletableFuture.<LedgerEntries>failedFuture(mightError)
+ : currentLedger.readUnconfirmedAsync(ledgerId, entryId));
}).when(spyLedgerHandle).readUnconfirmedAsync(anyLong(), anyLong());
ml.currentLedger = spyLedgerHandle;
}
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/OneWayReplicatorTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/OneWayReplicatorTest.java
index 5e6a78305da..99f608a200c 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/OneWayReplicatorTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/OneWayReplicatorTest.java
@@ -35,6 +35,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.benmanes.caffeine.cache.AsyncLoadingCache;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
+import com.google.common.util.concurrent.MoreExecutors;
import io.netty.channel.Channel;
import io.netty.util.concurrent.FastThreadLocalThread;
import java.lang.reflect.Field;
@@ -723,7 +724,8 @@ public class OneWayReplicatorTest extends OneWayReplicatorTestBase {
}
return new ManagedLedgerException.TooManyRequestsException("mocked error");
};
- ManagedLedgerTest.makeReadEntryProbFail(ml1, bkErrorOrNot);
+ // bkErrorOrNot doesn't block, so evaluate it inline on the calling read thread via directExecutor().
+ ManagedLedgerTest.makeReadEntryProbFail(ml1, bkErrorOrNot, MoreExecutors.directExecutor());
// Verify: the replication will finish even though received ManagedLedgerException.TooManyRequestsException.
pulsar1.getConfig().setReplicationStartAt("earliest");
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 63f7abbd640..4bf96d37b8a 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
@@ -46,9 +46,12 @@ import java.util.List;
import java.util.Optional;
import java.util.Set;
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.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
+import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.apache.bookkeeper.mledger.Entry;
import org.apache.bookkeeper.mledger.ManagedCursor;
@@ -162,6 +165,10 @@ public class PersistentReplicatorInflightTaskTest extends OneWayReplicatorTestBa
PersistentTopic topic = (PersistentTopic) pulsar1.getBrokerService().getTopic(topicName, false)
.join().get();
ManagedLedgerImpl ml = (ManagedLedgerImpl) topic.getManagedLedger();
+ // errorOrNot blocks on failRead, so run it on a dedicated single-threaded executor instead of the
+ // calling read thread; otherwise the blocked read thread would stall replicator.terminate().
+ @Cleanup("shutdownNow")
+ ExecutorService readFailExecutor = Executors.newSingleThreadExecutor();
ManagedLedgerTest.makeReadEntryProbFail(ml, () -> {
readStarted.countDown();
try {
@@ -173,7 +180,7 @@ public class PersistentReplicatorInflightTaskTest extends OneWayReplicatorTestBa
return new ManagedLedgerException(e);
}
return new ManagedLedgerException.TooManyRequestsException("mocked read failure");
- });
+ }, readFailExecutor);
pulsar1.getConfig().setReplicationStartAt("earliest");
admin1.topics().setReplicationClusters(topicName, Arrays.asList(cluster1, cluster2));
@@ -324,6 +331,10 @@ public class PersistentReplicatorInflightTaskTest extends OneWayReplicatorTestBa
ManagedLedgerImpl ml = (ManagedLedgerImpl) topic.getManagedLedger();
// Clear the entry cache and intercept ledger reads: block the first read so it stays in flight
// (the in-flight task keeps entries == null), then let it and all later reads succeed.
+ // errorOrNot blocks the first read on releaseRead, so run it on a dedicated single-threaded executor
+ // instead of the calling read thread.
+ @Cleanup("shutdownNow")
+ ExecutorService readFailExecutor = Executors.newSingleThreadExecutor();
ManagedLedgerTest.makeReadEntryProbFail(ml, () -> {
if (blockNextRead.compareAndSet(true, false)) {
readBlocked.countDown();
@@ -335,7 +346,7 @@ public class PersistentReplicatorInflightTaskTest extends OneWayReplicatorTestBa
}
// Never fail the read; it must complete successfully to reach the skip branch.
return null;
- });
+ }, readFailExecutor);
// Start replication from earliest; the first read blocks inside the ledger read (in flight).
pulsar1.getConfig().setReplicationStartAt("earliest");
@@ -467,6 +478,10 @@ public class PersistentReplicatorInflightTaskTest extends OneWayReplicatorTestBa
ManagedLedgerImpl ml = (ManagedLedgerImpl) topic.getManagedLedger();
// Clear the entry cache and intercept ledger reads: block the first read so it stays in flight
// (the in-flight task keeps entries == null), then let it and all later reads succeed.
+ // errorOrNot blocks the first read on releaseRead, so run it on a dedicated single-threaded executor
+ // instead of the calling read thread.
+ @Cleanup("shutdownNow")
+ ExecutorService readFailExecutor = Executors.newSingleThreadExecutor();
ManagedLedgerTest.makeReadEntryProbFail(ml, () -> {
if (blockNextRead.compareAndSet(true, false)) {
readBlocked.countDown();
@@ -478,7 +493,7 @@ public class PersistentReplicatorInflightTaskTest extends OneWayReplicatorTestBa
}
// Never fail the read; it must complete successfully to reach the skip branch.
return null;
- });
+ }, readFailExecutor);
// Start replication from earliest; the first read blocks inside the ledger read (in flight).
pulsar1.getConfig().setReplicationStartAt("earliest");
(pulsar) 03/03: [fix][broker] Don't let a closing topic-policies reader abort a concurrent cache-init reload (#26132)
Posted by lh...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
lhotari pushed a commit to branch branch-4.0
in repository https://gitbox.apache.org/repos/asf/pulsar.git
commit 88405242a0168b8981ea61bdf503de00297b17f4
Author: Lari Hotari <lh...@users.noreply.github.com>
AuthorDate: Thu Jul 2 03:02:34 2026 +0300
[fix][broker] Don't let a closing topic-policies reader abort a concurrent cache-init reload (#26132)
(cherry picked from commit decc80ff0369c0387c6cd02745ebe993dbf71ff1)
---
.../SystemTopicBasedTopicPoliciesService.java | 108 ++++++++-------------
.../SystemTopicBasedTopicPoliciesServiceTest.java | 93 ++++++++++++++----
2 files changed, 116 insertions(+), 85 deletions(-)
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/SystemTopicBasedTopicPoliciesService.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/SystemTopicBasedTopicPoliciesService.java
index 623933eaafc..c1cd71f31f2 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/SystemTopicBasedTopicPoliciesService.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/SystemTopicBasedTopicPoliciesService.java
@@ -455,7 +455,7 @@ public class SystemTopicBasedTopicPoliciesService implements TopicPoliciesServic
// The cached writer will be closed when an exception happens
// This is potentially not a great idea since we should be able to rely on the Pulsar client's
// behavior for restoring a Producer after a failure.
- writerCaches.synchronous().invalidate(topicName.getNamespaceObject());
+ cleanWriterCache(topicName.getNamespaceObject());
throw FutureUtil.wrapToCompletionException(t);
});
}
@@ -646,7 +646,7 @@ public class SystemTopicBasedTopicPoliciesService implements TopicPoliciesServic
initPolicesCache(reader, stageFuture);
return stageFuture
// Read policies in background
- .thenAccept(__ -> readMorePoliciesAsync(reader));
+ .thenAccept(__ -> readMorePoliciesAsync(reader, initNamespacePolicyFuture));
}).thenApply(__ -> {
initNamespacePolicyFuture.complete(null);
return null;
@@ -682,13 +682,7 @@ public class SystemTopicBasedTopicPoliciesService implements TopicPoliciesServic
}
private CompletableFuture<SystemTopicClient.Reader<PulsarEvent>> newReader(NamespaceName ns) {
- return readerCaches.compute(ns, (__, existingFuture) -> {
- if (existingFuture == null) {
- return createSystemTopicClient(ns);
- }
-
- return existingFuture;
- });
+ return readerCaches.computeIfAbsent(ns, __ -> createSystemTopicClient(ns));
}
protected CompletableFuture<SystemTopicClient.Reader<PulsarEvent>> createSystemTopicClient(
@@ -714,7 +708,7 @@ public class SystemTopicBasedTopicPoliciesService implements TopicPoliciesServic
}
AtomicInteger bundlesCount = ownedBundlesCountPerNamespace.get(namespace);
if (bundlesCount == null || bundlesCount.decrementAndGet() <= 0) {
- cleanPoliciesCacheInitMap(namespace, true);
+ cleanPoliciesCacheInitMap(namespace);
cleanWriterCache(namespace);
cleanOwnedBundlesCount(namespace);
}
@@ -779,17 +773,20 @@ public class SystemTopicBasedTopicPoliciesService implements TopicPoliciesServic
/**
* Identity-guarded cleanup for an initialization that failed (it timed out, the {@code __change_events} reader
- * could not be created, or reading the topic threw). Unlike {@link #cleanPoliciesCacheInitMap}, which
+ * could not be created, or reading the topic threw), or whose background reader was later closed (an
+ * {@code AlreadyClosedException} surfaced in {@link #readMorePoliciesAsync} after a namespace unload closed the
+ * reader). Unlike {@link #cleanPoliciesCacheInitMap}, which
* removes/closes by namespace key unconditionally, this only tears down state that still belongs to
* {@code initFuture}. By the time the failure is observed, a concurrent retry — or a namespace-bundle unload that
* left the init future orphaned — may already own the namespace with a fresh future and reader; removing by key
* would drop that newer future and close its reader, pinning the namespace again. Guarding on identity ensures a
* late failure never clobbers a newer initialization.
*
- * @param closeReader when {@code true}, also clears the cached policies and closes the reader that belongs to this
- * initialization; when {@code false}, only the init future is dropped, leaving the reader cached
- * for the retry to reuse (mirrors the transient read-error path of
- * {@link #cleanPoliciesCacheInitMap}).
+ * @param closeReader when {@code true}, also closes the reader and message-handler tracker that belong to this
+ * initialization; when {@code false}, only the init future is dropped, leaving the reader
+ * cached for the retry to reuse. The cached policies are intentionally left in place; they
+ * are cleared only when the whole namespace is unloaded, so this cleanup cannot race a
+ * concurrent re-initialization.
*/
@VisibleForTesting
void cleanupFailedPolicyCacheInit(@NonNull NamespaceName namespace,
@@ -798,23 +795,29 @@ public class SystemTopicBasedTopicPoliciesService implements TopicPoliciesServic
// initialization, never one a concurrent retry creates immediately afterwards.
CompletableFuture<SystemTopicClient.Reader<PulsarEvent>> readerFuture =
closeReader ? readerCaches.get(namespace) : null;
+ TopicPolicyMessageHandlerTracker tracker = topicPolicyMessageHandlerTrackers.get(namespace);
+
+ // Identity guard: only proceed while this initialization still owns the namespace's init future.
if (!policyCacheInitMap.remove(namespace, initFuture)) {
// Superseded by a retry or an unload; that owner is responsible for its own reader/state.
return;
}
+
// Complete the dropped future (a no-op if the caller already completed it) outside any map remapping function,
// so awaiting topic loads fail fast and retry instead of hanging until the broker restarts (issue #25294).
failPendingPolicyCacheInit(namespace, initFuture);
if (!closeReader) {
return;
}
- policiesCache.entrySet().removeIf(entry -> Objects.equals(entry.getKey().getNamespaceObject(), namespace));
- globalPoliciesCache.entrySet()
- .removeIf(entry -> Objects.equals(entry.getKey().getNamespaceObject(), namespace));
- TopicPolicyMessageHandlerTracker tracker = topicPolicyMessageHandlerTrackers.remove(namespace);
- if (tracker != null) {
+
+ // Close the tracker captured above only if it is still the one installed for this namespace, so a
+ // concurrent re-initialization that installed a newer tracker is left untouched.
+ if (tracker != null && topicPolicyMessageHandlerTrackers.remove(namespace, tracker)) {
tracker.close();
}
+
+ // Remove and close the reader captured above only if it is still the current one, so a reader
+ // created by a later initialization is never closed by this stale cleanup.
if (readerFuture != null && readerCaches.remove(namespace, readerFuture)
&& !readerFuture.isCompletedExceptionally()) {
readerFuture.thenCompose(SystemTopicClient.Reader::closeAsync)
@@ -828,7 +831,7 @@ public class SystemTopicBasedTopicPoliciesService implements TopicPoliciesServic
private void initPolicesCache(SystemTopicClient.Reader<PulsarEvent> reader, CompletableFuture<Void> future) {
if (closed.get()) {
future.completeExceptionally(new BrokerServiceException(getClass().getName() + " is closed."));
- cleanPoliciesCacheInitMap(reader.getSystemTopic().getTopicName().getNamespaceObject(), true);
+ cleanPoliciesCacheInitMap(reader.getSystemTopic().getTopicName().getNamespaceObject());
return;
}
reader.hasMoreEventsAsync().whenComplete((hasMore, ex) -> {
@@ -873,13 +876,10 @@ public class SystemTopicBasedTopicPoliciesService implements TopicPoliciesServic
});
}
+ // Full teardown of a namespace's topic-policies state: removes and closes the reader, the message-handler
+ // tracker, the cached policies and the init future. Used when the whole namespace is unloaded.
@VisibleForTesting
- void cleanPoliciesCacheInitMap(@NonNull NamespaceName namespace, boolean closeReader) {
- if (!closeReader) {
- failPendingPolicyCacheInit(namespace, policyCacheInitMap.remove(namespace));
- return;
- }
-
+ void cleanPoliciesCacheInitMap(@NonNull NamespaceName namespace) {
TopicPolicyMessageHandlerTracker topicPolicyMessageHandlerTracker =
topicPolicyMessageHandlerTrackers.remove(namespace);
if (topicPolicyMessageHandlerTracker != null) {
@@ -931,52 +931,17 @@ public class SystemTopicBasedTopicPoliciesService implements TopicPoliciesServic
ownedBundlesCountPerNamespace.remove(namespace);
}
-
- private void cleanCacheAndCloseReader(@NonNull NamespaceName namespace, boolean cleanOwnedBundlesCount,
- boolean cleanWriterCache) {
- if (cleanWriterCache) {
- writerCaches.synchronous().invalidate(namespace);
- }
- CompletableFuture<SystemTopicClient.Reader<PulsarEvent>> readerFuture = readerCaches.remove(namespace);
-
- TopicPolicyMessageHandlerTracker topicPolicyMessageHandlerTracker =
- topicPolicyMessageHandlerTrackers.remove(namespace);
- if (topicPolicyMessageHandlerTracker != null) {
- topicPolicyMessageHandlerTracker.close();
- }
-
- if (cleanOwnedBundlesCount) {
- ownedBundlesCountPerNamespace.remove(namespace);
- }
- if (readerFuture != null && !readerFuture.isCompletedExceptionally()) {
- readerFuture.thenCompose(SystemTopicClient.Reader::closeAsync)
- .exceptionally(ex -> {
- log.warn("[{}] Close change_event reader fail.", namespace, ex);
- return null;
- });
- }
-
- policyCacheInitMap.compute(namespace, (k, v) -> {
- policiesCache.entrySet().removeIf(entry -> Objects.equals(entry.getKey().getNamespaceObject(), namespace));
- globalPoliciesCache.entrySet()
- .removeIf(entry -> Objects.equals(entry.getKey().getNamespaceObject(), namespace));
- return null;
- });
- }
-
-
-
-
/**
* This is an async method for the background reader to continue syncing new messages.
*
* Note: You should not do any blocking call here. because it will affect
* #{@link SystemTopicBasedTopicPoliciesService#getTopicPoliciesAsync} method to block loading topic.
*/
- private void readMorePoliciesAsync(SystemTopicClient.Reader<PulsarEvent> reader) {
+ private void readMorePoliciesAsync(SystemTopicClient.Reader<PulsarEvent> reader,
+ CompletableFuture<Void> initFuture) {
NamespaceName namespaceObject = reader.getSystemTopic().getTopicName().getNamespaceObject();
if (closed.get()) {
- cleanPoliciesCacheInitMap(namespaceObject, true);
+ cleanupFailedPolicyCacheInit(namespaceObject, initFuture, true);
return;
}
reader.readNextAsync()
@@ -995,15 +960,22 @@ public class SystemTopicBasedTopicPoliciesService implements TopicPoliciesServic
})
.whenComplete((__, ex) -> {
if (ex == null) {
- readMorePoliciesAsync(reader);
+ readMorePoliciesAsync(reader, initFuture);
} else {
if (isAlreadyClosedException(ex)) {
log.info("Closing the topic policies reader for {}",
reader.getSystemTopic().getTopicName());
- cleanPoliciesCacheInitMap(namespaceObject, true);
+ // Tear down by init-future identity, not by namespace key: this reader may have been
+ // closed by a namespace unload while a concurrent reload already installed a fresh
+ // reader and init future for the same namespace (the close only surfaces here, on the
+ // client executor, afterwards). A namespace-keyed cleanup would clobber that newer
+ // generation and abort its init with "...aborted because the cached state was cleared",
+ // failing the reloading topic. cleanupFailedPolicyCacheInit only tears down state that
+ // still belongs to this initialization, so a superseded reader's late close is a no-op.
+ cleanupFailedPolicyCacheInit(namespaceObject, initFuture, true);
} else {
log.warn("Read more topic polices exception, read again.", ex);
- readMorePoliciesAsync(reader);
+ readMorePoliciesAsync(reader, initFuture);
}
}
});
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/SystemTopicBasedTopicPoliciesServiceTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/SystemTopicBasedTopicPoliciesServiceTest.java
index 04b9bc67e7e..8ea225ebf62 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/SystemTopicBasedTopicPoliciesServiceTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/SystemTopicBasedTopicPoliciesServiceTest.java
@@ -604,17 +604,19 @@ public class SystemTopicBasedTopicPoliciesServiceTest extends MockedPulsarServic
});
// Cleanup must run exactly once per trigger and not repeat recursively (in older code it ran 3 times).
- // Two failures are triggered here: the reader.close() above drives readMorePoliciesAsync into
- // cleanPoliciesCacheInitMap (1x), and the second prepareInitPoliciesCacheAsync fails in initPolicesCache and
- // is torn down by the identity-guarded cleanupFailedPolicyCacheInit (1x).
+ // Two failures are triggered here, and both tear down through the identity-guarded cleanupFailedPolicyCacheInit
+ // (2x): the reader.close() above drives readMorePoliciesAsync's AlreadyClosed branch into it, and the second
+ // prepareInitPoliciesCacheAsync fails in initPolicesCache and is torn down by it as well. The namespace-keyed
+ // cleanPoliciesCacheInitMap must not be reached from the reader-close path, otherwise a superseded reader could
+ // clobber a newer generation's init future.
boolean logFound = testLogAppender.getEvents().stream().anyMatch(logEvent ->
logEvent.getMessage().toString().contains("Failed to create reader on __change_events topic"));
assertFalse(logFound);
boolean logFound2 = testLogAppender.getEvents().stream().anyMatch(logEvent ->
logEvent.getMessage().toString().contains("Failed to check the move events for the system topic"));
assertTrue(logFound2);
- verify(spyService, times(1)).cleanPoliciesCacheInitMap(any(), anyBoolean());
- verify(spyService, times(1)).cleanupFailedPolicyCacheInit(any(), any(), anyBoolean());
+ verify(spyService, times(0)).cleanPoliciesCacheInitMap(any());
+ verify(spyService, times(2)).cleanupFailedPolicyCacheInit(any(), any(), anyBoolean());
// make sure not occur Recursive update
boolean logFound3 = testLogAppender.getEvents().stream().anyMatch(logEvent ->
@@ -684,7 +686,7 @@ public class SystemTopicBasedTopicPoliciesServiceTest extends MockedPulsarServic
|| logEvent.getMessage().toString().contains("Failed to read event from the system topic"));
assertFalse(logFound2);
verify(spyService, times(1)).cleanupFailedPolicyCacheInit(any(), any(), anyBoolean());
- verify(spyService, times(0)).cleanPoliciesCacheInitMap(any(), anyBoolean());
+ verify(spyService, times(0)).cleanPoliciesCacheInitMap(any());
}
@Test(timeOut = 60_000)
@@ -733,22 +735,16 @@ public class SystemTopicBasedTopicPoliciesServiceTest extends MockedPulsarServic
// Dropping the cached init future (e.g. on a namespace-bundle unload) must complete it so the topic loads
// awaiting it fail fast and retry, instead of hanging until the broker restarts (issue #25294).
- CompletableFuture<Void> pendingWithReaderClose = new CompletableFuture<>();
- service.policyCacheInitMap.put(namespace, pendingWithReaderClose);
- service.cleanPoliciesCacheInitMap(namespace, true);
- assertTrue(pendingWithReaderClose.isCompletedExceptionally());
- assertNull(service.getPoliciesCacheInit(namespace));
-
- CompletableFuture<Void> pendingWithoutReaderClose = new CompletableFuture<>();
- service.policyCacheInitMap.put(namespace, pendingWithoutReaderClose);
- service.cleanPoliciesCacheInitMap(namespace, false);
- assertTrue(pendingWithoutReaderClose.isCompletedExceptionally());
+ CompletableFuture<Void> pendingInitFuture = new CompletableFuture<>();
+ service.policyCacheInitMap.put(namespace, pendingInitFuture);
+ service.cleanPoliciesCacheInitMap(namespace);
+ assertTrue(pendingInitFuture.isCompletedExceptionally());
assertNull(service.getPoliciesCacheInit(namespace));
// An already-completed init future must not be overwritten/disturbed.
CompletableFuture<Void> alreadyDone = CompletableFuture.completedFuture(null);
service.policyCacheInitMap.put(namespace, alreadyDone);
- service.cleanPoliciesCacheInitMap(namespace, true);
+ service.cleanPoliciesCacheInitMap(namespace);
assertFalse(alreadyDone.isCompletedExceptionally());
}
@@ -783,4 +779,67 @@ public class SystemTopicBasedTopicPoliciesServiceTest extends MockedPulsarServic
assertNull(service.getReaderCaches().get(namespace));
Mockito.verify(newerReader, Mockito.times(1)).closeAsync();
}
+
+ @Test
+ @SuppressWarnings("unchecked")
+ public void testClosedSupersededReaderDoesNotAbortReloadedInit() throws Exception {
+ // Reproduces the race behind the flaky AdminApi2Test.testGetInternalStatsWithProperties: a namespace unload
+ // closes the __change_events reader while a reload (e.g. getTopic right after unload) installs a fresh reader
+ // and init future for the same namespace. The old reader's close only surfaces later, on the pulsar-client
+ // executor, as an AlreadyClosedException in readMorePoliciesAsync. That late cleanup must NOT clobber the newer
+ // generation and abort its init future ("...aborted because the cached state was cleared"), which would fail
+ // the reloading topic load.
+ @Cleanup
+ TestLogAppender testLogAppender = TestLogAppender.create(log);
+
+ pulsar.getTopicPoliciesService().close();
+ SystemTopicBasedTopicPoliciesService spyService =
+ Mockito.spy(new SystemTopicBasedTopicPoliciesService(pulsar));
+ FieldUtils.writeField(pulsar, "topicPoliciesService", spyService, true);
+
+ final NamespaceName namespace = NamespaceName.get(NAMESPACE5);
+ admin.namespaces().createNamespace(NAMESPACE5);
+
+ // A real reader, spied so its background read loop is fully controllable: it reports "no more events" so the
+ // initialization completes and readMorePoliciesAsync starts, then parks on a read future we complete by hand.
+ SystemTopicClient.Reader<PulsarEvent> oldReader =
+ Mockito.spy(spyService.createSystemTopicClient(namespace).get(30, TimeUnit.SECONDS));
+ CompletableFuture<Message<PulsarEvent>> parkedRead = new CompletableFuture<>();
+ Mockito.doReturn(CompletableFuture.completedFuture(false)).when(oldReader).hasMoreEventsAsync();
+ Mockito.doReturn(parkedRead).when(oldReader).readNextAsync();
+ Mockito.doReturn(CompletableFuture.completedFuture(oldReader))
+ .when(spyService).createSystemTopicClient(namespace);
+ spyService.getReaderCaches().put(namespace, CompletableFuture.completedFuture(oldReader));
+
+ // Drive initialization: readMorePoliciesAsync(oldReader, <old init future>) is now looping, parked on
+ // parkedRead, having registered its whenComplete callback.
+ assertTrue(spyService.prepareInitPoliciesCacheAsync(namespace).get(30, TimeUnit.SECONDS));
+ Mockito.verify(oldReader, Mockito.atLeastOnce()).readNextAsync();
+
+ // Simulate the concurrent unload+reload having already replaced the generation: a fresh reader and a fresh,
+ // still-pending init future that a reloading topic is awaiting.
+ SystemTopicClient.Reader<PulsarEvent> reloadReader = Mockito.mock(SystemTopicClient.Reader.class);
+ Mockito.doReturn(CompletableFuture.completedFuture(null)).when(reloadReader).closeAsync();
+ CompletableFuture<SystemTopicClient.Reader<PulsarEvent>> reloadReaderFuture =
+ CompletableFuture.completedFuture(reloadReader);
+ CompletableFuture<Void> reloadInitFuture = new CompletableFuture<>();
+ spyService.getReaderCaches().put(namespace, reloadReaderFuture);
+ spyService.policyCacheInitMap.put(namespace, reloadInitFuture);
+
+ // The old reader finally observes it was closed; this runs readMorePoliciesAsync's AlreadyClosed cleanup
+ // synchronously on this thread.
+ parkedRead.completeExceptionally(new PulsarClientException.AlreadyClosedException("reader is already closed"));
+
+ // The cleanup ran (it logged), but being identity-guarded on the init future it left the newer generation
+ // untouched. Before the fix it cleared readerCaches/policyCacheInitMap by namespace key and aborted the reload.
+ assertTrue(testLogAppender.getEvents().stream().anyMatch(e ->
+ e.getMessage().toString().contains("Closing the topic policies reader for")));
+ assertFalse("the reload's init future must not be aborted by the superseded reader's late close",
+ reloadInitFuture.isCompletedExceptionally());
+ assertFalse(reloadInitFuture.isDone());
+ assertSame("the reload's reader must remain cached", reloadReaderFuture,
+ spyService.getReaderCaches().get(namespace));
+ assertSame(reloadInitFuture, spyService.getPoliciesCacheInit(namespace));
+ Mockito.verify(reloadReader, Mockito.never()).closeAsync();
+ }
}