You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pulsar.apache.org by lh...@apache.org on 2026/10/17 06:32:59 UTC

(pulsar) branch branch-4.2 updated (d2bd02abcf6e -> 77f70756cfd6)

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

lhotari pushed a change to branch branch-4.2
in repository https://gitbox.apache.org/repos/asf/pulsar.git


    from d2bd02abcf6e [fix][broker] PIP-442: Fix unbounded executor queue growth and single-thread bottleneck in the topic list memory limiter (#26929)
     new 465f9ca64764 [fix][misc] Fix Backoff mandatory-stop timer tracking (#25282)
     new ca26d9ada0f6 [fix][broker]The partitions of the topic was wrongly created even though this cluster was not allowed to access it (#25443)
     new 77f70756cfd6 [improve][ml] Bound the requeues of size-based cache eviction to one cycle through the removal queue (#26933)

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:
 conf/broker.conf                                   |  15 ++-
 conf/standalone.conf                               |  15 ++-
 .../mledger/ManagedLedgerFactoryConfig.java        |  15 ++-
 .../impl/cache/RangeCacheRemovalCounters.java      |   4 +
 .../mledger/impl/cache/RangeCacheRemovalQueue.java |  11 +-
 .../impl/cache/RangeEntryCacheManagerImpl.java     |   3 +-
 .../impl/cache/RangeCacheRemovalQueueTest.java     | 123 +++++++++++++++++++++
 .../apache/pulsar/broker/ServiceConfiguration.java |  17 ++-
 .../broker/admin/impl/PersistentTopicsBase.java    |  46 +++++---
 .../pulsar/broker/service/BrokerService.java       |  32 ++++++
 .../service/OneWayReplicatorUsingGlobalZKTest.java |  33 ++++++
 .../org/apache/pulsar/common/util/Backoff.java     |   7 +-
 .../org/apache/pulsar/common/util/BackoffTest.java |  93 ++++++++++++++++
 13 files changed, 388 insertions(+), 26 deletions(-)


(pulsar) 02/03: [fix][broker]The partitions of the topic was wrongly created even though this cluster was not allowed to access it (#25443)

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.2
in repository https://gitbox.apache.org/repos/asf/pulsar.git

commit ca26d9ada0f65923a1cbf2648e53f5ca6dd579a9
Author: fengyubiao <yu...@streamnative.io>
AuthorDate: Sat Oct 17 10:17:35 2026 +0800

    [fix][broker]The partitions of the topic was wrongly created even though this cluster was not allowed to access it (#25443)
    
    Co-authored-by: Matteo Merli <mm...@apache.org>
    (cherry picked from commit 1cd3457c0a52753a5e995b1b4a17e024cf41952f)
---
 .../broker/admin/impl/PersistentTopicsBase.java    | 46 +++++++++++++++-------
 .../pulsar/broker/service/BrokerService.java       | 32 +++++++++++++++
 .../service/OneWayReplicatorUsingGlobalZKTest.java | 33 ++++++++++++++++
 3 files changed, 96 insertions(+), 15 deletions(-)

diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/impl/PersistentTopicsBase.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/impl/PersistentTopicsBase.java
index 6b85eb8b809d..aad4141f5919 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/impl/PersistentTopicsBase.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/impl/PersistentTopicsBase.java
@@ -49,6 +49,7 @@ import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicInteger;
 import java.util.concurrent.atomic.AtomicReference;
 import java.util.function.BiConsumer;
+import java.util.function.Consumer;
 import java.util.stream.Collectors;
 import java.util.stream.IntStream;
 import javax.ws.rs.WebApplicationException;
@@ -551,27 +552,42 @@ public class PersistentTopicsBase extends AdminResource {
     }
 
     protected void internalCreateMissedPartitions(AsyncResponse asyncResponse) {
-        getPartitionedTopicMetadataAsync(topicName, false, false).thenAccept(metadata -> {
-            if (metadata != null && metadata.partitions > 0) {
-                validateNamespaceOperationAsync(topicName.getNamespaceObject(),
-                        NamespaceOperation.CREATE_TOPIC)
-                .thenCompose(__ -> tryCreatePartitionsAsync(metadata.partitions)).thenAccept(v -> {
-                    asyncResponse.resume(Response.noContent().build());
-                }).exceptionally(e -> {
-                    log.error("[{}] Failed to create partitions for topic {}", clientAppId(), topicName);
-                    resumeAsyncResponseExceptionally(asyncResponse, e);
-                    return null;
-                });
-            } else {
-                throw new RestException(Status.NOT_FOUND, String.format("Topic %s does not exist", topicName));
-            }
-        }).exceptionally(ex -> {
+        Consumer<Throwable> errorHandler = ex -> {
             // If the exception is not redirect exception we need to log it.
             if (!isRedirectException(ex)) {
                 log.error("[{}] Failed to create partitions for topic {}",
                         clientAppId(), topicName);
             }
             resumeAsyncResponseExceptionally(asyncResponse, ex);
+        };
+        pulsar().getBrokerService().isCurrentClusterAllowed(topicName).thenAccept(allowed -> {
+            if (!allowed) {
+                resumeAsyncResponseExceptionally(asyncResponse,
+                    new RestException(Status.BAD_REQUEST, String.format("Topic [%s] is not allowed to be loaded"
+                        + " up on the current cluster, please recheck replication polices.", topicName)));
+                return;
+            }
+            getPartitionedTopicMetadataAsync(topicName, false, false).thenAccept(metadata -> {
+                if (metadata != null && metadata.partitions > 0) {
+                    validateNamespaceOperationAsync(topicName.getNamespaceObject(),
+                        NamespaceOperation.CREATE_TOPIC)
+                        .thenCompose(__ -> tryCreatePartitionsAsync(metadata.partitions)).thenAccept(v -> {
+                            asyncResponse.resume(Response.noContent().build());
+                        }).exceptionally(e -> {
+                            log.error("[{}] Failed to create partitions for topic {}", clientAppId(), topicName);
+                            resumeAsyncResponseExceptionally(asyncResponse, e);
+                            return null;
+                        });
+                } else {
+                    resumeAsyncResponseExceptionally(asyncResponse,
+                            new RestException(Status.NOT_FOUND, String.format("Topic %s does not exist", topicName)));
+                }
+            }).exceptionally(ex -> {
+                errorHandler.accept(ex);
+                return null;
+            });
+        }).exceptionally(ex -> {
+            errorHandler.accept(ex);
             return null;
         });
     }
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/BrokerService.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/BrokerService.java
index 50bd53736b09..390ff99f6b06 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/BrokerService.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/BrokerService.java
@@ -54,6 +54,7 @@ import java.time.Clock;
 import java.time.Duration;
 import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.Collection;
 import java.util.Collections;
 import java.util.HashMap;
 import java.util.HashSet;
@@ -4316,6 +4317,37 @@ public class BrokerService implements Closeable {
         this.pulsarChannelInitFactory = factory;
     }
 
+    /**
+     * Whether the current cluster is allowed to access the topic, by the same rule that is applied when the topic is
+     * loaded: the effective replication clusters (topic level, then global topic level, then namespace level) or the
+     * namespace-level allowed clusters contain the current cluster.
+     */
+    public CompletableFuture<Boolean> isCurrentClusterAllowed(@NonNull TopicName topicName) {
+        final String cluster = pulsar.getConfig().getClusterName();
+        final CompletableFuture<Optional<TopicPolicies>> topicPoliciesFuture =
+                getTopicPoliciesBypassSystemTopic(topicName, TopicPoliciesService.GetType.LOCAL_ONLY);
+        final CompletableFuture<Optional<TopicPolicies>> globalTopicPoliciesFuture =
+                getTopicPoliciesBypassSystemTopic(topicName, TopicPoliciesService.GetType.GLOBAL_ONLY);
+        final CompletableFuture<Optional<Policies>> nsPoliciesFuture = pulsar.getPulsarResources()
+                .getNamespaceResources().getPoliciesAsync(topicName.getNamespaceObject());
+        return CompletableFuture.allOf(topicPoliciesFuture, globalTopicPoliciesFuture, nsPoliciesFuture)
+                .thenApply(__ -> {
+                    Optional<Policies> nsPolicies = nsPoliciesFuture.join();
+                    List<String> topicClusters = topicPoliciesFuture.join()
+                            .map(TopicPolicies::getReplicationClusters)
+                            .or(() -> globalTopicPoliciesFuture.join().map(TopicPolicies::getReplicationClusters))
+                            .orElse(null);
+                    Collection<String> replicationClusters = topicClusters != null ? topicClusters
+                            : nsPolicies.map(p -> p.replication_clusters).orElse(null);
+                    // A topic without replication clusters is loaded without checking the cluster either.
+                    if (isEmpty(replicationClusters)) {
+                        return true;
+                    }
+                    return replicationClusters.contains(cluster)
+                            || nsPolicies.map(p -> p.allowed_clusters.contains(cluster)).orElse(false);
+                });
+    }
+
     /***
      * After PIP-321 Introduce allowed-cluster at the namespace level, the condition that whether the cluster is
      * allowed to access by the current cluster was defined by two fields:
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/OneWayReplicatorUsingGlobalZKTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/OneWayReplicatorUsingGlobalZKTest.java
index edd577e6d76b..c6678bad783a 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/OneWayReplicatorUsingGlobalZKTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/OneWayReplicatorUsingGlobalZKTest.java
@@ -195,6 +195,15 @@ public class OneWayReplicatorUsingGlobalZKTest extends OneWayReplicatorTest {
         });
         waitReplicatorStopped(subTopic, pulsar1, pulsar2, true);
 
+        try {
+            admin2.topics().createMissedPartitions(topicName);
+            fail("The action that creates mission partitions should have thrown exception");
+        } catch (Exception e) {
+            assertTrue(e.getMessage().contains("is not allowed to be loaded up"));
+        }
+        assertFalse(admin2.topics().getList(replicatedNamespace)
+            .contains(TopicName.get(topicName).getPartition(0).toString()));
+
         // Remove global policy.
         admin1.topicPolicies(true).removeReplicationClusters(topicName);
         Producer<byte[]> producer2 = client1.newProducer().topic(topicName).create();
@@ -960,4 +969,28 @@ public class OneWayReplicatorUsingGlobalZKTest extends OneWayReplicatorTest {
         p.close();
         admin1.topics().delete(topic);
     }
+
+    /**
+     * A cluster in the namespace-level allowed clusters can load the topic even when the topic-level replication
+     * clusters do not contain it, so it is allowed to create the missed partitions too.
+     */
+    @Test
+    public void testCreateMissedPartitionsOnAllowedClusterOutsideTopicReplication() throws Exception {
+        final String ns1 = defaultTenant + "/ns_" + UUID.randomUUID().toString().replace("-", "");
+        final String topicName = BrokerTestUtil.newUniqueName("persistent://" + ns1 + "/tp");
+        final String subTopic = TopicName.get(topicName).getPartition(0).toString();
+        admin1.namespaces().createNamespace(ns1);
+        admin1.namespaces().setNamespaceAllowedClusters(ns1, new HashSet<>(Arrays.asList(cluster1, cluster2)));
+        admin1.namespaces().setNamespaceReplicationClusters(ns1,
+                new HashSet<>(Arrays.asList(cluster1, cluster2)), true);
+        admin1.topics().createPartitionedTopic(topicName, 1);
+        admin1.topicPolicies(true).setReplicationClusters(topicName, Arrays.asList(cluster1));
+        Awaitility.await().untilAsserted(() -> {
+            Set<String> global2 = admin2.topicPolicies(true).getReplicationClusters(topicName, false);
+            assertEquals(global2, Collections.singleton(cluster1));
+        });
+
+        admin2.topics().createMissedPartitions(topicName);
+        assertTrue(admin2.topics().getList(ns1).contains(subTopic));
+    }
 }


(pulsar) 03/03: [improve][ml] Bound the requeues of size-based cache eviction to one cycle through the removal queue (#26933)

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.2
in repository https://gitbox.apache.org/repos/asf/pulsar.git

commit 77f70756cfd6b748871cf580bb9eb6422687d7b6
Author: Lari Hotari <lh...@users.noreply.github.com>
AuthorDate: Fri Oct 16 23:05:34 2026 -0700

    [improve][ml] Bound the requeues of size-based cache eviction to one cycle through the removal queue (#26933)
    
    (cherry picked from commit 23a7fb66989a7e2483d925ad7c16b0904b321315)
---
 conf/broker.conf                                   |  15 ++-
 conf/standalone.conf                               |  15 ++-
 .../mledger/ManagedLedgerFactoryConfig.java        |  15 ++-
 .../impl/cache/RangeCacheRemovalCounters.java      |   4 +
 .../mledger/impl/cache/RangeCacheRemovalQueue.java |  11 +-
 .../impl/cache/RangeEntryCacheManagerImpl.java     |   3 +-
 .../impl/cache/RangeCacheRemovalQueueTest.java     | 123 +++++++++++++++++++++
 .../apache/pulsar/broker/ServiceConfiguration.java |  17 ++-
 8 files changed, 193 insertions(+), 10 deletions(-)

diff --git a/conf/broker.conf b/conf/broker.conf
index cd42d55d0676..d82b1efdddb0 100644
--- a/conf/broker.conf
+++ b/conf/broker.conf
@@ -1303,7 +1303,12 @@ cacheEvictionByMarkDeletedPosition=false
 # This setting will override the cacheEvictionByMarkDeletedPosition setting.
 cacheEvictionByExpectedReadCount=true
 
-# Whether we should make a copy of the entry payloads when inserting in cache
+# Whether we should make a copy of the entry payloads when inserting in cache. Without a copy, a cached entry keeps
+# the buffer that it was received in allocated while it stays in the cache. That is a buffer of the Netty connection
+# that the entry arrived on, from a client or from a bookie, such as a receive buffer or one that the TLS handler or
+# the frame decoder allocated, and it can be much larger than the entry.
+# The cache size limit counts only the entry's own size, so size-based eviction doesn't bound that memory, and
+# managedLedgerCacheEvictionExtendTTLOfEntriesWithRemainingExpectedReadsMaxTimes extends how long it stays allocated.
 managedLedgerCacheCopyEntries=false
 
 # Threshold to which bring down the cache level when eviction is triggered
@@ -1330,7 +1335,13 @@ managedLedgerCacheEvictionTimeThresholdMillis=1000
 # - Consumers temporarily falling behind the tail
 # Entries with remaining expected reads will have their TTL extended up to this many times
 # before being eligible for eviction. The TTL will be extended by
-# managedLedgerCacheEvictionTimeThresholdMillis each time.
+# managedLedgerCacheEvictionTimeThresholdMillis each time. When the cache needs memory, size-based eviction
+# overrides this protection after requeuing an entry at most once per eviction pass. Both this protection and the
+# one of managedLedgerCacheEvictionExtendTTLOfRecentlyAccessed apply only in a pass's first cycle through the
+# cache's entries; after it, the pass removes entries in their order in the queue. Entries added while a pass is
+# running are past its first cycle, so that pass doesn't requeue them.
+# Without managedLedgerCacheCopyEntries, a cached entry keeps the larger buffer that it was received in allocated
+# while its time to live is extended, so consider enabling copying before raising this value.
 # Default is 5.
 managedLedgerCacheEvictionExtendTTLOfEntriesWithRemainingExpectedReadsMaxTimes=5
 
diff --git a/conf/standalone.conf b/conf/standalone.conf
index 112e2f485c05..91c5715a4e2e 100644
--- a/conf/standalone.conf
+++ b/conf/standalone.conf
@@ -835,7 +835,12 @@ cacheEvictionByMarkDeletedPosition=false
 # This setting will override the cacheEvictionByMarkDeletedPosition setting.
 cacheEvictionByExpectedReadCount=true
 
-# Whether we should make a copy of the entry payloads when inserting in cache
+# Whether we should make a copy of the entry payloads when inserting in cache. Without a copy, a cached entry keeps
+# the buffer that it was received in allocated while it stays in the cache. That is a buffer of the Netty connection
+# that the entry arrived on, from a client or from a bookie, such as a receive buffer or one that the TLS handler or
+# the frame decoder allocated, and it can be much larger than the entry.
+# The cache size limit counts only the entry's own size, so size-based eviction doesn't bound that memory, and
+# managedLedgerCacheEvictionExtendTTLOfEntriesWithRemainingExpectedReadsMaxTimes extends how long it stays allocated.
 managedLedgerCacheCopyEntries=false
 
 # Threshold to which bring down the cache level when eviction is triggered
@@ -862,7 +867,13 @@ managedLedgerCacheEvictionTimeThresholdMillis=1000
 # - Consumers temporarily falling behind the tail
 # Entries with remaining expected reads will have their TTL extended up to this many times
 # before being eligible for eviction. The TTL will be extended by
-# managedLedgerCacheEvictionTimeThresholdMillis each time.
+# managedLedgerCacheEvictionTimeThresholdMillis each time. When the cache needs memory, size-based eviction
+# overrides this protection after requeuing an entry at most once per eviction pass. Both this protection and the
+# one of managedLedgerCacheEvictionExtendTTLOfRecentlyAccessed apply only in a pass's first cycle through the
+# cache's entries; after it, the pass removes entries in their order in the queue. Entries added while a pass is
+# running are past its first cycle, so that pass doesn't requeue them.
+# Without managedLedgerCacheCopyEntries, a cached entry keeps the larger buffer that it was received in allocated
+# while its time to live is extended, so consider enabling copying before raising this value.
 # Default is 5.
 managedLedgerCacheEvictionExtendTTLOfEntriesWithRemainingExpectedReadsMaxTimes=5
 
diff --git a/managed-ledger/src/main/java/org/apache/bookkeeper/mledger/ManagedLedgerFactoryConfig.java b/managed-ledger/src/main/java/org/apache/bookkeeper/mledger/ManagedLedgerFactoryConfig.java
index 25fac086fd54..f410fe057e00 100644
--- a/managed-ledger/src/main/java/org/apache/bookkeeper/mledger/ManagedLedgerFactoryConfig.java
+++ b/managed-ledger/src/main/java/org/apache/bookkeeper/mledger/ManagedLedgerFactoryConfig.java
@@ -66,7 +66,13 @@ public class ManagedLedgerFactoryConfig {
      * - Consumers temporarily falling behind the tail
      * Entries with remaining expected reads will have their TTL extended up to this many times
      * before being eligible for eviction. The TTL will be extended by
-     * managedLedgerCacheEvictionTimeThresholdMillis each time.
+     * managedLedgerCacheEvictionTimeThresholdMillis each time. When the cache needs memory, size-based eviction
+     * overrides this protection after requeuing an entry at most once per eviction pass. Both this protection and the
+     * one of cacheEvictionExtendTTLOfRecentlyAccessed apply only in a pass's first cycle through the cache's entries;
+     * after it, the pass removes entries in their order in the queue. Entries added while a pass is running are past
+     * its first cycle, so that pass doesn't requeue them.
+     * Without copyEntriesInCache, a cached entry keeps the larger buffer that it was received in allocated while its
+     * time to live is extended, so consider enabling copying before raising this value.
      */
     private int cacheEvictionExtendTTLOfEntriesWithRemainingExpectedReadsMaxTimes = 5;
 
@@ -77,7 +83,12 @@ public class ManagedLedgerFactoryConfig {
     private boolean cacheEvictionExtendTTLOfRecentlyAccessed = true;
 
     /**
-     * Whether we should make a copy of the entry payloads when inserting in cache.
+     * Whether we should make a copy of the entry payloads when inserting in cache. Without a copy, a cached entry keeps
+     * the buffer that it was received in allocated while it stays in the cache. That is a buffer of the Netty
+     * connection that the entry arrived on, from a client or from a bookie, such as a receive buffer or one that the
+     * TLS handler or the frame decoder allocated, and it can be much larger than the entry.
+     * The cache size limit counts only the entry's own size, so size-based eviction doesn't bound that memory, and
+     * cacheEvictionExtendTTLOfEntriesWithRemainingExpectedReadsMaxTimes extends how long it stays allocated.
      */
     private boolean copyEntriesInCache = false;
 
diff --git a/managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/cache/RangeCacheRemovalCounters.java b/managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/cache/RangeCacheRemovalCounters.java
index bbbdb9dc619d..ac4fadd4916e 100644
--- a/managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/cache/RangeCacheRemovalCounters.java
+++ b/managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/cache/RangeCacheRemovalCounters.java
@@ -34,6 +34,8 @@ class RangeCacheRemovalCounters {
     };
     int removedEntries;
     long removedSize;
+    // the queue slots that an eviction pass has examined, to tell the queue's first cycle from the next ones
+    int evaluatedEntries;
 
     private RangeCacheRemovalCounters(Recycler.Handle<RangeCacheRemovalCounters> recyclerHandle) {
         this.recyclerHandle = recyclerHandle;
@@ -43,12 +45,14 @@ class RangeCacheRemovalCounters {
         RangeCacheRemovalCounters results = RECYCLER.get();
         results.removedEntries = 0;
         results.removedSize = 0;
+        results.evaluatedEntries = 0;
         return results;
     }
 
     void recycle() {
         removedEntries = 0;
         removedSize = 0;
+        evaluatedEntries = 0;
         recyclerHandle.recycle(this);
     }
 
diff --git a/managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/cache/RangeCacheRemovalQueue.java b/managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/cache/RangeCacheRemovalQueue.java
index 41d98c441cde..8730a5b49ee1 100644
--- a/managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/cache/RangeCacheRemovalQueue.java
+++ b/managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/cache/RangeCacheRemovalQueue.java
@@ -83,12 +83,19 @@ class RangeCacheRemovalQueue {
 
     public synchronized Pair<Integer, Long> evictLeastAccessedEntries(long sizeToFree) {
         checkArgument(sizeToFree > 0);
+        // A requeued entry goes to the end of the queue, where this pass meets it again. An entry is requeued only in
+        // the pass's first cycle through the queue, so that freeing memory takes at most two cycles, whatever the
+        // maximum requeue count for entries with expected reads is. After the first cycle, entries are removed in
+        // their order in the queue, so an entry with expected reads ahead of a recently accessed entry goes first.
+        // Inserting into the cache doesn't wait for a running pass, so entries added during the pass land behind
+        // the first cycle and are removed without a requeue when the pass reaches them.
+        int firstCycleEntries = removalQueue.size();
         return evictEntries((e, c) -> {
             // stop eviction if we have already removed enough entries
             if (c.removedSize >= sizeToFree) {
                 return EvictionResult.STOP;
             }
-            if (shouldRequeue(e)) {
+            if (c.evaluatedEntries <= firstCycleEntries && shouldRequeue(e)) {
                 return EvictionResult.REQUEUE;
             }
             // remove by default since there's a need to free up more memory
@@ -189,6 +196,8 @@ class RangeCacheRemovalQueue {
     private static EvictionResult evaluateEvictionPredicate(EvictionPredicate evictionPredicate,
                                                             RangeCacheRemovalCounters counters,
                                                             RangeCacheEntryWrapper entry) {
+        // every examined slot of the queue counts, also an entry that was already removed from the cache
+        counters.evaluatedEntries++;
         if (entry.key == null) {
             // entry has been removed by another thread
             return EvictionResult.MISSING;
diff --git a/managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/cache/RangeEntryCacheManagerImpl.java b/managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/cache/RangeEntryCacheManagerImpl.java
index 6f9e737cdb5e..0fde5d8c4fa9 100644
--- a/managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/cache/RangeEntryCacheManagerImpl.java
+++ b/managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/cache/RangeEntryCacheManagerImpl.java
@@ -136,7 +136,8 @@ public class RangeEntryCacheManagerImpl implements EntryCacheManager {
     Optional<CompletableFuture<Void>> triggerEvictionWhenNeeded() {
         long currentSize = this.currentSize.get();
 
-        // Trigger a single eviction in background. While the eviction is running we stop inserting entries in the cache
+        // Trigger a single eviction in background. While it is running, a new trigger returns the running eviction's
+        // future instead of starting another one. Inserting entries in the cache doesn't wait for it.
         if (currentSize > evictionTriggerThreshold) {
             CompletableFuture<Void> evictionCompletionFuture = null;
             while (evictionCompletionFuture == null) {
diff --git a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/cache/RangeCacheRemovalQueueTest.java b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/cache/RangeCacheRemovalQueueTest.java
index 35b7d548e3cc..b059125d6225 100644
--- a/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/cache/RangeCacheRemovalQueueTest.java
+++ b/managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/cache/RangeCacheRemovalQueueTest.java
@@ -28,7 +28,10 @@ import static org.testng.Assert.assertEquals;
 import static org.testng.Assert.assertFalse;
 import static org.testng.Assert.assertNotNull;
 import static org.testng.Assert.assertTrue;
+import io.netty.buffer.ByteBuf;
 import io.netty.buffer.Unpooled;
+import java.util.ArrayList;
+import java.util.List;
 import org.apache.bookkeeper.mledger.Position;
 import org.apache.bookkeeper.mledger.PositionFactory;
 import org.apache.bookkeeper.mledger.impl.EntryImpl;
@@ -174,6 +177,105 @@ public class RangeCacheRemovalQueueTest {
         assertThat(e3.key).isNull();
     }
 
+    @Test
+    public void testSizeBasedEvictionRequeuesAtMostOncePerPass() {
+        // A high requeue limit for entries with expected reads keeps them in the cache longer on time-based eviction,
+        // but size-based eviction must still free memory in one pass, without cycling through the queue up to the
+        // limit
+        RangeCacheRemovalQueue q = new RangeCacheRemovalQueue(
+                /*maxRequeueCountWhenHasExpectedReads*/ 1000,
+                /*extendTTLOfRecentlyAccessed*/ true);
+        List<RangeCacheEntryWrapper> entries = new ArrayList<>();
+        for (long entryId = 0; entryId < 100; entryId++) {
+            RangeCacheEntryWrapper e = addWrappedEntry(q, 12L, entryId, 2 /* has expected reads */, 10);
+            e.accessed = true;
+            entries.add(e);
+        }
+
+        Pair<Integer, Long> result = q.evictLeastAccessedEntries(500);
+
+        assertThat(result.getRight().longValue()).isEqualTo(500L);
+        assertThat(entries.stream().filter(e -> e.key == null).count()).isEqualTo(50);
+        // every remaining entry was requeued once, in the pass's first cycle, before the second cycle removed the
+        // oldest
+        assertThat(entries.stream().filter(e -> e.key != null).mapToInt(e -> e.requeueCount))
+                .hasSize(50).containsOnly(1);
+
+        // the remaining entries keep their other extensions: time-based eviction requeues them instead of removing
+        // them, although they have expired
+        long now = System.nanoTime();
+        entries.stream().filter(e -> e.key != null).forEach(e -> e.timestampNanos = now - 10_000_000L);
+        Pair<Integer, Long> timeBasedResult = q.evictLEntriesBeforeTimestamp(now - 1L);
+        assertThat(timeBasedResult.getLeft()).isZero();
+        assertThat(entries.stream().filter(e -> e.key != null).mapToInt(e -> e.requeueCount))
+                .hasSize(50).containsOnly(2);
+    }
+
+    @Test
+    public void testSizeBasedEvictionReleasesBuffersOfEntriesWithExpectedReads() {
+        // As testSizeBasedEvictionRequeuesAtMostOncePerPass, with a real cache and buffers: the entries that the
+        // pass's second cycle removes are removed from the cache, and their buffers are released
+        RangeCacheRemovalQueue q = new RangeCacheRemovalQueue(
+                /*maxRequeueCountWhenHasExpectedReads*/ 1000,
+                /*extendTTLOfRecentlyAccessed*/ false);
+        RangeCache cache = new RangeCache(q);
+        List<ByteBuf> buffers = new ArrayList<>();
+        for (long entryId = 0; entryId < 100; entryId++) {
+            ByteBuf buffer = Unpooled.directBuffer(10).writeZero(10);
+            Position position = PositionFactory.create(14L, entryId);
+            // the entry retains the buffer, and the cache takes the entry's reference
+            assertTrue(cache.put(position, EntryImpl.create(position, buffer, 2 /* has expected reads */)));
+            buffer.release();
+            buffers.add(buffer);
+        }
+        try {
+            assertThat(cache.getSize()).isEqualTo(1000L);
+
+            Pair<Integer, Long> result = q.evictLeastAccessedEntries(500);
+
+            assertThat(result.getLeft()).isEqualTo(50);
+            assertThat(result.getRight()).isEqualTo(500L);
+            assertThat(cache.getSize()).isEqualTo(500L);
+            assertThat(cache.getNumberOfEntries()).isEqualTo(50);
+            // the oldest half was requeued once and removed in the second cycle
+            for (int i = 0; i < 100; i++) {
+                Position position = PositionFactory.create(14L, i);
+                if (i < 50) {
+                    assertThat(cache.exists(position)).as("entry %d", i).isFalse();
+                    assertThat(buffers.get(i).refCnt()).as("entry %d", i).isZero();
+                } else {
+                    assertThat(cache.exists(position)).as("entry %d", i).isTrue();
+                    assertThat(buffers.get(i).refCnt()).as("entry %d", i).isEqualTo(1);
+                }
+            }
+        } finally {
+            cache.clear();
+        }
+        assertThat(buffers).allSatisfy(buffer -> assertThat(buffer.refCnt()).isZero());
+    }
+
+    @Test
+    public void testSizeBasedEvictionCountsRemovedEntriesInTheFirstCycle() {
+        // Entries that were removed from the cache stay in the queue until a pass meets them. They count toward the
+        // pass's first cycle, so that the live entries behind them are requeued only once.
+        RangeCacheRemovalQueue q = new RangeCacheRemovalQueue(
+                /*maxRequeueCountWhenHasExpectedReads*/ 1000,
+                /*extendTTLOfRecentlyAccessed*/ false);
+        for (long entryId = 0; entryId < 98; entryId++) {
+            RangeCacheEntryWrapper removed = addWrappedEntry(q, 13L, entryId, 0, 10);
+            removed.markRemoved(removed.key, removed.value);
+        }
+        RangeCacheEntryWrapper first = addWrappedEntry(q, 13L, 98L, 2 /* has expected reads */, 10);
+        RangeCacheEntryWrapper second = addWrappedEntry(q, 13L, 99L, 2 /* has expected reads */, 10);
+
+        Pair<Integer, Long> result = q.evictLeastAccessedEntries(10);
+
+        assertThat(result.getRight().longValue()).isEqualTo(10L);
+        assertThat(first.key).isNull();
+        assertThat(second.key).isNotNull();
+        assertThat(second.requeueCount).isEqualTo(1);
+    }
+
     @Test
     public void testSizeBasedEvictionEvictsEasiestFirstAsLongAsNeeded() {
         RangeCacheRemovalQueue q = new RangeCacheRemovalQueue(
@@ -216,6 +318,27 @@ public class RangeCacheRemovalQueueTest {
         assertThat(e3.key).isNull();
     }
 
+    @Test
+    public void testSizeBasedEvictionRemovesInQueueOrderAfterTheFirstCycle() {
+        // Both protections apply only in the pass's first cycle through the queue. After it, entries are removed in
+        // their order in the queue, so an entry with expected reads ahead of a recently accessed entry goes first.
+        RangeCacheRemovalQueue q = new RangeCacheRemovalQueue(
+                /*maxRequeueCountWhenHasExpectedReads*/ 5,
+                /*extendTTLOfRecentlyAccessed*/ true);
+
+        RangeCacheEntryWrapper e1 = addWrappedEntry(q, 11L, 1L, 2, 50); // has expected reads
+        RangeCacheEntryWrapper e2 = addWrappedEntry(q, 11L, 2L, 0, 40); // recently accessed
+        e2.accessed = true;
+        RangeCacheEntryWrapper e3 = addWrappedEntry(q, 11L, 3L, 0, 30); // easiest to evict
+
+        Pair<Integer, Long> r1 = q.evictLeastAccessedEntries(35);
+        assertNotNull(r1);
+        assertThat(r1.getRight().longValue()).isEqualTo(80L);
+        assertThat(e1.key).isNull();
+        assertThat(e2.key).isNotNull();
+        assertThat(e3.key).isNull();
+    }
+
     @Test
     public void testGetNonEvictableSizeCountsEntriesWithExpectedReads() {
         RangeCacheRemovalQueue q = new RangeCacheRemovalQueue(
diff --git a/pulsar-broker-common/src/main/java/org/apache/pulsar/broker/ServiceConfiguration.java b/pulsar-broker-common/src/main/java/org/apache/pulsar/broker/ServiceConfiguration.java
index e2caa617f4da..7cb1805f0efb 100644
--- a/pulsar-broker-common/src/main/java/org/apache/pulsar/broker/ServiceConfiguration.java
+++ b/pulsar-broker-common/src/main/java/org/apache/pulsar/broker/ServiceConfiguration.java
@@ -2312,7 +2312,13 @@ public class ServiceConfiguration implements PulsarConfiguration {
             (int) (DirectMemoryUtils.jvmMaxDirectMemory() / 5 / (1024 * 1024)));
 
     @FieldContext(category = CATEGORY_STORAGE_ML, doc = "Whether we should make a copy of the entry payloads when "
-            + "inserting in cache")
+            + "inserting in cache. Without a copy, a cached entry keeps the buffer that it was received in allocated\n"
+            + "while it stays in the cache. That is a buffer of the Netty connection that the entry arrived on, from\n"
+            + "a client or from a bookie, such as a receive buffer or one that the TLS handler or the frame decoder\n"
+            + "allocated, and it can be much larger than the entry. The cache size limit counts only\n"
+            + "the entry's own size, so size-based eviction doesn't bound that memory, and\n"
+            + "managedLedgerCacheEvictionExtendTTLOfEntriesWithRemainingExpectedReadsMaxTimes extends how long it\n"
+            + "stays allocated.")
     private boolean managedLedgerCacheCopyEntries = false;
 
     @FieldContext(category = CATEGORY_STORAGE_ML, doc = "Maximum buffer size for bytes read from storage."
@@ -2365,7 +2371,14 @@ public class ServiceConfiguration implements PulsarConfiguration {
             + "- Consumers temporarily falling behind the tail\n"
             + "Entries with remaining expected reads will have their TTL extended up to this many times\n"
             + "before being eligible for eviction. The TTL will be extended by\n"
-            + "managedLedgerCacheEvictionTimeThresholdMillis each time.\n"
+            + "managedLedgerCacheEvictionTimeThresholdMillis each time. When the cache needs memory, size-based\n"
+            + "eviction overrides this protection after requeuing an entry at most once per eviction pass. Both this\n"
+            + "protection and the one of managedLedgerCacheEvictionExtendTTLOfRecentlyAccessed apply only in a\n"
+            + "pass's first cycle through the cache's entries; after it, the pass removes entries in their order in\n"
+            + "the queue. Entries added while a pass is running are past its first cycle, so that pass doesn't\n"
+            + "requeue them.\n"
+            + "Without managedLedgerCacheCopyEntries, a cached entry keeps the larger buffer that it was received in\n"
+            + "allocated while its time to live is extended, so consider enabling copying before raising this value.\n"
             + "Default is 5.")
     private int managedLedgerCacheEvictionExtendTTLOfEntriesWithRemainingExpectedReadsMaxTimes = 5;
 


(pulsar) 01/03: [fix][misc] Fix Backoff mandatory-stop timer tracking (#25282)

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.2
in repository https://gitbox.apache.org/repos/asf/pulsar.git

commit 465f9ca6476486ed9fb7006f3f9a7d5670bcf1d0
Author: sinan liu <li...@gmail.com>
AuthorDate: Sat Oct 17 08:31:25 2026 +0800

    [fix][misc] Fix Backoff mandatory-stop timer tracking (#25282)
    
    Co-authored-by: Matteo Merli <mm...@apache.org>
    (cherry picked from commit 7c7efeed3cc6a19976cdd7616a868e00e56cd760)
---
 .../org/apache/pulsar/common/util/Backoff.java     |  7 +-
 .../org/apache/pulsar/common/util/BackoffTest.java | 93 ++++++++++++++++++++++
 2 files changed, 99 insertions(+), 1 deletion(-)

diff --git a/pulsar-common/src/main/java/org/apache/pulsar/common/util/Backoff.java b/pulsar-common/src/main/java/org/apache/pulsar/common/util/Backoff.java
index 5957ce86796a..0b15837eae77 100644
--- a/pulsar-common/src/main/java/org/apache/pulsar/common/util/Backoff.java
+++ b/pulsar-common/src/main/java/org/apache/pulsar/common/util/Backoff.java
@@ -64,6 +64,7 @@ public class Backoff {
     private Duration next;
     @Getter
     private Instant firstBackoffTime;
+    private boolean firstBackoffTimeSet;
     @Getter
     private boolean mandatoryStopMade;
 
@@ -74,6 +75,7 @@ public class Backoff {
         this.next = initial;
         this.clock = clock;
         this.firstBackoffTime = Instant.EPOCH;
+        this.firstBackoffTimeSet = false;
         if (initial.isZero() && max.isZero() && mandatoryStop.isZero()) {
             this.mandatoryStopMade = true;
         }
@@ -117,8 +119,9 @@ public class Backoff {
         if (!mandatoryStopMade) {
             Instant now = clock.instant();
             Duration timeElapsedSinceFirstBackoff = Duration.ZERO;
-            if (initial.equals(current)) {
+            if (!firstBackoffTimeSet) {
                 firstBackoffTime = now;
+                firstBackoffTimeSet = true;
             } else {
                 timeElapsedSinceFirstBackoff = Duration.between(firstBackoffTime, now);
             }
@@ -156,6 +159,8 @@ public class Backoff {
      */
     public void reset() {
         this.next = this.initial;
+        this.firstBackoffTime = Instant.EPOCH;
+        this.firstBackoffTimeSet = false;
         this.mandatoryStopMade = initial.isZero() && max.isZero() && mandatoryStop.isZero();
     }
 
diff --git a/pulsar-common/src/test/java/org/apache/pulsar/common/util/BackoffTest.java b/pulsar-common/src/test/java/org/apache/pulsar/common/util/BackoffTest.java
index 152ddee5156d..2a498441a8c9 100644
--- a/pulsar-common/src/test/java/org/apache/pulsar/common/util/BackoffTest.java
+++ b/pulsar-common/src/test/java/org/apache/pulsar/common/util/BackoffTest.java
@@ -76,6 +76,99 @@ public class BackoffTest {
         assertEquals(diffBackOffTime, 300);
     }
 
+    @Test
+    public void mandatoryStopShouldWorkWithConstantBackoff() {
+        Clock mockClock = Mockito.mock(Clock.class);
+        Mockito.when(mockClock.instant())
+                .thenReturn(Instant.ofEpochMilli(0))
+                .thenReturn(Instant.ofEpochMilli(400));
+
+        Backoff backoff = Backoff.builder()
+                .initialDelay(Duration.ofMillis(100))
+                .maxBackoff(Duration.ofMillis(100))
+                .mandatoryStop(Duration.ofMillis(300))
+                .clock(mockClock)
+                .build();
+
+        // first call starts the mandatory-stop timer
+        backoff.next();
+        Instant firstBackoffTime = backoff.getFirstBackoffTime();
+
+        // elapsed wall-clock time should exceed mandatory stop
+        backoff.next();
+        assertEquals(backoff.getFirstBackoffTime(), firstBackoffTime,
+                "firstBackoffTime should not be updated after the first call to next()");
+        assertTrue(backoff.isMandatoryStopMade(),
+                "mandatory stop should be reached even when initial == max (constant backoff)");
+    }
+
+    @Test
+    public void reduceToHalfShouldNotResetMandatoryStopTimer() {
+        Clock mockClock = Mockito.mock(Clock.class);
+        Mockito.when(mockClock.instant())
+                .thenReturn(Instant.ofEpochMilli(0))
+                .thenReturn(Instant.ofEpochMilli(200));
+
+        Backoff backoff = Backoff.builder()
+                .initialDelay(Duration.ofMillis(100))
+                .maxBackoff(Duration.ofMillis(400))
+                .mandatoryStop(Duration.ofMillis(250))
+                .clock(mockClock)
+                .build();
+
+        // first call starts the mandatory-stop timer (next becomes 200)
+        backoff.next();
+        Instant firstBackoffTime = backoff.getFirstBackoffTime();
+
+        // This can bring the next delay back to initial, but it should not reset firstBackoffTime.
+        backoff.reduceToHalf();
+
+        backoff.next();
+        assertEquals(backoff.getFirstBackoffTime(), firstBackoffTime,
+                "reduceToHalf should not reset firstBackoffTime");
+        assertTrue(backoff.isMandatoryStopMade(),
+                "mandatory stop should be reached based on wall-clock time since the first call to next()");
+    }
+
+    @Test
+    public void resetShouldStartNewMandatoryStopCycle() {
+        Clock mockClock = Mockito.mock(Clock.class);
+        Mockito.when(mockClock.instant())
+                .thenReturn(Instant.ofEpochMilli(0))
+                .thenReturn(Instant.ofEpochMilli(400))
+                .thenReturn(Instant.ofEpochMilli(1000))
+                .thenReturn(Instant.ofEpochMilli(1400));
+
+        Backoff backoff = Backoff.builder()
+                .initialDelay(Duration.ofMillis(100))
+                .maxBackoff(Duration.ofMillis(100))
+                .mandatoryStop(Duration.ofMillis(300))
+                .clock(mockClock)
+                .build();
+
+        // Cycle 1: reach mandatory stop
+        backoff.next();
+        Instant firstCycleStart = backoff.getFirstBackoffTime();
+        backoff.next();
+        assertTrue(backoff.isMandatoryStopMade(), "mandatory stop should be reached in cycle-1");
+
+        // Reset should clear mandatory-stop state so a new cycle can start.
+        backoff.reset();
+        assertFalse(backoff.isMandatoryStopMade(), "reset should clear mandatoryStopMade");
+        assertEquals(backoff.getFirstBackoffTime(), Instant.EPOCH, "reset should clear firstBackoffTime");
+
+        // Cycle 2: should start timing again and be able to reach mandatory stop again.
+        backoff.next();
+        Instant secondCycleStart = backoff.getFirstBackoffTime();
+        assertEquals(secondCycleStart, Instant.ofEpochMilli(1000),
+                "reset should start a new mandatory-stop timing window");
+        assertEquals(Duration.between(firstCycleStart, secondCycleStart).toMillis(), 1000,
+                "reset should not reuse the old timing window");
+
+        backoff.next();
+        assertTrue(backoff.isMandatoryStopMade(), "mandatory stop should be reached in cycle-2");
+    }
+
     @Test
     public void basicTest() {
         Clock mockClock = Clock.fixed(Instant.EPOCH, ZoneId.systemDefault());