You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pulsar.apache.org by zi...@apache.org on 2026/06/18 07:29:25 UTC

(pulsar) branch master updated: [fix][broker] Prevent topic policy initialization race with a buffering listener wrapper (#26044)

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

nodece 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 b70b3a386c2 [fix][broker] Prevent topic policy initialization race with a buffering listener wrapper (#26044)
b70b3a386c2 is described below

commit b70b3a386c29374cdfa9c5367aacda8a730e4a71
Author: Lari Hotari <lh...@users.noreply.github.com>
AuthorDate: Thu Jun 18 10:29:17 2026 +0300

    [fix][broker] Prevent topic policy initialization race with a buffering listener wrapper (#26044)
---
 .../pulsar/broker/service/AbstractTopic.java       |   8 +-
 .../broker/service/TopicPolicyListenerWrapper.java | 117 +++++++++++++++++++
 .../service/nonpersistent/NonPersistentTopic.java  |  18 ++-
 .../broker/service/persistent/PersistentTopic.java |  56 +++++++---
 .../service/TopicPolicyListenerWrapperTest.java    | 124 +++++++++++++++++++++
 5 files changed, 304 insertions(+), 19 deletions(-)

diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/AbstractTopic.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/AbstractTopic.java
index 3d489f3ae53..9a17f44848b 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/AbstractTopic.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/AbstractTopic.java
@@ -564,14 +564,18 @@ public abstract class AbstractTopic implements Topic, TopicPolicyListener {
                 && maxProducers <= USER_CREATED_PRODUCER_COUNTER_UPDATER.get(this);
     }
 
+    protected TopicPolicyListener getTopicPolicyListener() {
+        return this;
+    }
+
     protected void registerTopicPolicyListener() {
         brokerService.getPulsar().getTopicPoliciesService()
-                .registerListenerAsync(TopicName.getPartitionedTopicName(topic), this);
+                .registerListenerAsync(TopicName.getPartitionedTopicName(topic), getTopicPolicyListener());
     }
 
     protected void unregisterTopicPolicyListener() {
         brokerService.getPulsar().getTopicPoliciesService()
-                .unregisterListener(TopicName.getPartitionedTopicName(topic), this);
+                .unregisterListener(TopicName.getPartitionedTopicName(topic), getTopicPolicyListener());
     }
 
     protected boolean isSameAddressProducersExceeded(Producer producer) {
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/TopicPolicyListenerWrapper.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/TopicPolicyListenerWrapper.java
new file mode 100644
index 00000000000..1e2f4336a3c
--- /dev/null
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/TopicPolicyListenerWrapper.java
@@ -0,0 +1,117 @@
+/*
+ * 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;
+
+import java.util.Optional;
+import java.util.concurrent.TimeUnit;
+import lombok.CustomLog;
+import org.apache.pulsar.common.policies.data.TopicPolicies;
+
+/**
+ * This TopicPolicyListener is used as a wrapper for the real TopicPolicyListener.
+ * This prevents a race condition in initialization where the topic policy state can change while the
+ * topic policy state is being applied to the topic in PersistentTopic#initTopicPolicy() method or in
+ * NonPersistentTopic#initialize method. The impact of the race conditions is that the topic policy state would
+ * be left in an inconsistent state until another update arrives. This is a rare corner case, but possible.
+ */
+@CustomLog
+public class TopicPolicyListenerWrapper implements TopicPolicyListener {
+    private final TopicPolicyListener realTopicListener;
+    // The latest value received during initialization, per scope. A null reference means no update was
+    // received during initialization (the loaded value should be used); an Optional that is present holds the
+    // received policies, and an empty Optional records that a delete (onUpdate(null)) was received, so the
+    // loaded value must not be applied. Optional is used because the map-like field cannot itself hold null
+    // while still distinguishing "not received" (null) from "received a delete" (Optional.empty()).
+    private Optional<TopicPolicies> latestGlobalPolicies;
+    private Optional<TopicPolicies> latestLocalPolicies;
+    private boolean initialized;
+    private final long createdTimestampNanos = System.nanoTime();
+    private static final long INITIALIZATION_WARNING_LOG_INTERVAL_NANOS = TimeUnit.SECONDS.toNanos(30);
+    private int lastIntervalLogged;
+
+    public TopicPolicyListenerWrapper(TopicPolicyListener realTopicListener) {
+        this.realTopicListener = realTopicListener;
+    }
+
+    @Override
+    public synchronized void onUpdate(TopicPolicies data) {
+        if (initialized) {
+            realTopicListener.onUpdate(data);
+            return;
+        }
+
+        maybeLogWarning();
+
+        // Record the latest value received during initialization so it can be applied (preferring it over the
+        // loaded value) in completeInitialization. A received value is stored as Optional.of(data) and a delete
+        // as Optional.empty(), so the delete is propagated downstream instead of being lost.
+        if (data == null) {
+            // A delete (onUpdate(null)) does not carry the global/local scope through the listener interface,
+            // so record it for both scopes; a later scoped update received during initialization still
+            // overrides its own scope.
+            latestGlobalPolicies = Optional.empty();
+            latestLocalPolicies = Optional.empty();
+        } else if (data.isGlobalPolicies()) {
+            latestGlobalPolicies = Optional.of(data);
+        } else {
+            latestLocalPolicies = Optional.of(data);
+        }
+    }
+
+    /**
+     * Complete initialization of the TopicPolicyListenerWrapper and emit the latest policies to the real listener.
+     * @param loadedGlobalPolicies the loaded global policies
+     * @param loadedLocalPolicies the loaded local policies
+     */
+    public synchronized void completeInitialization(TopicPolicies loadedGlobalPolicies,
+                                                    TopicPolicies loadedLocalPolicies) {
+        // The listener might have received a newer value (or a delete) than the loaded one while the loading
+        // was happening; prefer the latest value received during initialization, falling back to the loaded
+        // value only when nothing was received for that scope.
+        emitInitialPolicies(latestGlobalPolicies, loadedGlobalPolicies);
+        emitInitialPolicies(latestLocalPolicies, loadedLocalPolicies);
+        latestGlobalPolicies = null;
+        latestLocalPolicies = null;
+        initialized = true;
+    }
+
+    private void emitInitialPolicies(Optional<TopicPolicies> latestReceived, TopicPolicies loaded) {
+        if (latestReceived != null) {
+            // A value (or a delete) was received during initialization; it supersedes the loaded value.
+            realTopicListener.onUpdate(latestReceived.orElse(null));
+        } else if (loaded != null) {
+            realTopicListener.onUpdate(loaded);
+        }
+    }
+
+    // warn if the initialization takes too long and updates have been received
+    // this helps detect issues where completeInitialization didn't get called after loading policies
+    private void maybeLogWarning() {
+        long durationNanos = System.nanoTime() - createdTimestampNanos;
+        int warningLogIntervalCount = (int) (durationNanos / INITIALIZATION_WARNING_LOG_INTERVAL_NANOS);
+        if (warningLogIntervalCount > lastIntervalLogged) {
+            log.warn().attr("topicPolicyListener", realTopicListener)
+                    .attr("sinceCreationMs", TimeUnit.NANOSECONDS.toMillis(durationNanos))
+                    .log("TopicPolicyUpdate buffered. TopicPolicyListenerWrapper initialization phase took too long. "
+                            + "completeInitialization should have been called to complete the phase.");
+            lastIntervalLogged = warningLogIntervalCount;
+        }
+    }
+}
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/nonpersistent/NonPersistentTopic.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/nonpersistent/NonPersistentTopic.java
index 0d9c2a251d8..a1ff0b83ef3 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/nonpersistent/NonPersistentTopic.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/nonpersistent/NonPersistentTopic.java
@@ -67,6 +67,7 @@ import org.apache.pulsar.broker.service.SubscriptionOption;
 import org.apache.pulsar.broker.service.Topic;
 import org.apache.pulsar.broker.service.TopicAttributes;
 import org.apache.pulsar.broker.service.TopicPolicyListener;
+import org.apache.pulsar.broker.service.TopicPolicyListenerWrapper;
 import org.apache.pulsar.broker.service.TransportCnx;
 import org.apache.pulsar.broker.service.schema.exceptions.IncompatibleSchemaException;
 import org.apache.pulsar.broker.service.schema.exceptions.NotExistSchemaException;
@@ -131,6 +132,9 @@ public class NonPersistentTopic extends AbstractTopic implements Topic, TopicPol
             TOPIC_ATTRIBUTES_FIELD_UPDATER = AtomicReferenceFieldUpdater.newUpdater(
                     NonPersistentTopic.class, TopicAttributes.class, "topicAttributes");
 
+    // prevents race conditions in topic policy initialization
+    private final TopicPolicyListenerWrapper topicPolicyListener = new TopicPolicyListenerWrapper(this);
+
     private static class TopicStats {
         public double averageMsgSize;
         public double aggMsgRateIn;
@@ -186,7 +190,14 @@ public class NonPersistentTopic extends AbstractTopic implements Topic, TopicPol
                     updatePublishRateLimiter();
                     updateResourceGroupLimiter(policies);
                     return updateClusterMigrated();
-                }, getPoliciesNotifyThread());
+                }, getPoliciesNotifyThread())
+                // Complete the topic-policy listener wrapper so buffered and future topic-level policy
+                // updates are forwarded to this topic. Without this the wrapper stays uninitialized forever
+                // and all topic-level policy updates are silently dropped. Unlike PersistentTopic,
+                // non-persistent topics don't load initial topic policies (matching the previous behavior),
+                // so the loaded values are passed as null.
+                .thenRunAsync(() -> topicPolicyListener.completeInitialization(null, null),
+                        getPoliciesNotifyThread());
     }
 
     @Override
@@ -1324,4 +1335,9 @@ public class NonPersistentTopic extends AbstractTopic implements Topic, TopicPol
         return TOPIC_ATTRIBUTES_FIELD_UPDATER.updateAndGet(this,
                 old -> old != null ? old : new TopicAttributes(TopicName.get(topic)));
     }
+
+    @Override
+    public TopicPolicyListener getTopicPolicyListener() {
+        return topicPolicyListener;
+    }
 }
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/persistent/PersistentTopic.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/persistent/PersistentTopic.java
index 4a9094383d7..596808e0910 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/persistent/PersistentTopic.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/persistent/PersistentTopic.java
@@ -60,6 +60,7 @@ import java.util.concurrent.atomic.AtomicReference;
 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
 import java.util.function.BiConsumer;
 import java.util.function.BiFunction;
+import java.util.function.Function;
 import lombok.Getter;
 import lombok.Value;
 import org.apache.bookkeeper.client.BKException.BKNoSuchLedgerExistsException;
@@ -136,6 +137,8 @@ import org.apache.pulsar.broker.service.Subscription;
 import org.apache.pulsar.broker.service.SubscriptionOption;
 import org.apache.pulsar.broker.service.Topic;
 import org.apache.pulsar.broker.service.TopicPoliciesService;
+import org.apache.pulsar.broker.service.TopicPolicyListener;
+import org.apache.pulsar.broker.service.TopicPolicyListenerWrapper;
 import org.apache.pulsar.broker.service.TransportCnx;
 import org.apache.pulsar.broker.service.schema.BookkeeperSchemaStorage;
 import org.apache.pulsar.broker.service.schema.exceptions.IncompatibleSchemaException;
@@ -297,6 +300,10 @@ public class PersistentTopic extends AbstractTopic implements Topic, AddEntryCal
     // Record the last time max read position is moved forward, unless it's a marker message.
     @Getter
     private volatile long lastMaxReadPositionMovedForwardTimestamp = 0;
+
+    // prevents race conditions in topic policy initialization
+    private final TopicPolicyListenerWrapper topicPolicyListener = new TopicPolicyListenerWrapper(this);
+
     @Getter
     private final ExecutorService orderedExecutor;
 
@@ -4947,22 +4954,34 @@ public class PersistentTopic extends AbstractTopic implements Topic, AddEntryCal
         final var topicPoliciesService = brokerService.pulsar().getTopicPoliciesService();
         final var partitionedTopicName = TopicName.getPartitionedTopicName(topic);
 
-        return topicPoliciesService.registerListenerAsync(partitionedTopicName, this).thenCompose(registered -> {
-            if (!registered) {
-                return CompletableFuture.completedFuture(null);
-            }
-            if (ExtensibleLoadManagerImpl.isInternalTopic(topic)) {
-                return CompletableFuture.completedFuture(null);
-            }
-            return topicPoliciesService.getTopicPoliciesAsync(partitionedTopicName,
-                    TopicPoliciesService.GetType.GLOBAL_ONLY)
-            .thenAcceptAsync(optionalPolicies -> optionalPolicies.ifPresent(this::onUpdate),
-                    getPoliciesNotifyThread())
-            .thenCompose(__ -> topicPoliciesService.getTopicPoliciesAsync(partitionedTopicName,
-                    TopicPoliciesService.GetType.LOCAL_ONLY))
-            .thenAcceptAsync(optionalPolicies -> optionalPolicies.ifPresent(this::onUpdate),
-                    getPoliciesNotifyThread());
-        });
+        return topicPoliciesService.registerListenerAsync(partitionedTopicName, topicPolicyListener)
+                .thenCompose(registered -> {
+                    if (!registered) {
+                        return CompletableFuture.completedFuture(null);
+                    }
+                    if (ExtensibleLoadManagerImpl.isInternalTopic(topic)) {
+                        // Internal topics don't load topic-level policies, but the listener wrapper must
+                        // still be initialized so any buffered/future updates are forwarded to the topic
+                        // instead of being silently dropped.
+                        return CompletableFuture.runAsync(
+                                () -> topicPolicyListener.completeInitialization(null, null),
+                                getPoliciesNotifyThread());
+                    }
+                    // future for fetching global topic policies
+                    CompletableFuture<Optional<TopicPolicies>> globalPoliciesFuture =
+                            topicPoliciesService.getTopicPoliciesAsync(partitionedTopicName,
+                                    TopicPoliciesService.GetType.GLOBAL_ONLY);
+                    // future for fetching local topic policies
+                    CompletableFuture<Optional<TopicPolicies>> localPoliciesFuture =
+                            topicPoliciesService.getTopicPoliciesAsync(partitionedTopicName,
+                                    TopicPoliciesService.GetType.LOCAL_ONLY);
+                    return globalPoliciesFuture.thenCombine(localPoliciesFuture, (global, local) -> {
+                        // finally update the topic policies with the latest value or loaded value
+                        return CompletableFuture.runAsync(() ->
+                                topicPolicyListener.completeInitialization(global.orElse(null), local.orElse(null)),
+                                getPoliciesNotifyThread());
+                    }).thenCompose(Function.identity());
+                });
     }
 
     @VisibleForTesting
@@ -5139,4 +5158,9 @@ public class PersistentTopic extends AbstractTopic implements Topic, AddEntryCal
 
         return future;
     }
+
+    @Override
+    public TopicPolicyListener getTopicPolicyListener() {
+        return topicPolicyListener;
+    }
 }
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/TopicPolicyListenerWrapperTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/TopicPolicyListenerWrapperTest.java
new file mode 100644
index 00000000000..0e755359274
--- /dev/null
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/TopicPolicyListenerWrapperTest.java
@@ -0,0 +1,124 @@
+/*
+ * 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;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatCode;
+import java.util.ArrayList;
+import java.util.List;
+import org.apache.pulsar.common.policies.data.TopicPolicies;
+import org.testng.annotations.Test;
+
+@Test(groups = "broker")
+public class TopicPolicyListenerWrapperTest {
+
+    private static TopicPolicies globalPolicies() {
+        return TopicPolicies.builder().isGlobal(true).build();
+    }
+
+    private static TopicPolicies localPolicies() {
+        return TopicPolicies.builder().isGlobal(false).build();
+    }
+
+    private static final class RecordingListener implements TopicPolicyListener {
+        final List<TopicPolicies> updates = new ArrayList<>();
+
+        @Override
+        public void onUpdate(TopicPolicies data) {
+            updates.add(data);
+        }
+    }
+
+    @Test
+    public void shouldBufferUpdatesUntilInitializedThenForwardLive() {
+        RecordingListener real = new RecordingListener();
+        TopicPolicyListenerWrapper wrapper = new TopicPolicyListenerWrapper(real);
+
+        // Updates received before initialization are buffered, not forwarded.
+        TopicPolicies bufferedLocal = localPolicies();
+        wrapper.onUpdate(bufferedLocal);
+        assertThat(real.updates).isEmpty();
+
+        // On completion, the buffered local value wins over the loaded local value; the loaded global value
+        // is applied since none was buffered.
+        TopicPolicies loadedGlobal = globalPolicies();
+        wrapper.completeInitialization(loadedGlobal, localPolicies());
+        assertThat(real.updates).containsExactly(loadedGlobal, bufferedLocal);
+
+        // After initialization, updates are forwarded immediately.
+        TopicPolicies liveUpdate = localPolicies();
+        wrapper.onUpdate(liveUpdate);
+        assertThat(real.updates).containsExactly(loadedGlobal, bufferedLocal, liveUpdate);
+    }
+
+    @Test
+    public void shouldPreferBufferedOverLoadedForBothScopes() {
+        RecordingListener real = new RecordingListener();
+        TopicPolicyListenerWrapper wrapper = new TopicPolicyListenerWrapper(real);
+
+        TopicPolicies bufferedGlobal = globalPolicies();
+        TopicPolicies bufferedLocal = localPolicies();
+        wrapper.onUpdate(bufferedGlobal);
+        wrapper.onUpdate(bufferedLocal);
+
+        wrapper.completeInitialization(globalPolicies(), localPolicies());
+        assertThat(real.updates).containsExactly(bufferedGlobal, bufferedLocal);
+    }
+
+    @Test
+    public void shouldApplyLoadedWhenNothingBuffered() {
+        RecordingListener real = new RecordingListener();
+        TopicPolicyListenerWrapper wrapper = new TopicPolicyListenerWrapper(real);
+
+        TopicPolicies loadedGlobal = globalPolicies();
+        TopicPolicies loadedLocal = localPolicies();
+        wrapper.completeInitialization(loadedGlobal, loadedLocal);
+        assertThat(real.updates).containsExactly(loadedGlobal, loadedLocal);
+    }
+
+    @Test
+    public void shouldSuppressLoadedValuesWhenDeletedBeforeInitialization() {
+        RecordingListener real = new RecordingListener();
+        TopicPolicyListenerWrapper wrapper = new TopicPolicyListenerWrapper(real);
+
+        // A delete (null) arriving before initialization must not NPE and must not be forwarded yet (#26037).
+        assertThatCode(() -> wrapper.onUpdate(null)).doesNotThrowAnyException();
+        assertThat(real.updates).isEmpty();
+
+        // The delete supersedes the (now-stale) loaded values: they are not applied, and the delete (null) is
+        // propagated downstream instead.
+        wrapper.completeInitialization(globalPolicies(), localPolicies());
+        assertThat(real.updates).containsExactly(null, null);
+    }
+
+    @Test
+    public void shouldApplyLatestScopedUpdateOverEarlierDeleteDuringInitialization() {
+        RecordingListener real = new RecordingListener();
+        TopicPolicyListenerWrapper wrapper = new TopicPolicyListenerWrapper(real);
+
+        // A delete records empty for both scopes, then a newer global update overrides only the global scope.
+        wrapper.onUpdate(null);
+        TopicPolicies newerGlobal = globalPolicies();
+        wrapper.onUpdate(newerGlobal);
+
+        wrapper.completeInitialization(globalPolicies(), localPolicies());
+        // Global: the newer update wins; Local: the delete (null) wins over the loaded local value.
+        assertThat(real.updates).containsExactly(newerGlobal, null);
+    }
+}