You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pulsar.apache.org by mm...@apache.org on 2026/10/12 19:13:36 UTC
(pulsar) branch master updated: [fix][broker] Delete scalable topics when deleting a namespace or a tenant (#26869)
This is an automated email from the ASF dual-hosted git repository.
merlimat 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 35cabeb5fd8c [fix][broker] Delete scalable topics when deleting a namespace or a tenant (#26869)
35cabeb5fd8c is described below
commit 35cabeb5fd8c4cda097511d9f437f1a91572ac61
Author: Matteo Merli <mm...@apache.org>
AuthorDate: Mon Oct 12 12:13:29 2026 -0700
[fix][broker] Delete scalable topics when deleting a namespace or a tenant (#26869)
---
.../broker/resources/ScalableTopicResources.java | 13 ++
.../pulsar/broker/resources/TopicResources.java | 36 ++++
.../broker/resources/TopicResourcesTest.java | 20 ++
.../pulsar/broker/admin/impl/NamespacesBase.java | 116 +++++++++---
.../pulsar/broker/admin/impl/TenantsBase.java | 8 +
.../scalable/ScalableTopicNamespaceDeleteTest.java | 203 +++++++++++++++++++++
.../ScalableTopicNamespaceDeleteZooKeeperTest.java | 116 ++++++++++++
.../api/v5/V5MultiBrokerNamespaceDeleteTest.java | 176 ++++++++++++++++++
.../metadata/api/MetadataStoreException.java | 8 +
9 files changed, 672 insertions(+), 24 deletions(-)
diff --git a/pulsar-broker-common/src/main/java/org/apache/pulsar/broker/resources/ScalableTopicResources.java b/pulsar-broker-common/src/main/java/org/apache/pulsar/broker/resources/ScalableTopicResources.java
index 8d5999c061b7..bec03c6029df 100644
--- a/pulsar-broker-common/src/main/java/org/apache/pulsar/broker/resources/ScalableTopicResources.java
+++ b/pulsar-broker-common/src/main/java/org/apache/pulsar/broker/resources/ScalableTopicResources.java
@@ -283,6 +283,19 @@ public class ScalableTopicResources extends BaseResources<ScalableTopicMetadata>
.collect(Collectors.toList()));
}
+ /**
+ * Delete the node of a namespace whose scalable topics are deleted. Not recursive, so a scalable topic still
+ * in the namespace fails it.
+ */
+ public CompletableFuture<Void> clearNamespaceAsync(NamespaceName ns) {
+ return getStore().deleteIfExists(namespacePath(ns), Optional.empty());
+ }
+
+ /** Delete the scalable topic records of a tenant whose namespaces are deleted. */
+ public CompletableFuture<Void> clearTenantAsync(String tenant) {
+ return getStore().deleteRecursive(joinPath(SCALABLE_TOPIC_PATH, tenant));
+ }
+
/**
* List scalable topics in a namespace whose {@code properties} map contains every
* key/value pair in {@code propertyFilters} (AND semantics).
diff --git a/pulsar-broker-common/src/main/java/org/apache/pulsar/broker/resources/TopicResources.java b/pulsar-broker-common/src/main/java/org/apache/pulsar/broker/resources/TopicResources.java
index 66d2e81fb0eb..efa0b573c573 100644
--- a/pulsar-broker-common/src/main/java/org/apache/pulsar/broker/resources/TopicResources.java
+++ b/pulsar-broker-common/src/main/java/org/apache/pulsar/broker/resources/TopicResources.java
@@ -33,6 +33,7 @@ import org.apache.pulsar.common.naming.NamespaceName;
import org.apache.pulsar.common.naming.SystemTopicNames;
import org.apache.pulsar.common.naming.TopicDomain;
import org.apache.pulsar.common.naming.TopicName;
+import org.apache.pulsar.common.util.FutureUtil;
import org.apache.pulsar.metadata.api.Notification;
import org.apache.pulsar.metadata.api.NotificationType;
import org.apache.pulsar.metadata.api.extended.MetadataStoreExtended;
@@ -101,6 +102,41 @@ public class TopicResources {
return store.deleteIfExists(path, Optional.empty());
}
+ /**
+ * List the segment topics of the scalable topics in a namespace that have a managed ledger, stored at
+ * {@code /managed-ledgers/<namespace>/segment/<topic>/<descriptor>}.
+ */
+ public CompletableFuture<List<String>> listSegmentTopicsAsync(NamespaceName ns) {
+ String path = MANAGED_LEDGER_PATH + "/" + ns + "/" + TopicDomain.segment;
+ return store.getChildren(path).thenCompose(encodedTopics -> {
+ List<CompletableFuture<List<String>>> futures = encodedTopics.stream()
+ .map(encodedTopic -> store.getChildren(path + "/" + encodedTopic)
+ .thenApply(descriptors -> descriptors.stream()
+ .map(descriptor -> TopicDomain.segment + "://" + ns + "/"
+ + decode(encodedTopic) + "/" + descriptor)
+ .toList()))
+ .toList();
+ return FutureUtil.waitForAll(futures).thenApply(__ -> futures.stream()
+ .flatMap(future -> future.join().stream())
+ .toList());
+ });
+ }
+
+ /**
+ * Delete the segment domain of a namespace: the node of each scalable topic whose segment topics had a
+ * managed ledger, then the domain node. Not recursive, so a segment topic that still has a managed ledger
+ * fails it.
+ */
+ public CompletableFuture<Void> clearSegmentDomainPersistence(NamespaceName ns) {
+ String path = MANAGED_LEDGER_PATH + "/" + ns + "/" + TopicDomain.segment;
+ log.debug().attr("namespace", ns).attr("path", path).log("Clearing segment domain persistence");
+ return store.getChildren(path)
+ .thenCompose(encodedTopics -> FutureUtil.waitForAll(encodedTopics.stream()
+ .map(encodedTopic -> store.deleteIfExists(path + "/" + encodedTopic, Optional.empty()))
+ .toList()))
+ .thenCompose(__ -> store.deleteIfExists(path, Optional.empty()));
+ }
+
public CompletableFuture<Void> clearTenantPersistence(String tenant) {
String path = MANAGED_LEDGER_PATH + "/" + tenant;
log.info().attr("tenant", tenant).attr("path", path).log("Clearing tenant persistence for tenant: , path");
diff --git a/pulsar-broker-common/src/test/java/org/apache/pulsar/broker/resources/TopicResourcesTest.java b/pulsar-broker-common/src/test/java/org/apache/pulsar/broker/resources/TopicResourcesTest.java
index 76f4b3481a4c..40fb2cb7a2cc 100644
--- a/pulsar-broker-common/src/test/java/org/apache/pulsar/broker/resources/TopicResourcesTest.java
+++ b/pulsar-broker-common/src/test/java/org/apache/pulsar/broker/resources/TopicResourcesTest.java
@@ -18,11 +18,14 @@
*/
package org.apache.pulsar.broker.resources;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
import java.util.function.BiConsumer;
import org.apache.pulsar.common.naming.NamespaceName;
import org.apache.pulsar.metadata.api.Notification;
@@ -164,4 +167,21 @@ public class TopicResourcesTest {
"/managed-ledgers/tenant/namespace/persistent/topic2"));
verifyNoMoreInteractions(listener);
}
+
+ @Test
+ public void testListSegmentTopics() throws Exception {
+ String segmentDomain = "/managed-ledgers/tenant/namespace/segment";
+ when(metadataStore.getChildren(segmentDomain))
+ .thenReturn(CompletableFuture.completedFuture(List.of("topic", "my%20topic")));
+ when(metadataStore.getChildren(segmentDomain + "/topic"))
+ .thenReturn(CompletableFuture.completedFuture(List.of("0000-7fff-1", "8000-ffff-2")));
+ when(metadataStore.getChildren(segmentDomain + "/my%20topic"))
+ .thenReturn(CompletableFuture.completedFuture(List.of("0000-ffff-0")));
+
+ assertThat(topicResources.listSegmentTopicsAsync(NamespaceName.get("tenant/namespace")).get())
+ .containsExactlyInAnyOrder(
+ "segment://tenant/namespace/topic/0000-7fff-1",
+ "segment://tenant/namespace/topic/8000-ffff-2",
+ "segment://tenant/namespace/my topic/0000-ffff-0");
+ }
}
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/impl/NamespacesBase.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/impl/NamespacesBase.java
index d9e52fec575b..9cc0473dd5fc 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/impl/NamespacesBase.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/impl/NamespacesBase.java
@@ -46,6 +46,7 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.BiFunction;
import java.util.function.BooleanSupplier;
import java.util.function.Function;
import java.util.stream.Collectors;
@@ -60,6 +61,7 @@ import org.apache.pulsar.broker.ServiceConfiguration;
import org.apache.pulsar.broker.admin.AdminResource;
import org.apache.pulsar.broker.loadbalance.extensions.ExtensibleLoadManagerImpl;
import org.apache.pulsar.broker.namespace.LookupOptions;
+import org.apache.pulsar.broker.resources.ScalableTopicResources;
import org.apache.pulsar.broker.service.BrokerServiceException;
import org.apache.pulsar.broker.service.BrokerServiceException.SubscriptionBusyException;
import org.apache.pulsar.broker.service.Subscription;
@@ -302,17 +304,19 @@ public abstract class NamespacesBase extends AdminResource {
}
return topicsFuture.thenCompose(allTopics ->
pulsar().getNamespaceService().getFullListOfPartitionedTopic(namespaceName)
- .thenCompose(allPartitionedTopics -> {
- List<List<String>> topicsSum = new ArrayList<>(2);
+ .thenCombine(listScalableTopicsAsync(), (allPartitionedTopics, allScalable) -> {
+ List<List<String>> topicsSum = new ArrayList<>(3);
topicsSum.add(allTopics);
topicsSum.add(allPartitionedTopics);
- return CompletableFuture.completedFuture(topicsSum);
+ topicsSum.add(allScalable);
+ return topicsSum;
}))
.thenCompose(topics -> {
List<String> allTopics = topics.get(0);
Set<String> allUserCreatedTopics = new HashSet<>();
List<String> allPartitionedTopics = topics.get(1);
Set<String> allUserCreatedPartitionTopics = new HashSet<>();
+ List<String> allScalableTopics = topics.get(2);
boolean hasNonSystemTopic = false;
Set<String> allSystemTopics = new HashSet<>();
Set<String> allPartitionedSystemTopics = new HashSet<>();
@@ -343,7 +347,7 @@ public abstract class NamespacesBase extends AdminResource {
}
}
if (!force) {
- if (hasNonSystemTopic) {
+ if (hasNonSystemTopic || !allScalableTopics.isEmpty()) {
throw new RestException(Status.CONFLICT, "Cannot delete non empty namespace");
}
}
@@ -360,6 +364,10 @@ public abstract class NamespacesBase extends AdminResource {
internalDeleteTopicsAsync(allUserCreatedTopics))
.thenCompose(ignore ->
internalDeletePartitionedTopicsAsync(allUserCreatedPartitionTopics))
+ // Like the regular topics, before the system topics: deleting a segment
+ // topic deletes its topic policies
+ .thenCompose(ignore ->
+ internalDeleteScalableTopicsAsync(allScalableTopics))
.thenCompose(ignore ->
internalDeleteTopicsAsync(allSystemTopics))
.thenCompose(ignore ->
@@ -407,27 +415,24 @@ public abstract class NamespacesBase extends AdminResource {
.whenComplete((result, error) -> {
if (error != null) {
final Throwable rc = FutureUtil.unwrapCompletionException(error);
- if (rc instanceof MetadataStoreException) {
- if (rc.getCause() != null && rc.getCause() instanceof KeeperException.NotEmptyException) {
- KeeperException.NotEmptyException ne =
- (KeeperException.NotEmptyException) rc.getCause();
- log.info()
- .attr("namespace", namespaceName)
- .attr("path", ne.getPath())
- .log("In-flight topics during namespace deletion, retrying");
- final int next = retryTimes - 1;
- if (next > 0) {
- // async recursive
- internalRetryableDeleteNamespaceAsync0(force, next, callback);
- } else {
- callback.completeExceptionally(
- new RestException(Status.CONFLICT, "The broker still have in-flight topics"
- + " created during namespace deletion (path " + ne.getPath() + ") "
- + "is not empty on metadata store, please try again."));
- // drop out recursive
- }
- return;
+ final String notEmptyPath = getNotEmptyPath(rc);
+ if (notEmptyPath != null) {
+ log.info()
+ .attr("namespace", namespaceName)
+ .attr("path", notEmptyPath)
+ .log("In-flight topics during namespace deletion, retrying");
+ final int next = retryTimes - 1;
+ if (next > 0) {
+ // async recursive
+ internalRetryableDeleteNamespaceAsync0(force, next, callback);
+ } else {
+ callback.completeExceptionally(
+ new RestException(Status.CONFLICT, "The broker still have in-flight topics"
+ + " created during namespace deletion (path " + notEmptyPath + ") "
+ + "is not empty on metadata store, please try again."));
+ // drop out recursive
}
+ return;
}
callback.completeExceptionally(error);
return;
@@ -436,6 +441,21 @@ public abstract class NamespacesBase extends AdminResource {
});
}
+ /**
+ * The path of the node that a metadata store refused to delete because it has children, or null for any other
+ * error. ZooKeeper reports it as the cause of a {@link MetadataStoreException}, Oxia as a
+ * {@link MetadataStoreException.NotEmptyException}.
+ */
+ private static String getNotEmptyPath(Throwable ex) {
+ if (ex instanceof MetadataStoreException.NotEmptyException notEmpty) {
+ return notEmpty.getPath();
+ }
+ if (ex instanceof MetadataStoreException && ex.getCause() instanceof KeeperException.NotEmptyException ne) {
+ return ne.getPath();
+ }
+ return null;
+ }
+
private boolean isDeletedAlongWithUserCreatedTopic(String topic) {
// The transaction pending ack topic will be deleted while topic unsubscribe corresponding subscription.
return topic.endsWith(SystemTopicNames.PENDING_ACK_STORE_SUFFIX);
@@ -475,6 +495,44 @@ public abstract class NamespacesBase extends AdminResource {
return FutureUtil.waitForAll(futures);
}
+ private CompletableFuture<List<String>> listScalableTopicsAsync() {
+ ScalableTopicResources resources = pulsar().getPulsarResources().getScalableTopicResources();
+ return resources != null
+ ? resources.listScalableTopicsAsync(namespaceName)
+ : CompletableFuture.completedFuture(List.of());
+ }
+
+ /**
+ * Delete the scalable topics through the scalable-topic delete, which also deletes their segment topics and
+ * their schema. Then delete the segment topics still in the namespace: the scalable-topic delete makes a single
+ * attempt at each of its segment topics, and one left behind keeps the namespace from being deleted.
+ */
+ private CompletableFuture<Void> internalDeleteScalableTopicsAsync(List<String> scalableTopics) {
+ return deleteWithAdminAsync(scalableTopics,
+ (admin, topic) -> admin.scalableTopics().deleteScalableTopicAsync(topic, true))
+ .thenCompose(__ -> pulsar().getPulsarResources().getTopicResources()
+ .listSegmentTopicsAsync(namespaceName))
+ .thenCompose(segmentTopics -> deleteWithAdminAsync(segmentTopics,
+ (admin, segmentTopic) -> admin.scalableTopics().deleteSegmentAsync(segmentTopic, true)));
+ }
+
+ private CompletableFuture<Void> deleteWithAdminAsync(
+ List<String> names, BiFunction<PulsarAdmin, String, CompletableFuture<Void>> delete) {
+ if (names.isEmpty()) {
+ return CompletableFuture.completedFuture(null);
+ }
+ PulsarAdmin admin;
+ try {
+ admin = pulsar().getAdminClient();
+ } catch (Exception ex) {
+ log.error()
+ .exception(ex)
+ .log("Get admin client error when preparing to delete topics.");
+ return FutureUtil.failedFuture(ex);
+ }
+ return FutureUtil.waitForAll(names.stream().map(name -> delete.apply(admin, name)).toList());
+ }
+
private CompletableFuture<Policies> precheckWhenDeleteNamespace(NamespaceName nsName, boolean force) {
CompletableFuture<Policies> preconditionCheck =
validateTenantOperationAsync(nsName.getTenant(), TenantOperation.DELETE_NAMESPACE)
@@ -543,9 +601,19 @@ public abstract class NamespacesBase extends AdminResource {
return namespaceResources().deleteNamespaceAsync(namespaceName)
.thenCompose(ignore -> namespaceResources().getPartitionedTopicResources()
.clearPartitionedTopicMetadataAsync(namespaceName))
+ // clear the node of the scalable topic records
+ .thenCompose(ignore -> {
+ ScalableTopicResources scalableTopicResources =
+ pulsar().getPulsarResources().getScalableTopicResources();
+ return scalableTopicResources != null
+ ? scalableTopicResources.clearNamespaceAsync(namespaceName)
+ : CompletableFuture.completedFuture(null);
+ })
// clear resource for manager-ledger z-node
.thenCompose(ignore -> pulsar().getPulsarResources().getTopicResources()
.clearDomainPersistence(namespaceName))
+ .thenCompose(ignore -> pulsar().getPulsarResources().getTopicResources()
+ .clearSegmentDomainPersistence(namespaceName))
.thenCompose(ignore -> pulsar().getPulsarResources().getTopicResources()
.clearNamespacePersistence(namespaceName))
// we have successfully removed all the ownership for the namespace, the policies
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/impl/TenantsBase.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/impl/TenantsBase.java
index 3121675c435b..1d76d6b11e73 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/impl/TenantsBase.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/impl/TenantsBase.java
@@ -45,6 +45,7 @@ import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
+import org.apache.pulsar.broker.resources.ScalableTopicResources;
import org.apache.pulsar.broker.web.PulsarWebResource;
import org.apache.pulsar.broker.web.RestException;
import org.apache.pulsar.client.admin.PulsarAdmin;
@@ -258,6 +259,13 @@ public class TenantsBase extends PulsarWebResource {
.thenCompose(__ -> hasActiveNamespace(tenant))
.thenCompose(__ -> tenantResources().deleteTenantAsync(tenant))
.thenCompose(__ -> pulsar().getPulsarResources().getTopicResources().clearTenantPersistence(tenant))
+ .thenCompose(__ -> {
+ ScalableTopicResources scalableTopicResources =
+ pulsar().getPulsarResources().getScalableTopicResources();
+ return scalableTopicResources != null
+ ? scalableTopicResources.clearTenantAsync(tenant)
+ : CompletableFuture.completedFuture(null);
+ })
.thenCompose(__ -> pulsar().getPulsarResources().getNamespaceResources().deleteTenantAsync(tenant))
.thenCompose(__ -> pulsar().getPulsarResources().getNamespaceResources()
.getPartitionedTopicResources().clearPartitionedTopicTenantAsync(tenant))
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/ScalableTopicNamespaceDeleteTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/ScalableTopicNamespaceDeleteTest.java
new file mode 100644
index 000000000000..543ad1033d75
--- /dev/null
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/ScalableTopicNamespaceDeleteTest.java
@@ -0,0 +1,203 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pulsar.broker.service.scalable;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import java.time.Duration;
+import java.util.Set;
+import java.util.UUID;
+import lombok.Cleanup;
+import org.apache.pulsar.broker.resources.ScalableTopicResources;
+import org.apache.pulsar.broker.service.SharedPulsarCluster;
+import org.apache.pulsar.client.admin.PulsarAdminException;
+import org.apache.pulsar.client.api.v5.Checkpoint;
+import org.apache.pulsar.client.api.v5.CheckpointConsumer;
+import org.apache.pulsar.client.api.v5.Message;
+import org.apache.pulsar.client.api.v5.Producer;
+import org.apache.pulsar.client.api.v5.V5ClientBaseTest;
+import org.apache.pulsar.client.api.v5.schema.Schema;
+import org.apache.pulsar.common.naming.NamespaceName;
+import org.apache.pulsar.common.naming.TopicName;
+import org.apache.pulsar.common.policies.data.TenantInfo;
+import org.apache.pulsar.metadata.api.MetadataStore;
+import org.assertj.core.api.SoftAssertions;
+import org.testng.annotations.Test;
+
+/**
+ * Deleting a namespace, or a tenant, must handle the scalable topics in it like its regular topics: a delete
+ * without force is refused while one exists, and a forced delete deletes them, with their metadata, the managed
+ * ledgers of their segments and their schema, so a namespace re-created with the same name starts empty.
+ */
+public class ScalableTopicNamespaceDeleteTest extends V5ClientBaseTest {
+
+ @Test
+ public void testDeleteNamespaceWithScalableTopicIsRejected() throws Exception {
+ String topic = newScalableTopic(1);
+
+ assertThatThrownBy(() -> admin.namespaces().deleteNamespace(getNamespace()))
+ .as("deleting, without force, a namespace that has a scalable topic")
+ .isInstanceOf(PulsarAdminException.ConflictException.class);
+
+ assertThat(admin.namespaces().getPolicies(getNamespace()).deleted)
+ .as("the namespace is not marked deleted")
+ .isFalse();
+ assertThat(admin.scalableTopics().listScalableTopics(getNamespace()))
+ .containsExactly(topic);
+ }
+
+ @Test
+ public void testForceDeleteNamespaceDeletesScalableTopic() throws Exception {
+ String namespace = getNamespace();
+ String topic = newScalableTopic(2);
+ publishString(topic, "v");
+
+ admin.namespaces().deleteNamespace(namespace, true);
+
+ assertScalableTopicDeleted(namespace, topic);
+ }
+
+ @Test
+ public void testDeleteNamespaceDeletesSegmentTopicsLeftBehind() throws Exception {
+ String namespace = getNamespace();
+ String topic = newScalableTopic(2);
+ publishString(topic, "v");
+ // What a scalable-topic delete that failed to delete the segment topics leaves: only the record is gone.
+ getPulsar().getPulsarResources().getScalableTopicResources()
+ .deleteScalableTopicAsync(TopicName.get(topic)).get();
+
+ admin.namespaces().deleteNamespace(namespace);
+
+ assertThat(store().getChildren("/managed-ledgers/" + namespace + "/segment").get())
+ .as("managed ledgers of the segment topics left behind")
+ .isEmpty();
+ }
+
+ @Test
+ public void testRecreatedNamespaceDoesNotResurrectScalableTopic() throws Exception {
+ String namespace = getNamespace();
+ String topic = newScalableTopic(1);
+ publishString(topic, "old");
+
+ admin.namespaces().deleteNamespace(namespace, true);
+ admin.namespaces().createNamespace(namespace, Set.of(SharedPulsarCluster.CLUSTER_NAME));
+
+ assertThat(admin.scalableTopics().listScalableTopics(namespace))
+ .as("scalable topics of the re-created namespace")
+ .isEmpty();
+ // A new topic with the name of the deleted one, and another schema, starts empty.
+ admin.scalableTopics().createScalableTopic(topic, 1);
+ @Cleanup
+ Producer<Integer> producer = v5Client.newProducer(Schema.int32())
+ .topic(topic)
+ .create();
+ producer.newMessage().key("k").value(1).send();
+ @Cleanup
+ CheckpointConsumer<Integer> consumer = v5Client.newCheckpointConsumer(Schema.int32())
+ .topic(topic)
+ .startPosition(Checkpoint.earliest())
+ .create();
+ Message<Integer> msg = consumer.receive(Duration.ofSeconds(10));
+ assertThat(msg).as("first message of the new topic").isNotNull();
+ assertThat(msg.value()).isEqualTo(1);
+ }
+
+ @Test
+ public void testForceDeleteTenantDeletesScalableTopic() throws Exception {
+ String tenant = "scalable-tenant-" + UUID.randomUUID().toString().substring(0, 8);
+ admin.tenants().createTenant(tenant, TenantInfo.builder()
+ .allowedClusters(Set.of(SharedPulsarCluster.CLUSTER_NAME))
+ .build());
+ String namespace = tenant + "/ns";
+ admin.namespaces().createNamespace(namespace, Set.of(SharedPulsarCluster.CLUSTER_NAME));
+ String topic = "topic://" + namespace + "/scalable";
+ admin.scalableTopics().createScalableTopic(topic, 1);
+ publishString(topic, "v");
+
+ admin.tenants().deleteTenant(tenant, true);
+
+ assertScalableTopicDeleted(namespace, topic);
+ assertThat(store().getChildren("/topics/" + tenant).get())
+ .as("scalable topic records of the deleted tenant")
+ .isEmpty();
+ }
+
+ @Test
+ public void testForceDeleteNamespaceDeletesMigratedTopic() throws Exception {
+ String namespace = getNamespace();
+ String base = namespace + "/migrated-" + UUID.randomUUID().toString().substring(0, 8);
+ admin.topics().createNonPartitionedTopic("persistent://" + base);
+ publishString("persistent://" + base, "pre");
+ admin.scalableTopics().migrateToScalable(base, false);
+ publishString("topic://" + base, "post");
+
+ admin.namespaces().deleteNamespace(namespace, true);
+
+ assertScalableTopicDeleted(namespace, "topic://" + base);
+ assertThat(getPulsar().getPulsarResources().getTopicResources()
+ .persistentTopicExists(TopicName.get("persistent://" + base)).get())
+ .as("the persistent topic the scalable topic was migrated from")
+ .isFalse();
+ }
+
+ @Test
+ public void testForceDeleteNamespaceWithSameNamedNonPersistentTopic() throws Exception {
+ String namespace = getNamespace();
+ String topic = newScalableTopic(1);
+ publishString(topic, "v");
+ // Connected, so the namespace delete deletes the non-persistent topic as an active one.
+ @Cleanup
+ var nonPersistentProducer = pulsarClient.newProducer()
+ .topic("non-persistent://" + TopicName.get(topic).getNamespace() + "/"
+ + TopicName.get(topic).getLocalName())
+ .create();
+
+ admin.namespaces().deleteNamespace(namespace, true);
+
+ assertScalableTopicDeleted(namespace, topic);
+ }
+
+ private void publishString(String topic, String value) throws Exception {
+ @Cleanup
+ Producer<String> producer = v5Client.newProducer(Schema.string())
+ .topic(topic)
+ .create();
+ producer.newMessage().key("k").value(value).send();
+ }
+
+ private MetadataStore store() {
+ return getPulsar().getPulsarResources().getScalableTopicResources().getStore();
+ }
+
+ private void assertScalableTopicDeleted(String namespace, String topic) {
+ ScalableTopicResources resources = getPulsar().getPulsarResources().getScalableTopicResources();
+ SoftAssertions softly = new SoftAssertions();
+ softly.assertThat(store().getChildren(resources.namespacePath(NamespaceName.get(namespace))).join())
+ .as("scalable topic records of the deleted namespace %s", namespace)
+ .isEmpty();
+ softly.assertThat(store().getChildren("/managed-ledgers/" + namespace + "/segment").join())
+ .as("managed ledgers of the segments of the deleted namespace %s", namespace)
+ .isEmpty();
+ softly.assertThat(getPulsar().getSchemaRegistryService()
+ .getSchema(TopicName.get(topic).getSchemaName()).join())
+ .as("schema of %s", topic)
+ .isNull();
+ softly.assertAll();
+ }
+}
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/ScalableTopicNamespaceDeleteZooKeeperTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/ScalableTopicNamespaceDeleteZooKeeperTest.java
new file mode 100644
index 000000000000..31b77416c200
--- /dev/null
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/ScalableTopicNamespaceDeleteZooKeeperTest.java
@@ -0,0 +1,116 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pulsar.broker.service.scalable;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import java.util.Set;
+import java.util.UUID;
+import lombok.Cleanup;
+import org.apache.pulsar.broker.auth.MockedPulsarServiceBaseTest;
+import org.apache.pulsar.client.api.v5.Producer;
+import org.apache.pulsar.client.api.v5.PulsarClient;
+import org.apache.pulsar.client.api.v5.schema.Schema;
+import org.apache.pulsar.common.naming.TopicName;
+import org.apache.pulsar.metadata.api.MetadataStore;
+import org.testng.annotations.AfterClass;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.Test;
+
+/**
+ * Namespace deletion with scalable topics on ZooKeeper, which refuses to delete a node that has children: what
+ * the delete leaves under the namespace fails it after its retries.
+ */
+public class ScalableTopicNamespaceDeleteZooKeeperTest extends MockedPulsarServiceBaseTest {
+
+ private PulsarClient v5Client;
+
+ @BeforeClass(alwaysRun = true)
+ @Override
+ protected void setup() throws Exception {
+ conf.setForceDeleteNamespaceAllowed(true);
+ internalSetup();
+ setupDefaultTenantAndNamespace();
+ v5Client = PulsarClient.builder()
+ .serviceUrl(pulsar.getBrokerServiceUrl())
+ .build();
+ }
+
+ @AfterClass(alwaysRun = true)
+ @Override
+ protected void cleanup() throws Exception {
+ if (v5Client != null) {
+ v5Client.close();
+ v5Client = null;
+ }
+ internalCleanup();
+ }
+
+ @Test
+ public void testForceDeleteNamespaceWithScalableTopic() throws Exception {
+ String namespace = newNamespace();
+ String topic = "topic://" + namespace + "/scalable";
+ admin.scalableTopics().createScalableTopic(topic, 1);
+ publishString(topic, "v");
+
+ admin.namespaces().deleteNamespace(namespace, true);
+
+ assertNamespaceDeleted(namespace, topic);
+ }
+
+ @Test
+ public void testDeleteNamespaceAfterDeletingItsScalableTopic() throws Exception {
+ String namespace = newNamespace();
+ String topic = "topic://" + namespace + "/scalable";
+ admin.scalableTopics().createScalableTopic(topic, 1);
+ publishString(topic, "v");
+ admin.scalableTopics().deleteScalableTopic(topic, true);
+
+ admin.namespaces().deleteNamespace(namespace);
+
+ assertNamespaceDeleted(namespace, topic);
+ }
+
+ private String newNamespace() throws Exception {
+ String namespace = "public/ns-" + UUID.randomUUID().toString().substring(0, 8);
+ admin.namespaces().createNamespace(namespace, Set.of(configClusterName));
+ return namespace;
+ }
+
+ private void publishString(String topic, String value) throws Exception {
+ @Cleanup
+ Producer<String> producer = v5Client.newProducer(Schema.string())
+ .topic(topic)
+ .create();
+ producer.newMessage().key("k").value(value).send();
+ }
+
+ private void assertNamespaceDeleted(String namespace, String topic) throws Exception {
+ assertThat(admin.namespaces().getNamespaces("public")).doesNotContain(namespace);
+ MetadataStore store = pulsar.getLocalMetadataStore();
+ assertThat(store.exists("/topics/" + namespace).get())
+ .as("scalable topic records of the deleted namespace %s", namespace)
+ .isFalse();
+ assertThat(store.exists("/managed-ledgers/" + namespace).get())
+ .as("managed ledgers of the deleted namespace %s", namespace)
+ .isFalse();
+ assertThat(pulsar.getSchemaRegistryService().getSchema(TopicName.get(topic).getSchemaName()).get())
+ .as("schema of %s", topic)
+ .isNull();
+ }
+}
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/client/api/v5/V5MultiBrokerNamespaceDeleteTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/client/api/v5/V5MultiBrokerNamespaceDeleteTest.java
new file mode 100644
index 000000000000..8115ed417bfa
--- /dev/null
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/client/api/v5/V5MultiBrokerNamespaceDeleteTest.java
@@ -0,0 +1,176 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pulsar.client.api.v5;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.assertj.core.api.Assertions.catchThrowable;
+import java.util.Optional;
+import java.util.Set;
+import java.util.UUID;
+import lombok.Cleanup;
+import org.apache.pulsar.broker.service.SharedMultiBrokerPulsarCluster;
+import org.apache.pulsar.client.admin.PulsarAdminException;
+import org.apache.pulsar.client.api.v5.schema.Schema;
+import org.apache.pulsar.common.naming.TopicName;
+import org.apache.pulsar.common.policies.data.TenantInfo;
+import org.apache.pulsar.metadata.api.MetadataStore;
+import org.assertj.core.api.SoftAssertions;
+import org.testng.annotations.Test;
+
+/**
+ * Namespace and tenant deletion with scalable topics, on Oxia: unlike the in-memory store of the single-broker
+ * tests, it refuses to delete a node that has children, so whatever the delete leaves under the namespace
+ * fails it.
+ */
+public class V5MultiBrokerNamespaceDeleteTest extends V5MultiBrokerClientBaseTest {
+
+ @Test
+ public void testDeleteNamespaceWithScalableTopicIsRejected() throws Exception {
+ String namespace = getNamespace();
+ String topic = newScalableTopic(1);
+
+ Throwable thrown = catchThrowable(() -> admin.namespaces().deleteNamespace(namespace));
+
+ SoftAssertions softly = new SoftAssertions();
+ softly.assertThat(thrown)
+ .as("deleting, without force, a namespace that has a scalable topic")
+ .isInstanceOf(PulsarAdminException.ConflictException.class);
+ softly.assertThat(admin.namespaces().getPolicies(namespace).deleted)
+ .as("the namespace is not marked deleted")
+ .isFalse();
+ softly.assertThat(admin.scalableTopics().listScalableTopics(namespace))
+ .containsExactly(topic);
+ softly.assertAll();
+ }
+
+ @Test
+ public void testForceDeleteNamespaceWithScalableTopic() throws Exception {
+ String namespace = getNamespace();
+ String topic = newScalableTopic(2);
+ publishString(topic, "v");
+
+ admin.namespaces().deleteNamespace(namespace, true);
+
+ assertNamespaceDeleted(namespace, topic);
+ }
+
+ @Test
+ public void testDeleteNamespaceAfterDeletingItsScalableTopic() throws Exception {
+ String namespace = getNamespace();
+ String topic = newScalableTopic(1);
+ publishString(topic, "v");
+ admin.scalableTopics().deleteScalableTopic(topic, true);
+
+ admin.namespaces().deleteNamespace(namespace);
+
+ assertNamespaceDeleted(namespace, topic);
+ }
+
+ @Test
+ public void testDeleteNamespaceDeletesSegmentTopicsLeftBehind() throws Exception {
+ String namespace = getNamespace();
+ String topic = newScalableTopic(2);
+ publishString(topic, "v");
+ // What a scalable-topic delete that failed to delete the segment topics leaves: only the record is gone.
+ brokers.get(0).getPulsarResources().getScalableTopicResources()
+ .deleteScalableTopicAsync(TopicName.get(topic)).get();
+
+ admin.namespaces().deleteNamespace(namespace);
+
+ assertThat(admin.namespaces().getNamespaces(SharedMultiBrokerPulsarCluster.TENANT_NAME))
+ .doesNotContain(namespace);
+ assertThat(store().exists("/managed-ledgers/" + namespace).get())
+ .as("managed ledgers of the deleted namespace %s", namespace)
+ .isFalse();
+ }
+
+ @Test
+ public void testDeleteNamespaceWithNodeLeftUnderItIsConflict() throws Exception {
+ String namespace = getNamespace();
+ // Like a topic created while the namespace is deleted, but one that nothing deletes.
+ String stray = "/managed-ledgers/" + namespace + "/stray";
+ store().put(stray, new byte[0], Optional.empty()).get();
+
+ assertThatThrownBy(() -> admin.namespaces().deleteNamespace(namespace))
+ .as("deleting a namespace that keeps a node under it, after the retries")
+ .isInstanceOf(PulsarAdminException.ConflictException.class)
+ .hasMessageContaining("/managed-ledgers/" + namespace);
+
+ store().delete(stray, Optional.empty()).get();
+ admin.namespaces().deleteNamespace(namespace);
+ assertThat(admin.namespaces().getNamespaces(SharedMultiBrokerPulsarCluster.TENANT_NAME))
+ .doesNotContain(namespace);
+ }
+
+ @Test
+ public void testForceDeleteTenantWithScalableTopic() throws Exception {
+ String tenant = "scalable-tenant-" + UUID.randomUUID().toString().substring(0, 8);
+ admin.tenants().createTenant(tenant, TenantInfo.builder()
+ .allowedClusters(Set.of(SharedMultiBrokerPulsarCluster.CLUSTER_NAME))
+ .build());
+ String namespace = tenant + "/ns";
+ admin.namespaces().createNamespace(namespace, Set.of(SharedMultiBrokerPulsarCluster.CLUSTER_NAME));
+ String topic = "topic://" + namespace + "/scalable";
+ admin.scalableTopics().createScalableTopic(topic, 1);
+ publishString(topic, "v");
+
+ admin.tenants().deleteTenant(tenant, true);
+
+ assertThat(admin.tenants().getTenants()).doesNotContain(tenant);
+ assertThat(store().exists("/topics/" + tenant).get())
+ .as("scalable topic records of the deleted tenant")
+ .isFalse();
+ assertThat(store().exists("/managed-ledgers/" + tenant).get())
+ .as("managed ledgers of the deleted tenant")
+ .isFalse();
+ assertSchemaDeleted(topic);
+ }
+
+ private void publishString(String topic, String value) throws Exception {
+ @Cleanup
+ Producer<String> producer = v5Client.newProducer(Schema.string())
+ .topic(topic)
+ .create();
+ producer.newMessage().key("k").value(value).send();
+ }
+
+ private MetadataStore store() {
+ return brokers.get(0).getPulsarResources().getScalableTopicResources().getStore();
+ }
+
+ private void assertNamespaceDeleted(String namespace, String topic) throws Exception {
+ assertThat(admin.namespaces().getNamespaces(SharedMultiBrokerPulsarCluster.TENANT_NAME))
+ .doesNotContain(namespace);
+ assertThat(store().exists("/topics/" + namespace).get())
+ .as("scalable topic records of the deleted namespace %s", namespace)
+ .isFalse();
+ assertThat(store().exists("/managed-ledgers/" + namespace).get())
+ .as("managed ledgers of the deleted namespace %s", namespace)
+ .isFalse();
+ assertSchemaDeleted(topic);
+ }
+
+ private void assertSchemaDeleted(String topic) throws Exception {
+ assertThat(brokers.get(0).getSchemaRegistryService()
+ .getSchema(TopicName.get(topic).getSchemaName()).get())
+ .as("schema of %s", topic)
+ .isNull();
+ }
+}
diff --git a/pulsar-metadata/src/main/java/org/apache/pulsar/metadata/api/MetadataStoreException.java b/pulsar-metadata/src/main/java/org/apache/pulsar/metadata/api/MetadataStoreException.java
index 76649f08175b..81080b62aa9e 100644
--- a/pulsar-metadata/src/main/java/org/apache/pulsar/metadata/api/MetadataStoreException.java
+++ b/pulsar-metadata/src/main/java/org/apache/pulsar/metadata/api/MetadataStoreException.java
@@ -175,8 +175,16 @@ public class MetadataStoreException extends IOException {
public static class NotEmptyException extends MetadataStoreException {
private static final long serialVersionUID = 1L;
+ private final String path;
+
public NotEmptyException(String path) {
super("Key '" + path + "' has children");
+ this.path = path;
+ }
+
+ /** The path of the node that has children. */
+ public String getPath() {
+ return path;
}
}