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/09/03 18:00:44 UTC
(pulsar) branch master updated: [improve][broker] PIP-486: rebucket rollover and the segments-vs-buckets auto-scale policy (#26434)
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 94af75a5a75c [improve][broker] PIP-486: rebucket rollover and the segments-vs-buckets auto-scale policy (#26434)
94af75a5a75c is described below
commit 94af75a5a75ccdeb1c4f69e21df09e281673fca6
Author: Matteo Merli <mm...@apache.org>
AuthorDate: Thu Sep 3 11:00:36 2026 -0700
[improve][broker] PIP-486: rebucket rollover and the segments-vs-buckets auto-scale policy (#26434)
---
.../apache/pulsar/broker/ServiceConfiguration.java | 27 +++
.../pulsar/broker/admin/v2/ScalableTopics.java | 59 ++++++-
.../broker/service/scalable/AutoScaleConfig.java | 35 ++++
.../broker/service/scalable/AutoScaleDecision.java | 13 +-
.../service/scalable/AutoScalePolicyEvaluator.java | 149 +++++++++++++---
.../broker/service/scalable/EntryBucketSplits.java | 11 +-
.../service/scalable/ScalableTopicController.java | 160 +++++++++++++++--
.../service/scalable/ScalableTopicService.java | 11 ++
.../broker/service/scalable/SegmentLayout.java | 55 +++++-
.../service/scalable/SubscriptionCoordinator.java | 9 +-
.../service/scalable/AutoScaleConfigTest.java | 27 +++
.../scalable/AutoScalePolicyEvaluatorTest.java | 165 +++++++++++++++++-
.../service/scalable/EntryBucketSplitsTest.java | 32 ++++
.../ScalableTopicControllerAutoScaleTest.java | 149 +++++++++++++++-
.../broker/service/scalable/SegmentLayoutTest.java | 43 +++++
.../scalable/SubscriptionCoordinatorTest.java | 77 ++++++++-
.../pulsar/client/api/v5/V5AutoRebucketTest.java | 192 +++++++++++++++++++++
.../client/api/v5/V5SegmentRebucketTest.java | 164 ++++++++++++++++++
.../apache/pulsar/client/admin/ScalableTopics.java | 20 +++
.../policies/data/AutoScalePolicyOverride.java | 9 +
.../policies/data/ScalableTopicMetadata.java | 8 +
.../policies/data/ScalableTopicMetadataTest.java | 10 +-
.../client/admin/internal/ScalableTopicsImpl.java | 14 ++
23 files changed, 1378 insertions(+), 61 deletions(-)
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 ecf3ac940937..c6e098d10356 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
@@ -1468,6 +1468,15 @@ public class ServiceConfiguration implements PulsarConfiguration {
)
private int scalableTopicEntryBucketBudget = 4;
+ @FieldContext(
+ dynamic = true,
+ category = CATEGORY_POLICIES,
+ doc = "Hard ceiling on a single segment's entry-bucket count (PIP-486). Bounds both the "
+ + "manual rebucket operation and the controller's auto rebucket-up; a segment's "
+ + "bucket count caps how many consumers can share it."
+ )
+ private int scalableTopicEntryBucketMaxPerSegment = 1024;
+
@FieldContext(
dynamic = true,
category = CATEGORY_POLICIES,
@@ -1486,6 +1495,24 @@ public class ServiceConfiguration implements PulsarConfiguration {
)
private int scalableTopicSplitCooldownSeconds = 60;
+ @FieldContext(
+ dynamic = true,
+ category = CATEGORY_POLICIES,
+ doc = "PIP-486 segments-vs-buckets lever: on consumer-driven scale-up, split only if the "
+ + "busiest segment's inbound msg/s is at or above this floor; below it the "
+ + "controller grows the segment's entry-buckets instead (a low-throughput topic "
+ + "should not materialize physical segments just for consumer count)."
+ )
+ private double scalableTopicSplitVsRebucketMinMsgRateInThreshold = 1_000;
+
+ @FieldContext(
+ dynamic = true,
+ category = CATEGORY_POLICIES,
+ doc = "Minimum time (seconds) between automatic entry-bucket rollovers (rebuckets) on a "
+ + "topic. Coalesces consumer-join bursts, like the split cooldown."
+ )
+ private int scalableTopicRebucketCooldownSeconds = 60;
+
@FieldContext(
dynamic = true,
category = CATEGORY_POLICIES,
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/v2/ScalableTopics.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/v2/ScalableTopics.java
index ce253f6fdfb9..b08fdd835a13 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/v2/ScalableTopics.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/v2/ScalableTopics.java
@@ -193,6 +193,7 @@ public class ScalableTopics extends AdminResource {
ScalableTopicMetadata metadata = ScalableTopicController.createInitialMetadata(
numInitialSegments,
pulsar().getConfiguration().getScalableTopicEntryBucketBudget(),
+ pulsar().getConfiguration().getScalableTopicEntryBucketMaxPerSegment(),
props);
return resources().createScalableTopicAsync(tn, metadata)
.thenCompose(ignored -> createInitialSegmentTopicsAsync(tn, metadata));
@@ -337,7 +338,8 @@ public class ScalableTopics extends AdminResource {
}).thenCompose(partitions -> {
ScalableTopicMetadata metadata =
ScalableTopicController.createMigratedMetadata(persistentBase, partitions,
- pulsar().getConfiguration().getScalableTopicEntryBucketBudget());
+ pulsar().getConfiguration().getScalableTopicEntryBucketBudget(),
+ pulsar().getConfiguration().getScalableTopicEntryBucketMaxPerSegment());
return createMigratedChildTopicsAsync(scalableName, metadata)
.thenCompose(__ -> resources().createScalableTopicAsync(scalableName, metadata))
.thenCompose(__ -> terminateLegacyTopicsAsync(persistentBase, partitions));
@@ -935,6 +937,61 @@ public class ScalableTopics extends AdminResource {
});
}
+ @POST
+ @Path("/{tenant}/{namespace}/{topic}/rebucket/{segmentId}")
+ @Operation(summary = "Rebucket a segment: roll it over to a same-range successor with a new "
+ + "entry-bucket count.")
+ @ApiResponses(value = {
+ @ApiResponse(responseCode = "204", description = "Segment rebucketed successfully"),
+ @ApiResponse(responseCode = "404", description = "Scalable topic doesn't exist"),
+ @ApiResponse(responseCode = "412", description = "Segment is unknown, not active, "
+ + "or the bucket count is invalid or unchanged"),
+ @ApiResponse(responseCode = "500", description = "Internal server error")})
+ public void rebucketSegment(
+ @Suspended final AsyncResponse asyncResponse,
+ @Parameter(description = "Specify the tenant", required = true)
+ @PathParam("tenant") String tenant,
+ @Parameter(description = "Specify the namespace", required = true)
+ @PathParam("namespace") String namespace,
+ @Parameter(description = "Specify topic name", required = true)
+ @PathParam("topic") @Encoded String encodedTopic,
+ @Parameter(description = "Segment ID to rebucket", required = true)
+ @PathParam("segmentId") long segmentId,
+ @Parameter(description = "Entry-bucket count for the successor segment", required = true)
+ @QueryParam("bucketCount") int bucketCount) {
+ validateNamespaceName(tenant, namespace);
+ TopicName tn = TopicName.get(TopicDomain.topic.value(), namespaceName, encodedTopic);
+
+ validateSuperUserAccessAsync()
+ .thenCompose(__ -> onControllerLeader(tn,
+ svc -> svc.rebucketSegment(tn, segmentId, bucketCount)))
+ .thenAccept(__ -> {
+ log.info().attr("clientAppId", clientAppId())
+ .attr("segmentId", segmentId).attr("bucketCount", bucketCount)
+ .attr("topic", tn)
+ .log("Rebucketed segment of scalable topic");
+ asyncResponse.resume(Response.noContent().build());
+ })
+ .exceptionally(ex -> {
+ Throwable cause = FutureUtil.unwrapCompletionException(ex);
+ if (cause instanceof IllegalArgumentException) {
+ // Segment-level validation (unknown, sealed, bad or unchanged bucket
+ // count): a client error, not a server one.
+ log.info().attr("clientAppId", clientAppId())
+ .attr("segmentId", segmentId).attr("topic", tn)
+ .attr("reason", cause.getMessage()).log("Rebucket rejected");
+ asyncResponse.resume(new RestException(
+ Response.Status.PRECONDITION_FAILED, cause.getMessage()));
+ return null;
+ }
+ log.error().attr("clientAppId", clientAppId())
+ .attr("segmentId", segmentId).attr("topic", tn)
+ .exception(ex).log("Failed to rebucket segment");
+ resumeAsyncResponseExceptionally(asyncResponse, ex);
+ return null;
+ });
+ }
+
@POST
@Path("/{tenant}/{namespace}/{topic}/merge/{segmentId1}/{segmentId2}")
@Operation(summary = "Merge two adjacent segments into one.")
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/scalable/AutoScaleConfig.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/scalable/AutoScaleConfig.java
index 848b59cfa146..8efc6d25abb7 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/scalable/AutoScaleConfig.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/scalable/AutoScaleConfig.java
@@ -46,6 +46,10 @@ import org.apache.pulsar.common.policies.data.AutoScalePolicyOverride;
* @param mergeWindow how long a segment must continuously stay below every merge threshold
* before it becomes merge-eligible (measured from the load record's
* metadata-store last-modified time)
+ * @param rebucketCooldown minimum interval between automatic entry-bucket rollovers
+ * @param splitVsRebucketMinMsgRateIn consumer-driven scale-up splits only at/above this inbound
+ * msg/s on the busiest segment; below it, entry-buckets grow instead
+ * @param maxEntryBucketsPerSegment hard ceiling on a single segment's entry-bucket count
* @param splitMsgRateIn inbound msg/s above which a segment is split
* @param splitBytesRateIn inbound bytes/s above which a segment is split
* @param splitMsgRateOut outbound (dispatched) msg/s above which a segment is split
@@ -62,8 +66,11 @@ public record AutoScaleConfig(
int minSegments,
int maxDagDepth,
Duration splitCooldown,
+ Duration rebucketCooldown,
Duration mergeCooldown,
Duration mergeWindow,
+ double splitVsRebucketMinMsgRateIn,
+ int maxEntryBucketsPerSegment,
double splitMsgRateIn,
double splitBytesRateIn,
double splitMsgRateOut,
@@ -105,6 +112,17 @@ public record AutoScaleConfig(
return config.validated();
}
+ /**
+ * A disabled policy built from the broker configuration <b>without validation</b>: the
+ * fallback for an invalid resolved policy. Deliberately unvalidated — when the broker
+ * config itself violates an invariant, validating here would rethrow and fail every
+ * evaluation instead of disabling auto scaling as documented. Only {@code enabled} is
+ * consulted on the returned object.
+ */
+ static AutoScaleConfig disabledFallback(ServiceConfiguration conf) {
+ return brokerDefaults(conf).toBuilder().enabled(false).build();
+ }
+
private static AutoScaleConfig brokerDefaults(ServiceConfiguration conf) {
return AutoScaleConfig.builder()
.enabled(conf.isScalableTopicAutoScaleEnabled())
@@ -112,6 +130,10 @@ public record AutoScaleConfig(
.minSegments(conf.getScalableTopicMinSegments())
.maxDagDepth(conf.getScalableTopicMaxDagDepth())
.splitCooldown(Duration.ofSeconds(conf.getScalableTopicSplitCooldownSeconds()))
+ .rebucketCooldown(Duration.ofSeconds(conf.getScalableTopicRebucketCooldownSeconds()))
+ .splitVsRebucketMinMsgRateIn(
+ conf.getScalableTopicSplitVsRebucketMinMsgRateInThreshold())
+ .maxEntryBucketsPerSegment(conf.getScalableTopicEntryBucketMaxPerSegment())
.mergeCooldown(Duration.ofSeconds(conf.getScalableTopicMergeCooldownSeconds()))
.mergeWindow(Duration.ofSeconds(conf.getScalableTopicMergeWindowSeconds()))
.splitMsgRateIn(conf.getScalableTopicSplitMsgRateInThreshold())
@@ -145,6 +167,12 @@ public record AutoScaleConfig(
if (o.getSplitCooldownSeconds() != null) {
b.splitCooldown(Duration.ofSeconds(o.getSplitCooldownSeconds()));
}
+ if (o.getRebucketCooldownSeconds() != null) {
+ b.rebucketCooldown(Duration.ofSeconds(o.getRebucketCooldownSeconds()));
+ }
+ if (o.getSplitVsRebucketMinMsgRateInThreshold() != null) {
+ b.splitVsRebucketMinMsgRateIn(o.getSplitVsRebucketMinMsgRateInThreshold());
+ }
if (o.getMergeCooldownSeconds() != null) {
b.mergeCooldown(Duration.ofSeconds(o.getMergeCooldownSeconds()));
}
@@ -194,6 +222,7 @@ public record AutoScaleConfig(
check(maxSegments >= minSegments, "maxSegments must be >= minSegments");
check(maxDagDepth >= 0, "maxDagDepth must be >= 0");
check(!splitCooldown.isNegative(), "splitCooldown must not be negative");
+ check(!rebucketCooldown.isNegative(), "rebucketCooldown must not be negative");
check(!mergeCooldown.isNegative(), "mergeCooldown must not be negative");
check(!mergeWindow.isNegative(), "mergeWindow must not be negative");
check(splitMsgRateIn > 0, "splitMsgRateInThreshold must be > 0");
@@ -204,6 +233,12 @@ public record AutoScaleConfig(
check(mergeBytesRateIn >= 0, "mergeBytesRateInThreshold must be >= 0");
check(mergeMsgRateOut >= 0, "mergeMsgRateOutThreshold must be >= 0");
check(mergeBytesRateOut >= 0, "mergeBytesRateOutThreshold must be >= 0");
+ // Written as >= so a NaN (reachable via the JSON override) fails the check too.
+ check(splitVsRebucketMinMsgRateIn >= 0,
+ "splitVsRebucketMinMsgRateInThreshold must be >= 0");
+ check(maxEntryBucketsPerSegment >= 1 && maxEntryBucketsPerSegment
+ <= EntryBucketSplits.MAX_BUCKETS,
+ "maxEntryBucketsPerSegment must be in [1, " + EntryBucketSplits.MAX_BUCKETS + "]");
check(splitMsgRateIn > mergeMsgRateIn,
"splitMsgRateInThreshold must be > mergeMsgRateInThreshold (hysteresis)");
check(splitBytesRateIn > mergeBytesRateIn,
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/scalable/AutoScaleDecision.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/scalable/AutoScaleDecision.java
index e8a1713e1f06..9dd74afb16ff 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/scalable/AutoScaleDecision.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/scalable/AutoScaleDecision.java
@@ -24,7 +24,8 @@ package org.apache.pulsar.broker.service.scalable;
* carries a short {@code reason} string used for logging and metrics.
*/
public sealed interface AutoScaleDecision
- permits AutoScaleDecision.Split, AutoScaleDecision.Merge, AutoScaleDecision.NoAction {
+ permits AutoScaleDecision.Split, AutoScaleDecision.Merge, AutoScaleDecision.Rebucket,
+ AutoScaleDecision.NoAction {
/** Split {@code segmentId} at its midpoint. */
record Split(long segmentId, String reason) implements AutoScaleDecision {
@@ -34,6 +35,16 @@ public sealed interface AutoScaleDecision
record Merge(long segmentId1, long segmentId2, String reason) implements AutoScaleDecision {
}
+ /**
+ * Roll every segment in {@code segmentIds} over to a same-range successor with
+ * {@code newBucketCount} entry-buckets (PIP-486): consumer scale-up served by buckets
+ * instead of a split. One decision carries the whole batch so a multi-segment topic
+ * converges to a uniform bucketing in a single evaluation, not one segment per cooldown.
+ */
+ record Rebucket(java.util.List<Long> segmentIds, int newBucketCount, String reason)
+ implements AutoScaleDecision {
+ }
+
/** No action this evaluation. */
record NoAction() implements AutoScaleDecision {
}
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/scalable/AutoScalePolicyEvaluator.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/scalable/AutoScalePolicyEvaluator.java
index bcb48ffd6a93..04f728b379f0 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/scalable/AutoScalePolicyEvaluator.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/scalable/AutoScalePolicyEvaluator.java
@@ -37,7 +37,11 @@ import org.apache.pulsar.common.scalable.SegmentLoadStats;
* <li><b>Split</b> (fast, lightly coalesced by {@code splitCooldown}): consumer-count
* scale-up first, then traffic-driven scale-up.</li>
* <li><b>Merge</b> (lazy, gated by {@code mergeCooldown} + {@code mergeWindow} +
- * {@code maxDagDepth}): only if no split fired.</li>
+ * {@code maxDagDepth}): only if no split fired. A merge whose clamped bucket count
+ * ({@code maxEntryBucketsPerSegment}) would drop total consumer capacity below the
+ * parallelism live consumers currently get is skipped — merging must never idle a
+ * consumer that owns a bucket today, since the rebucket lane cannot grow past the
+ * ceiling to win the capacity back.</li>
* </ol>
*/
public final class AutoScalePolicyEvaluator {
@@ -68,7 +72,8 @@ public final class AutoScalePolicyEvaluator {
AutoScaleConfig config,
long nowMs,
long lastSplitAtMs,
- long lastMergeAtMs) {
+ long lastMergeAtMs,
+ long lastRebucketAtMs) {
if (!config.enabled()) {
return AutoScaleDecision.NONE;
@@ -76,13 +81,100 @@ public final class AutoScalePolicyEvaluator {
List<SegmentInfo> active = new ArrayList<>(layout.getActiveSegments().values());
- AutoScaleDecision split = trySplit(active, loadBySegment, streamConsumerCount,
- config, nowMs, lastSplitAtMs);
+ AutoScaleDecision consumerScale = tryConsumerScale(active, loadBySegment,
+ streamConsumerCount, config, nowMs, lastSplitAtMs, lastRebucketAtMs);
+ if (!(consumerScale instanceof AutoScaleDecision.NoAction)) {
+ return consumerScale;
+ }
+
+ AutoScaleDecision split = trySplit(active, loadBySegment, config, nowMs, lastSplitAtMs);
if (!(split instanceof AutoScaleDecision.NoAction)) {
return split;
}
- return tryMerge(active, layout, loadBySegment, config, nowMs, lastMergeAtMs);
+ return tryMerge(active, layout, loadBySegment, streamConsumerCount, config, nowMs,
+ lastMergeAtMs);
+ }
+
+ // --- Consumer-driven scale-up: segments vs entry-buckets (PIP-486) ---
+
+ /**
+ * Serve surplus consumers (a subscription with more consumers than active segments) by
+ * adding capacity on one of two axes:
+ * <ul>
+ * <li><b>Split</b> when traffic justifies a physical segment: the busiest segment's
+ * inbound rate is at or above {@code splitVsRebucketMinMsgRateIn} and the topic is
+ * under {@code maxSegments} — today's "segments first" behavior.</li>
+ * <li><b>Rebucket-up</b> otherwise (a low-throughput topic, or the topic is at the
+ * segment cap): if the existing entry-bucket capacity cannot absorb the surplus,
+ * roll the smallest-bucketed segment over to the smallest power of two that lets
+ * every consumer own a bucket, capped at {@code maxEntryBucketsPerSegment}.
+ * Raising is fast (one rollover sized to the surplus); lowering is deliberately
+ * not automated here — spiky consumer counts must not flap the bucketing.</li>
+ * </ul>
+ */
+ private static AutoScaleDecision tryConsumerScale(
+ List<SegmentInfo> active,
+ Map<Long, SegmentLoadSample> loadBySegment,
+ Map<String, Integer> streamConsumerCount,
+ AutoScaleConfig config,
+ long nowMs,
+ long lastSplitAtMs,
+ long lastRebucketAtMs) {
+
+ int consumers = streamConsumerCount.values().stream()
+ .mapToInt(Integer::intValue).max().orElse(0);
+ int segments = active.size();
+ if (consumers <= segments) {
+ return AutoScaleDecision.NONE;
+ }
+
+ SegmentInfo busiest = busiestByMsgRateIn(active, loadBySegment);
+ if (busiest == null) {
+ return AutoScaleDecision.NONE;
+ }
+ boolean atSegmentCap = segments >= config.maxSegments();
+ boolean belowSplitFloor = statsOf(busiest.segmentId(), loadBySegment).msgRateIn()
+ < config.splitVsRebucketMinMsgRateIn();
+
+ if (!atSegmentCap && !belowSplitFloor) {
+ // Traffic justifies a physical segment.
+ if (withinCooldown(nowMs, lastSplitAtMs, config.splitCooldown().toMillis())) {
+ return AutoScaleDecision.NONE;
+ }
+ return new AutoScaleDecision.Split(busiest.segmentId(), "consumer-count");
+ }
+
+ // Bucket lane: absorb the surplus with entry-buckets.
+ long capacity = 0;
+ for (SegmentInfo segment : active) {
+ capacity += segment.bucketCount();
+ }
+ if (consumers <= capacity) {
+ // The existing buckets already absorb the surplus (broker-side fan-out).
+ return AutoScaleDecision.NONE;
+ }
+ if (withinCooldown(nowMs, lastRebucketAtMs, config.rebucketCooldown().toMillis())) {
+ return AutoScaleDecision.NONE;
+ }
+ // One shot: bring every segment below the common per-segment target up to it in a
+ // single decision, so the topic converges to a uniform bucketing in one evaluation —
+ // never one segment per cooldown, and no arrival-history-dependent skew.
+ int target = Math.min(nextPowerOfTwo(ceilDiv(consumers, segments)),
+ config.maxEntryBucketsPerSegment());
+ List<Long> below = new ArrayList<>();
+ for (SegmentInfo segment : active) {
+ if (segment.bucketCount() < target) {
+ below.add(segment.segmentId());
+ }
+ }
+ if (below.isEmpty()) {
+ // Bucket capacity is maxed out; the remaining surplus stays idle.
+ return AutoScaleDecision.NONE;
+ }
+ below.sort(Long::compareTo);
+ return new AutoScaleDecision.Rebucket(below, target,
+ atSegmentCap ? "at-max-segments" : "below-split-rate-floor");
}
// --- Split pass ---
@@ -90,7 +182,6 @@ public final class AutoScalePolicyEvaluator {
private static AutoScaleDecision trySplit(
List<SegmentInfo> active,
Map<Long, SegmentLoadSample> loadBySegment,
- Map<String, Integer> streamConsumerCount,
AutoScaleConfig config,
long nowMs,
long lastSplitAtMs) {
@@ -102,20 +193,7 @@ public final class AutoScalePolicyEvaluator {
return AutoScaleDecision.NONE;
}
- // (a) Consumer-driven: per-subscription max. If any managed subscription has more
- // consumers than there are active segments, add a segment so the 1:1 assignment can
- // give the extra consumer its own segment. Split the busiest segment by msgRateIn so
- // the new pair lands where it relieves the most ingest.
- int requiredConsumers = streamConsumerCount.values().stream()
- .mapToInt(Integer::intValue).max().orElse(0);
- if (requiredConsumers > active.size()) {
- SegmentInfo target = busiestByMsgRateIn(active, loadBySegment);
- if (target != null) {
- return new AutoScaleDecision.Split(target.segmentId(), "consumer-count");
- }
- }
-
- // (b) Load-driven: split the segment with the highest overload score among those over
+ // Load-driven: split the segment with the highest overload score among those over
// at least one split threshold.
SegmentInfo hottest = null;
double hottestScore = 1.0; // strictly over threshold means a per-metric ratio > 1.0
@@ -156,6 +234,7 @@ public final class AutoScalePolicyEvaluator {
List<SegmentInfo> active,
SegmentLayout layout,
Map<Long, SegmentLoadSample> loadBySegment,
+ Map<String, Integer> streamConsumerCount,
AutoScaleConfig config,
long nowMs,
long lastMergeAtMs) {
@@ -169,6 +248,20 @@ public final class AutoScalePolicyEvaluator {
long mergeWindowMs = config.mergeWindow().toMillis();
+ // A merged segment's bucket count is the clamped sum of the pair's (the same clamp
+ // mergeSegments applies), so an at-ceiling merge shrinks total consumer capacity —
+ // and the rebucket lane cannot grow past the ceiling to recover it. Skip any pair
+ // whose merge would leave less capacity than the parallelism consumers get today:
+ // min(consumers, capacity), so an already over-subscribed topic can still take a
+ // capacity-preserving merge, and an idle one can always consolidate.
+ int consumers = streamConsumerCount.values().stream()
+ .mapToInt(Integer::intValue).max().orElse(0);
+ long totalCapacity = 0;
+ for (SegmentInfo segment : active) {
+ totalCapacity += segment.bucketCount();
+ }
+ long usedParallelism = Math.min(consumers, totalCapacity);
+
AutoScaleDecision.Merge coldest = null;
double coldestCombined = Double.MAX_VALUE;
for (int i = 0; i < active.size(); i++) {
@@ -182,6 +275,11 @@ public final class AutoScalePolicyEvaluator {
|| layout.mergeDepth(b.segmentId()) >= config.maxDagDepth()) {
continue;
}
+ long pairCapacity = (long) a.bucketCount() + b.bucketCount();
+ long mergedCapacity = Math.min(pairCapacity, config.maxEntryBucketsPerSegment());
+ if (totalCapacity - pairCapacity + mergedCapacity < usedParallelism) {
+ continue;
+ }
if (!coldEnough(a.segmentId(), loadBySegment, config, nowMs, mergeWindowMs)
|| !coldEnough(b.segmentId(), loadBySegment, config, nowMs, mergeWindowMs)) {
continue;
@@ -239,6 +337,17 @@ public final class AutoScalePolicyEvaluator {
return s.msgRateIn() + s.bytesRateIn() + s.msgRateOut() + s.bytesRateOut();
}
+ /** Ceiling integer division for positive operands. */
+ private static int ceilDiv(int a, int b) {
+ return (a + b - 1) / b;
+ }
+
+ /** The smallest power of two {@code >= v} (for {@code v >= 1}). */
+ private static int nextPowerOfTwo(int v) {
+ int highest = Integer.highestOneBit(v);
+ return highest == v ? v : highest << 1;
+ }
+
private static SegmentInfo busiestByMsgRateIn(List<SegmentInfo> active,
Map<Long, SegmentLoadSample> load) {
SegmentInfo best = null;
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/scalable/EntryBucketSplits.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/scalable/EntryBucketSplits.java
index 57a6461119e6..64d6da7dd1b9 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/scalable/EntryBucketSplits.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/scalable/EntryBucketSplits.java
@@ -38,6 +38,14 @@ import org.apache.pulsar.common.scalable.HashRange;
*/
final class EntryBucketSplits {
+ /**
+ * Absolute ceiling on a segment's entry-bucket count: one bucket per hash on the 16-bit
+ * ring. Beyond it {@link #equalWidth} would produce duplicate split points, whose
+ * zero-width ranges fail {@code HashRange} construction — at assignment time, after the
+ * layout was already persisted.
+ */
+ static final int MAX_BUCKETS = HashRange.MAX_HASH + 1;
+
private EntryBucketSplits() {
}
@@ -46,7 +54,7 @@ final class EntryBucketSplits {
* {@code floor(budget / segmentCount)}, but at least 1.
*/
static int bucketsForBudget(int budget, int segmentCount) {
- return Math.max(1, budget / segmentCount);
+ return Math.min(Math.max(1, budget / segmentCount), MAX_BUCKETS);
}
/**
@@ -70,6 +78,7 @@ final class EntryBucketSplits {
/** Equal-width split points for {@code bucketCount} buckets; empty when {@code bucketCount <= 1}. */
static List<Integer> equalWidth(int bucketCount) {
+ bucketCount = Math.min(bucketCount, MAX_BUCKETS);
if (bucketCount <= 1) {
return List.of();
}
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/scalable/ScalableTopicController.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/scalable/ScalableTopicController.java
index a8a599fff831..bc69c3df4b29 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/scalable/ScalableTopicController.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/scalable/ScalableTopicController.java
@@ -108,6 +108,7 @@ public class ScalableTopicController {
private volatile long lastSplitAtMs = Long.MIN_VALUE;
/** Epoch millis of the last merge on this topic (manual or auto); MIN_VALUE if none. */
private volatile long lastMergeAtMs = Long.MIN_VALUE;
+ private volatile long lastRebucketAtMs = Long.MIN_VALUE;
@Getter
private volatile LeaderElectionState leaderState = LeaderElectionState.NoLeader;
@@ -197,26 +198,35 @@ public class ScalableTopicController {
}
/**
- * Recover the auto split/merge cooldown clocks after winning leadership. The timestamps
- * are in-memory only, but the layout itself records when each segment was created — a
- * split's children have exactly one parent, a merge's child has two — so the most recent
- * creation time of each class is exactly when the last split / merge happened. Without
- * this, every leader failover would reset both cooldowns and e.g. allow an auto merge
- * seconds after one just ran on the previous leader.
+ * Recover the auto split/merge/rebucket cooldown clocks after winning leadership. The
+ * timestamps are in-memory only, but the layout itself records when each segment was
+ * created — a merge's child has two parents, and a single-parent child is a split child
+ * (strictly narrower hash range than its parent) or a rebucket successor (the same hash
+ * range as its parent) — so the most recent creation time of each class is exactly when
+ * the last operation of that kind happened. Without this, every leader failover would
+ * reset the cooldowns and e.g. allow an auto merge or rollover seconds after one just
+ * ran on the previous leader.
*/
private void seedAutoScaleCooldownsFromLayout() {
long split = Long.MIN_VALUE;
long merge = Long.MIN_VALUE;
+ long rebucket = Long.MIN_VALUE;
for (SegmentInfo segment : currentLayout.getAllSegments().values()) {
int parents = segment.parentIds().size();
if (parents == 1) {
- split = Math.max(split, segment.createdAtMs());
+ SegmentInfo parent = currentLayout.getAllSegments().get(segment.parentIds().get(0));
+ if (parent != null && parent.hashRange().equals(segment.hashRange())) {
+ rebucket = Math.max(rebucket, segment.createdAtMs());
+ } else {
+ split = Math.max(split, segment.createdAtMs());
+ }
} else if (parents >= 2) {
merge = Math.max(merge, segment.createdAtMs());
}
}
lastSplitAtMs = split;
lastMergeAtMs = merge;
+ lastRebucketAtMs = rebucket;
}
/**
@@ -378,7 +388,7 @@ public class ScalableTopicController {
.thenCombine(collectLoadSamples(), (consumers, load) ->
AutoScalePolicyEvaluator.decide(currentLayout, load,
consumers, config, clock.millis(),
- lastSplitAtMs, lastMergeAtMs))
+ lastSplitAtMs, lastMergeAtMs, lastRebucketAtMs))
.thenCompose(decision -> dispatch(decision, config, trigger));
})
.whenComplete((__, ex) -> {
@@ -430,8 +440,11 @@ public class ScalableTopicController {
.log("Resolved auto split/merge policy is invalid; treating auto "
+ "split/merge as disabled for this topic until the namespace "
+ "or topic override is fixed");
- return AutoScaleConfig.fromBrokerConfig(brokerConfig)
- .toBuilder().enabled(false).build();
+ // Built from the UNVALIDATED broker defaults: if the broker config itself is
+ // the invalid part, re-validating here would just rethrow on every tick
+ // instead of the documented "treated as disabled". Only `enabled` is ever
+ // consulted on this object.
+ return AutoScaleConfig.disabledFallback(brokerConfig);
}
});
}
@@ -447,6 +460,28 @@ public class ScalableTopicController {
return null;
});
}
+ if (decision instanceof AutoScaleDecision.Rebucket rebucket) {
+ log.info().attr("segmentIds", rebucket.segmentIds())
+ .attr("bucketCount", rebucket.newBucketCount()).attr("reason", rebucket.reason())
+ .attr("trigger", trigger).log("Auto rebucket");
+ // Roll the whole batch sequentially (each rollover is its own seal → successor →
+ // CAS → notify). A mid-batch failure aborts the rest; the follow-up evaluation —
+ // scheduled from whenComplete so it survives that failure — retries the remainder
+ // once the rebucket cooldown expires.
+ CompletableFuture<Void> chain = CompletableFuture.completedFuture(null);
+ for (long segmentId : rebucket.segmentIds()) {
+ chain = chain.thenCompose(__ ->
+ rebucketSegment(segmentId, rebucket.newBucketCount()))
+ .thenApply(__ -> null);
+ }
+ return chain.whenComplete((__, ___) ->
+ // Like post-split: a consumer burst may need another rollover once the
+ // cooldown expires (e.g. when the target was clamped by the per-segment
+ // bucket ceiling); the chain stops at the first NoAction. Delayed by the
+ // REBUCKET cooldown — the two cooldowns are configured independently.
+ scheduleFollowUpEvaluation(config.rebucketCooldown().toMillis() + 1,
+ "post-rebucket"));
+ }
if (decision instanceof AutoScaleDecision.Merge merge) {
log.info().attr("segmentId1", merge.segmentId1()).attr("segmentId2", merge.segmentId2())
.attr("reason", merge.reason()).attr("trigger", trigger).log("Auto merge");
@@ -463,11 +498,14 @@ public class ScalableTopicController {
* stops naturally at the first evaluation that decides {@code NoAction}.
*/
private void scheduleFollowUpEvaluation(AutoScaleConfig config) {
+ scheduleFollowUpEvaluation(config.splitCooldown().toMillis() + 1, "post-split");
+ }
+
+ private void scheduleFollowUpEvaluation(long delayMs, String trigger) {
if (closed || !isLeader()) {
return;
}
- long delayMs = config.splitCooldown().toMillis() + 1;
- scheduler().schedule(() -> runAutoScaleSafely("post-split"),
+ scheduler().schedule(() -> runAutoScaleSafely(trigger),
delayMs, TimeUnit.MILLISECONDS);
}
@@ -714,6 +752,64 @@ public class ScalableTopicController {
}).thenApply(__ -> currentLayout);
}
+ /**
+ * Rebucket an active segment (PIP-486 rollover): seal it and roll over to a single
+ * <b>same-range</b> successor with {@code newBucketCount} entry-buckets. A segment's
+ * bucketing is immutable for its life, so changing it rides the ordinary seal →
+ * successor flow — producers redirect through the standard segment-gone retry and
+ * per-key order is preserved by the existing machinery.
+ *
+ * <p>Same ordering invariant as split: the successor topic and subscription cursors are
+ * created before the parent is terminated, and the metadata CAS lands last.
+ */
+ public CompletableFuture<SegmentLayout> rebucketSegment(long segmentId, int newBucketCount) {
+ checkLeader();
+ int maxBuckets = maxEntryBucketsPerSegment();
+ if (newBucketCount < 1 || newBucketCount > maxBuckets) {
+ return CompletableFuture.failedFuture(new IllegalArgumentException(
+ "bucketCount must be in [1, " + maxBuckets + "]: " + newBucketCount));
+ }
+ final long nowMs = clock.millis();
+ final List<Integer> newSplits = EntryBucketSplits.equalWidth(newBucketCount);
+
+ // Compute the new layout locally to derive the successor's info (this also validates:
+ // segment exists, is active, and the splits actually change). Argument failures come
+ // back through the returned future, never as a synchronous throw.
+ SegmentLayout newLayout;
+ try {
+ newLayout = currentLayout.rebucketSegment(segmentId, newSplits, nowMs);
+ } catch (IllegalArgumentException e) {
+ return CompletableFuture.failedFuture(e);
+ }
+ SegmentInfo successor = newLayout.getAllSegments().get(newLayout.getNextSegmentId() - 1);
+ SegmentInfo parent = currentLayout.getAllSegments().get(segmentId);
+ String parentTopicName = toSegmentPersistentName(parent);
+
+ return resources.listSubscriptionsAsync(topicName)
+ .thenCompose(parentSubs ->
+ createSegmentTopic(successor, new java.util.ArrayList<>(parentSubs)))
+ .thenCompose(__ -> terminateSegmentTopic(parentTopicName))
+ .thenCompose(__ -> resources.updateScalableTopicAsync(topicName, md -> {
+ SegmentLayout latest = SegmentLayout.fromMetadata(md);
+ SegmentLayout updated = latest.rebucketSegment(segmentId, newSplits, nowMs);
+ return updated.toMetadata(md);
+ }))
+ .thenCompose(__ -> resources.getScalableTopicMetadataAsync(topicName, true))
+ .thenCompose(optMd -> {
+ currentLayout = SegmentLayout.fromMetadata(optMd.orElseThrow());
+ // Start the rebucket cooldown only once the rollover actually happened
+ // (a failed attempt doesn't burn the cooldown).
+ lastRebucketAtMs = nowMs;
+ return notifySubscriptions(currentLayout);
+ }).thenApply(__ -> currentLayout);
+ }
+
+ private int maxEntryBucketsPerSegment() {
+ // Defensive: PulsarService.getConfig() is null in some unit-test mocks.
+ var config = brokerService.getPulsar().getConfig();
+ return config != null ? config.getScalableTopicEntryBucketMaxPerSegment() : 1024;
+ }
+
/**
* Merge two adjacent active segments.
*
@@ -728,7 +824,8 @@ public class ScalableTopicController {
final long nowMs = clock.millis();
// Compute the new layout locally to derive merged segment info
- SegmentLayout newLayout = currentLayout.mergeSegments(segmentId1, segmentId2, nowMs);
+ SegmentLayout newLayout = currentLayout.mergeSegments(segmentId1, segmentId2, nowMs,
+ maxEntryBucketsPerSegment());
SegmentInfo merged = newLayout.getAllSegments().get(newLayout.getNextSegmentId() - 1);
SegmentInfo parent1 = currentLayout.getAllSegments().get(segmentId1);
SegmentInfo parent2 = currentLayout.getAllSegments().get(segmentId2);
@@ -748,7 +845,8 @@ public class ScalableTopicController {
// Step 3: Atomic metadata update (only after topic + cursors are ready + parents terminated)
.thenCompose(__ -> resources.updateScalableTopicAsync(topicName, md -> {
SegmentLayout latest = SegmentLayout.fromMetadata(md);
- SegmentLayout updated = latest.mergeSegments(segmentId1, segmentId2, nowMs);
+ SegmentLayout updated = latest.mergeSegments(segmentId1, segmentId2, nowMs,
+ maxEntryBucketsPerSegment());
return updated.toMetadata(md);
}))
.thenCompose(__ -> resources.getScalableTopicMetadataAsync(topicName, true))
@@ -1440,6 +1538,19 @@ public class ScalableTopicController {
public static ScalableTopicMetadata createInitialMetadata(int numInitialSegments,
int entryBucketBudget,
Map<String, String> properties) {
+ return createInitialMetadata(numInitialSegments, entryBucketBudget,
+ EntryBucketSplits.MAX_BUCKETS, properties);
+ }
+
+ /**
+ * As {@link #createInitialMetadata(int, int, Map)}, clamping each initial segment's
+ * budget-derived entry-bucket count to {@code maxBucketsPerSegment} (the configured
+ * per-segment ceiling — the budget is a dynamic setting and must not exceed it).
+ */
+ public static ScalableTopicMetadata createInitialMetadata(int numInitialSegments,
+ int entryBucketBudget,
+ int maxBucketsPerSegment,
+ Map<String, String> properties) {
if (numInitialSegments < 1) {
throw new IllegalArgumentException("Must have at least 1 segment");
}
@@ -1449,7 +1560,8 @@ public class ScalableTopicController {
// PIP-486: share the topic's entry-bucket budget equally across the initial segments.
List<Integer> entryBucketSplits = EntryBucketSplits.equalWidth(
- EntryBucketSplits.bucketsForBudget(entryBucketBudget, numInitialSegments));
+ Math.min(EntryBucketSplits.bucketsForBudget(entryBucketBudget, numInitialSegments),
+ maxBucketsPerSegment));
long nowMs = System.currentTimeMillis();
for (int i = 0; i < numInitialSegments; i++) {
@@ -1494,6 +1606,21 @@ public class ScalableTopicController {
public static ScalableTopicMetadata createMigratedMetadata(TopicName persistentBase,
int partitions,
int entryBucketBudget) {
+ return createMigratedMetadata(persistentBase, partitions, entryBucketBudget,
+ EntryBucketSplits.MAX_BUCKETS);
+ }
+
+ /**
+ * As {@link #createMigratedMetadata(TopicName, int, int)}, clamping each child's
+ * budget-derived entry-bucket count to {@code maxBucketsPerSegment} (the configured
+ * per-segment ceiling — the migration path must honour it like creation and merge do,
+ * since the evaluator only ever grows a segment's buckets and would never correct an
+ * over-ceiling migration).
+ */
+ public static ScalableTopicMetadata createMigratedMetadata(TopicName persistentBase,
+ int partitions,
+ int entryBucketBudget,
+ int maxBucketsPerSegment) {
int n = Math.max(partitions, 1);
long nowMs = System.currentTimeMillis();
Map<Long, SegmentInfo> segments = new LinkedHashMap<>();
@@ -1501,7 +1628,8 @@ public class ScalableTopicController {
// PIP-486: the active children share the topic's entry-bucket budget. The sealed legacy parents
// take no new writes, so they keep a single bucket (no splits).
List<Integer> childEntryBucketSplits = EntryBucketSplits.equalWidth(
- EntryBucketSplits.bucketsForBudget(entryBucketBudget, n));
+ Math.min(EntryBucketSplits.bucketsForBudget(entryBucketBudget, n),
+ maxBucketsPerSegment));
// Child IDs are N..2N-1; every child lists every parent (full fan-in).
List<Long> childIds = new ArrayList<>(n);
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/scalable/ScalableTopicService.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/scalable/ScalableTopicService.java
index e53364f00163..1e573914858f 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/scalable/ScalableTopicService.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/scalable/ScalableTopicService.java
@@ -146,6 +146,7 @@ public class ScalableTopicService {
ScalableTopicMetadata metadata = ScalableTopicController.createInitialMetadata(
numInitialSegments,
brokerService.getPulsar().getConfiguration().getScalableTopicEntryBucketBudget(),
+ brokerService.getPulsar().getConfiguration().getScalableTopicEntryBucketMaxPerSegment(),
properties);
// Write the scalable metadata FIRST, then materialize the underlying segment topics.
@@ -180,6 +181,16 @@ public class ScalableTopicService {
.thenApply(__ -> null);
}
+ /**
+ * Rebucket a segment (delegates to controller). Same leader contract as
+ * {@link #splitSegment(TopicName, long)}.
+ */
+ public CompletableFuture<Void> rebucketSegment(TopicName topic, long segmentId, int bucketCount) {
+ return getOrCreateController(topic)
+ .thenCompose(controller -> controller.rebucketSegment(segmentId, bucketCount))
+ .thenApply(__ -> null);
+ }
+
/**
* Merge two adjacent segments (delegates to controller). Same leader contract as
* {@link #splitSegment(TopicName, long)}.
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/scalable/SegmentLayout.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/scalable/SegmentLayout.java
index 9618ac5df4e9..6f62047314e9 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/scalable/SegmentLayout.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/scalable/SegmentLayout.java
@@ -204,6 +204,16 @@ public class SegmentLayout {
* @return a new SegmentLayout with the merge applied
*/
public SegmentLayout mergeSegments(long segmentId1, long segmentId2, long nowMs) {
+ return mergeSegments(segmentId1, segmentId2, nowMs, EntryBucketSplits.MAX_BUCKETS);
+ }
+
+ /**
+ * As {@link #mergeSegments(long, long, long)}, clamping the merged segment's entry-bucket
+ * count to {@code maxBucketsPerSegment} (the configured per-segment ceiling): the merged
+ * segment recovers the parents' buckets, but never past the hard ceiling.
+ */
+ public SegmentLayout mergeSegments(long segmentId1, long segmentId2, long nowMs,
+ int maxBucketsPerSegment) {
SegmentInfo seg1 = allSegments.get(segmentId1);
SegmentInfo seg2 = allSegments.get(segmentId2);
if (seg1 == null || seg2 == null) {
@@ -223,8 +233,8 @@ public class SegmentLayout {
// PIP-486: a merge is the inverse of a split — the merged segment recovers both parents' buckets
// (N1 + N2), so the topic's total entry-bucket count stays ≈ the budget as segments coalesce.
- List<Integer> mergedEntryBucketSplits =
- EntryBucketSplits.equalWidth(seg1.bucketCount() + seg2.bucketCount());
+ List<Integer> mergedEntryBucketSplits = EntryBucketSplits.equalWidth(
+ Math.min(seg1.bucketCount() + seg2.bucketCount(), maxBucketsPerSegment));
SegmentInfo sealed1 = seg1.sealed(newEpoch, nowMs, List.of(mergedId));
SegmentInfo sealed2 = seg2.sealed(newEpoch, nowMs, List.of(mergedId));
SegmentInfo merged = SegmentInfo.active(mergedId, mergedRange,
@@ -239,6 +249,47 @@ public class SegmentLayout {
return new SegmentLayout(newEpoch, nextSegmentId + 1, newSegments);
}
+ /**
+ * Produce a new layout by rebucketing a segment: seal it and create a single successor
+ * with the <b>same hash range</b> but a new entry-bucket boundary list (PIP-486 "rebucket
+ * rollover"). A segment's bucketing is immutable for its life, so changing N is a layout
+ * operation: the sealed predecessor drains under its old buckets while the successor takes
+ * new writes under the new ones — the ordinary seal → successor flow, so per-key order
+ * across the change is preserved by the existing machinery.
+ *
+ * @param segmentId the active segment to rebucket
+ * @param newSplits the successor's entry-bucket split points (ascending start hashes of
+ * buckets {@code 1..N-1}; empty = a single bucket spanning the ring)
+ * @param nowMs wall-clock millis used as the parent's seal time and the successor's
+ * create time
+ * @return a new SegmentLayout with the rollover applied
+ */
+ public SegmentLayout rebucketSegment(long segmentId, List<Integer> newSplits, long nowMs) {
+ SegmentInfo segment = allSegments.get(segmentId);
+ if (segment == null) {
+ throw new IllegalArgumentException("Segment not found: " + segmentId);
+ }
+ if (!segment.isActive()) {
+ throw new IllegalArgumentException("Cannot rebucket non-active segment: " + segmentId);
+ }
+ if (newSplits.equals(segment.entryBucketSplits())) {
+ throw new IllegalArgumentException(
+ "Segment " + segmentId + " already has the requested entry-bucket splits");
+ }
+
+ long newEpoch = epoch + 1;
+ long successorId = nextSegmentId;
+ SegmentInfo sealedParent = segment.sealed(newEpoch, nowMs, List.of(successorId));
+ SegmentInfo successor = SegmentInfo.active(successorId, segment.hashRange(),
+ List.of(segmentId), newEpoch, nowMs).withEntryBucketSplits(newSplits);
+
+ Map<Long, SegmentInfo> newSegments = new LinkedHashMap<>(allSegments);
+ newSegments.put(segmentId, sealedParent);
+ newSegments.put(successorId, successor);
+
+ return new SegmentLayout(newEpoch, nextSegmentId + 1, newSegments);
+ }
+
/**
* Prune an expired segment from the DAG. The segment must be sealed and have no
* children that are still in the DAG (i.e., children have already been pruned or
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/scalable/SubscriptionCoordinator.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/scalable/SubscriptionCoordinator.java
index 8166e9a2d0b1..02f2562a3ce0 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/scalable/SubscriptionCoordinator.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/service/scalable/SubscriptionCoordinator.java
@@ -374,9 +374,16 @@ public class SubscriptionCoordinator {
* as assignable.
*/
private boolean isAssignable(SegmentInfo segment, SegmentLayout layout) {
- if (drainChecker == null || !segment.isActive()) {
+ if (drainChecker == null) {
return true;
}
+ if (!segment.isActive()) {
+ // A sealed segment is assignable only while it still has backlog to drain. Once
+ // fully drained it carries no traffic, and keeping it assignable would pin
+ // consumers to a dead segment forever (the drain rebalance would spread the
+ // group across it and its successor).
+ return !drainedSegmentIds.contains(segment.segmentId());
+ }
for (long parentId : segment.parentIds()) {
// A parent that's no longer in the DAG has been pruned (its data is gone), so
// treat it as drained — there's nothing to wait on.
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/AutoScaleConfigTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/AutoScaleConfigTest.java
index 7a991834461e..44665d94576a 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/AutoScaleConfigTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/AutoScaleConfigTest.java
@@ -129,6 +129,33 @@ public class AutoScaleConfigTest {
negativeCooldown.setScalableTopicSplitCooldownSeconds(-1);
assertThrows(IllegalArgumentException.class,
() -> AutoScaleConfig.fromBrokerConfig(negativeCooldown));
+
+ // Negative rebucket cooldown: would silently disable the rollover throttle.
+ ServiceConfiguration negativeRebucket = new ServiceConfiguration();
+ negativeRebucket.setScalableTopicRebucketCooldownSeconds(-1);
+ assertThrows(IllegalArgumentException.class,
+ () -> AutoScaleConfig.fromBrokerConfig(negativeRebucket));
+
+ // Negative or NaN split-vs-rebucket floor: breaks lane selection.
+ ServiceConfiguration negativeFloor = new ServiceConfiguration();
+ negativeFloor.setScalableTopicSplitVsRebucketMinMsgRateInThreshold(-1);
+ assertThrows(IllegalArgumentException.class,
+ () -> AutoScaleConfig.fromBrokerConfig(negativeFloor));
+ ServiceConfiguration nanFloor = new ServiceConfiguration();
+ nanFloor.setScalableTopicSplitVsRebucketMinMsgRateInThreshold(Double.NaN);
+ assertThrows(IllegalArgumentException.class,
+ () -> AutoScaleConfig.fromBrokerConfig(nanFloor));
+
+ // Bucket ceiling outside [1, ring size]: 0 rejects every rebucket, beyond the 16-bit
+ // ring the split points would collide.
+ ServiceConfiguration zeroCeiling = new ServiceConfiguration();
+ zeroCeiling.setScalableTopicEntryBucketMaxPerSegment(0);
+ assertThrows(IllegalArgumentException.class,
+ () -> AutoScaleConfig.fromBrokerConfig(zeroCeiling));
+ ServiceConfiguration hugeCeiling = new ServiceConfiguration();
+ hugeCeiling.setScalableTopicEntryBucketMaxPerSegment(1 << 20);
+ assertThrows(IllegalArgumentException.class,
+ () -> AutoScaleConfig.fromBrokerConfig(hugeCeiling));
}
@Test
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/AutoScalePolicyEvaluatorTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/AutoScalePolicyEvaluatorTest.java
index e44204116070..350e6b77da37 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/AutoScalePolicyEvaluatorTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/AutoScalePolicyEvaluatorTest.java
@@ -54,8 +54,11 @@ public class AutoScalePolicyEvaluatorTest {
.minSegments(1)
.maxDagDepth(10)
.splitCooldown(Duration.ofMinutes(1))
+ .rebucketCooldown(Duration.ofMinutes(1))
.mergeCooldown(Duration.ofMinutes(5))
.mergeWindow(Duration.ofMinutes(5))
+ .splitVsRebucketMinMsgRateIn(1_000)
+ .maxEntryBucketsPerSegment(1024)
.splitMsgRateIn(SPLIT_MSG_IN)
.splitBytesRateIn(SPLIT_BYTES_IN)
.splitMsgRateOut(SPLIT_MSG_OUT)
@@ -91,7 +94,7 @@ public class AutoScalePolicyEvaluatorTest {
Map<String, Integer> consumers,
AutoScaleConfig config) {
return AutoScalePolicyEvaluator.decide(layout, load, consumers, config, NOW,
- NO_PRIOR, NO_PRIOR);
+ NO_PRIOR, NO_PRIOR, NO_PRIOR);
}
// --- enable switch ---
@@ -110,9 +113,10 @@ public class AutoScalePolicyEvaluatorTest {
@Test
public void testConsumerDrivenSplitTargetsBusiestSegment() {
SegmentLayout layout = initialLayout(2);
+ // Above the split-vs-rebucket floor (1k msg/s): traffic justifies a physical segment.
Map<Long, SegmentLoadSample> load = Map.of(
- 0L, sample(100, 0, 0, 0, old()),
- 1L, sample(200, 0, 0, 0, old()));
+ 0L, sample(1_500, 0, 0, 0, old()),
+ 1L, sample(2_000, 0, 0, 0, old()));
// One subscription with 3 consumers but only 2 segments → need a 3rd segment.
AutoScaleDecision d = decide(layout, load, Map.of("sub", 3), baseConfig().build());
assertTrue(d instanceof AutoScaleDecision.Split, d.toString());
@@ -134,25 +138,126 @@ public class AutoScalePolicyEvaluatorTest {
}
@Test
- public void testConsumerDrivenSplitRespectsMaxSegments() {
+ public void testSurplusAtMaxSegmentsRebuckets() {
+ // UC#3: at the segment cap the surplus is served by entry-buckets, never a split.
+ // 2 segments × 2 buckets (budget 4) = capacity 4 < 5 consumers → grow the smallest
+ // segment to ceil(5/2)=3 rounded up to the power of two, 4.
SegmentLayout layout = initialLayout(2);
- // Fresh samples so the merge pass can't fire — isolates the split suppression.
Map<Long, SegmentLoadSample> load = Map.of(0L, cold(0), 1L, cold(0));
AutoScaleDecision d = decide(layout, load, Map.of("sub", 5),
baseConfig().maxSegments(2).build());
- assertTrue(d instanceof AutoScaleDecision.NoAction, "at maxSegments, no split");
+ assertTrue(d instanceof AutoScaleDecision.Rebucket, d.toString());
+ AutoScaleDecision.Rebucket r = (AutoScaleDecision.Rebucket) d;
+ assertEquals(r.segmentIds(), List.of(0L, 1L),
+ "both below-target segments roll in the one decision");
+ assertEquals(r.newBucketCount(), 4);
+ assertEquals(r.reason(), "at-max-segments");
}
@Test
public void testConsumerDrivenSplitRespectsSplitCooldown() {
SegmentLayout layout = initialLayout(2);
- Map<Long, SegmentLoadSample> load = Map.of(0L, cold(0), 1L, cold(0));
+ // Above the floor so the decision stays in the split lane, then blocked by cooldown.
+ Map<Long, SegmentLoadSample> load = Map.of(
+ 0L, sample(1_500, 0, 0, 0, 0), 1L, sample(2_000, 0, 0, 0, 0));
long recentSplit = NOW - Duration.ofSeconds(30).toMillis(); // < 1m cooldown
AutoScaleDecision d = AutoScalePolicyEvaluator.decide(layout, load, Map.of("sub", 3),
- baseConfig().build(), NOW, recentSplit, NO_PRIOR);
+ baseConfig().build(), NOW, recentSplit, NO_PRIOR, NO_PRIOR);
assertTrue(d instanceof AutoScaleDecision.NoAction, "within split cooldown, no split");
}
+ // --- consumer-driven rebucket (PIP-486 segments-vs-buckets) ---
+
+ @Test
+ public void testSurplusBelowFloorWithinCapacityDoesNothing() {
+ // UC#2 half 1: a cold topic's surplus that fits the existing bucket capacity is
+ // absorbed by broker-side fan-out — no split, no rollover.
+ SegmentLayout layout = initialLayout(2); // 2 segments × 2 buckets = capacity 4
+ Map<Long, SegmentLoadSample> load = Map.of(0L, cold(0), 1L, cold(0));
+ AutoScaleDecision d = decide(layout, load, Map.of("sub", 4), baseConfig().build());
+ assertTrue(d instanceof AutoScaleDecision.NoAction, d.toString());
+ }
+
+ @Test
+ public void testSurplusBelowFloorBeyondCapacityRebuckets() {
+ // UC#2 half 2: below the floor and beyond capacity → rebucket-up, sized to give every
+ // consumer a bucket at the next power of two: ceil(5/1)=5 → 8.
+ SegmentLayout layout = initialLayout(1); // 1 segment × 4 buckets
+ Map<Long, SegmentLoadSample> load = Map.of(0L, cold(0));
+ AutoScaleDecision d = decide(layout, load, Map.of("sub", 5), baseConfig().build());
+ assertTrue(d instanceof AutoScaleDecision.Rebucket, d.toString());
+ AutoScaleDecision.Rebucket r = (AutoScaleDecision.Rebucket) d;
+ assertEquals(r.segmentIds(), List.of(0L));
+ assertEquals(r.newBucketCount(), 8);
+ assertEquals(r.reason(), "below-split-rate-floor");
+ }
+
+ @Test
+ public void testRebucketRespectsRebucketCooldown() {
+ SegmentLayout layout = initialLayout(1);
+ Map<Long, SegmentLoadSample> load = Map.of(0L, cold(0));
+ long recentRebucket = NOW - Duration.ofSeconds(30).toMillis(); // < 1m cooldown
+ AutoScaleDecision d = AutoScalePolicyEvaluator.decide(layout, load, Map.of("sub", 5),
+ baseConfig().build(), NOW, NO_PRIOR, NO_PRIOR, recentRebucket);
+ assertTrue(d instanceof AutoScaleDecision.NoAction, "within rebucket cooldown");
+ }
+
+ @Test
+ public void testRebucketCapsAtMaxBucketsPerSegment() {
+ // A huge surplus is clamped to the per-segment ceiling…
+ SegmentLayout layout = initialLayout(1);
+ Map<Long, SegmentLoadSample> load = Map.of(0L, cold(0));
+ AutoScaleDecision d = decide(layout, load, Map.of("sub", 5_000),
+ baseConfig().maxEntryBucketsPerSegment(8).build());
+ assertTrue(d instanceof AutoScaleDecision.Rebucket, d.toString());
+ assertEquals(((AutoScaleDecision.Rebucket) d).newBucketCount(), 8);
+ assertEquals(((AutoScaleDecision.Rebucket) d).segmentIds(), List.of(0L));
+
+ // …and once the segment is at the ceiling, the remaining surplus stays idle.
+ SegmentLayout maxed = SegmentLayout.fromMetadata(
+ ScalableTopicController.createInitialMetadata(1, 8, Map.of()));
+ AutoScaleDecision none = decide(maxed, load, Map.of("sub", 5_000),
+ baseConfig().maxEntryBucketsPerSegment(8).build());
+ assertTrue(none instanceof AutoScaleDecision.NoAction, none.toString());
+ }
+
+ @Test
+ public void testMultiSegmentSurplusRebucketsAllSegmentsInOneShot() {
+ // Review scenario: four N=1 segments at the cap and ten consumers must converge in a
+ // single decision — every segment to the common target 4 (ceil(10/4)=3 → pow2 4),
+ // never one segment per cooldown.
+ SegmentLayout layout = SegmentLayout.fromMetadata(
+ ScalableTopicController.createInitialMetadata(4, 4, Map.of())); // 4 × N=1
+ Map<Long, SegmentLoadSample> load = Map.of(
+ 0L, cold(0), 1L, cold(0), 2L, cold(0), 3L, cold(0));
+ AutoScaleDecision d = decide(layout, load, Map.of("sub", 10),
+ baseConfig().maxSegments(4).build());
+ assertTrue(d instanceof AutoScaleDecision.Rebucket, d.toString());
+ AutoScaleDecision.Rebucket r = (AutoScaleDecision.Rebucket) d;
+ assertEquals(r.segmentIds(), List.of(0L, 1L, 2L, 3L));
+ assertEquals(r.newBucketCount(), 4);
+ }
+
+ @Test
+ public void testPartiallyRebucketedLayoutConvergesToUniformTarget() {
+ // A layout left uneven (one segment already rolled to 4, three still at N=1) must
+ // bring exactly the below-target segments up to the same target — the steady state
+ // is uniform, not arrival-history-dependent.
+ SegmentLayout base = SegmentLayout.fromMetadata(
+ ScalableTopicController.createInitialMetadata(4, 4, Map.of())); // 4 × N=1
+ SegmentLayout uneven = base.rebucketSegment(0, EntryBucketSplits.equalWidth(4), 0L);
+ // Active: successor(id=4, N=4) + segments 1..3 (N=1). Capacity 7 < 10 consumers.
+ Map<Long, SegmentLoadSample> load = Map.of(
+ 1L, cold(0), 2L, cold(0), 3L, cold(0), 4L, cold(0));
+ AutoScaleDecision d = decide(uneven, load, Map.of("sub", 10),
+ baseConfig().maxSegments(4).build());
+ assertTrue(d instanceof AutoScaleDecision.Rebucket, d.toString());
+ AutoScaleDecision.Rebucket r = (AutoScaleDecision.Rebucket) d;
+ assertEquals(r.segmentIds(), List.of(1L, 2L, 3L),
+ "only the below-target segments roll; the already-at-target one is untouched");
+ assertEquals(r.newBucketCount(), 4);
+ }
+
// --- load-driven split ---
@Test
@@ -213,6 +318,48 @@ public class AutoScalePolicyEvaluatorTest {
|| (m.segmentId1() == 1L && m.segmentId2() == 0L));
}
+ @Test
+ public void testMergeSkippedWhenClampWouldCutLiveParallelism() {
+ // Two at-ceiling segments (N=8 each, ceiling 8): a merge clamps 16 buckets down to
+ // 8, and the rebucket lane cannot grow past the ceiling to win them back. With 12
+ // live consumers that is a real parallelism cut (12 → 8), so the pair must not merge.
+ SegmentLayout layout = SegmentLayout.fromMetadata(
+ ScalableTopicController.createInitialMetadata(2, 16, Map.of()));
+ Map<Long, SegmentLoadSample> load = Map.of(0L, cold(old()), 1L, cold(old()));
+ AutoScaleDecision d = decide(layout, load, Map.of("sub", 12),
+ baseConfig().maxEntryBucketsPerSegment(8).build());
+ assertTrue(d instanceof AutoScaleDecision.NoAction, d.toString());
+ }
+
+ @Test
+ public void testMergeProceedsWhenClampStillCoversConsumers() {
+ // Same at-ceiling pair, but only 8 consumers: the merged segment's 8 buckets keep
+ // every live consumer owning a bucket, so the cold pair may still consolidate.
+ SegmentLayout layout = SegmentLayout.fromMetadata(
+ ScalableTopicController.createInitialMetadata(2, 16, Map.of()));
+ Map<Long, SegmentLoadSample> load = Map.of(0L, cold(old()), 1L, cold(old()));
+ AutoScaleDecision d = decide(layout, load, Map.of("sub", 8),
+ baseConfig().maxEntryBucketsPerSegment(8).build());
+ assertTrue(d instanceof AutoScaleDecision.Merge, d.toString());
+ }
+
+ @Test
+ public void testCapacityPreservingMergeAllowedWhenOverSubscribed() {
+ // [N=4][N=4] with ceiling 8: the merged segment keeps all 8 buckets, so even a
+ // topic whose 20 consumers already over-subscribe the capacity loses nothing — the
+ // guard vetoes reductions of the parallelism consumers actually get, not every
+ // "capacity < consumers" state. (A recent rebucket keeps the consumer-scale lane
+ // quiet so the merge pass is reached at all.)
+ SegmentLayout layout = SegmentLayout.fromMetadata(
+ ScalableTopicController.createInitialMetadata(2, 8, Map.of()));
+ Map<Long, SegmentLoadSample> load = Map.of(0L, cold(old()), 1L, cold(old()));
+ long recentRebucket = NOW - Duration.ofSeconds(30).toMillis(); // < 1m rebucketCooldown
+ AutoScaleDecision d = AutoScalePolicyEvaluator.decide(layout, load, Map.of("sub", 20),
+ baseConfig().maxEntryBucketsPerSegment(8).build(), NOW, NO_PRIOR, NO_PRIOR,
+ recentRebucket);
+ assertTrue(d instanceof AutoScaleDecision.Merge, d.toString());
+ }
+
@Test
public void testMergeRespectsMinSegments() {
SegmentLayout layout = initialLayout(2);
@@ -227,7 +374,7 @@ public class AutoScalePolicyEvaluatorTest {
Map<Long, SegmentLoadSample> load = Map.of(0L, cold(old()), 1L, cold(old()));
long recentMerge = NOW - Duration.ofMinutes(1).toMillis(); // < 5m cooldown
AutoScaleDecision d = AutoScalePolicyEvaluator.decide(layout, load, Map.of(),
- baseConfig().build(), NOW, NO_PRIOR, recentMerge);
+ baseConfig().build(), NOW, NO_PRIOR, recentMerge, NO_PRIOR);
assertTrue(d instanceof AutoScaleDecision.NoAction, "within merge cooldown, no merge");
}
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/EntryBucketSplitsTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/EntryBucketSplitsTest.java
index e1e1c827aa3f..889c9f690530 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/EntryBucketSplitsTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/EntryBucketSplitsTest.java
@@ -24,6 +24,7 @@ import java.util.Map;
import org.apache.pulsar.broker.resources.ScalableTopicMetadata;
import org.apache.pulsar.common.naming.TopicName;
import org.apache.pulsar.common.scalable.HashRange;
+import org.apache.pulsar.common.scalable.SegmentInfo;
import org.testng.annotations.Test;
/**
@@ -142,4 +143,35 @@ public class EntryBucketSplitsTest {
List.of(HashRange.of(0, 0x3FFF), HashRange.of(0x4000, 0x7FFF),
HashRange.of(0x8000, 0xBFFF), HashRange.of(0xC000, 0xFFFF)));
}
+
+ @Test
+ public void testEqualWidthClampsToRingSize() {
+ // Beyond one bucket per hash the split points would collide and produce zero-width
+ // ranges; equalWidth clamps so ranges(...) always materializes.
+ var splits = EntryBucketSplits.equalWidth(EntryBucketSplits.MAX_BUCKETS * 4);
+ assertEquals(splits.size() + 1, EntryBucketSplits.MAX_BUCKETS);
+ var ranges = EntryBucketSplits.ranges(splits);
+ assertEquals(ranges.size(), EntryBucketSplits.MAX_BUCKETS);
+ }
+
+ @Test
+ public void testMigratedMetadataClampsToBucketCeiling() {
+ // The PIP-475 migration path honours the per-segment ceiling like creation and merge:
+ // budget 8 over 1 partition would give the child N=8, clamped here to 4.
+ var md = ScalableTopicController.createMigratedMetadata(
+ TopicName.get("persistent://public/default/legacy"), 1, 8, 4);
+ var child = md.getSegments().values().stream()
+ .filter(SegmentInfo::isActive).findFirst().orElseThrow();
+ assertEquals(child.bucketCount(), 4, "budget-derived N=8 clamped to the ceiling 4");
+ }
+
+ @Test
+ public void testMergeClampsToBucketCeiling() {
+ // Merging recovers the parents' buckets but never past the configured per-segment
+ // ceiling.
+ var md = ScalableTopicController.createInitialMetadata(2, 8, Map.of()); // 2 × N=4
+ SegmentLayout merged = SegmentLayout.fromMetadata(md).mergeSegments(0, 1, 0L, 6);
+ SegmentInfo child = merged.getAllSegments().get(2L);
+ assertEquals(child.bucketCount(), 6, "sum 8 clamped to the ceiling 6");
+ }
}
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/ScalableTopicControllerAutoScaleTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/ScalableTopicControllerAutoScaleTest.java
index c7a5ac04762f..05d8a54e588a 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/ScalableTopicControllerAutoScaleTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/ScalableTopicControllerAutoScaleTest.java
@@ -30,6 +30,7 @@ import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.pulsar.broker.PulsarService;
import org.apache.pulsar.broker.ServiceConfiguration;
import org.apache.pulsar.broker.resources.NamespaceResources;
@@ -212,6 +213,8 @@ public class ScalableTopicControllerAutoScaleTest {
@Test
public void testConsumerDrivenSplit() throws Exception {
+ // Zero the split-vs-rebucket floor so the cold test topic exercises the split lane.
+ config.setScalableTopicSplitVsRebucketMinMsgRateInThreshold(0);
startController(1);
assertEquals(activeSegmentCount(), 1);
@@ -329,11 +332,34 @@ public class ScalableTopicControllerAutoScaleTest {
"invalid override combination must disable auto split/merge, not split");
}
+ /**
+ * PIP-486 review: an invalid BROKER-level policy value (no override involved) must also
+ * degrade to "auto scaling disabled" — the fallback is built from the unvalidated broker
+ * defaults, so re-validating the same bad config cannot rethrow on every evaluation.
+ */
+ @Test
+ public void testInvalidBrokerLevelPolicyDisablesAutoScale() throws Exception {
+ config.setScalableTopicEntryBucketMaxPerSegment(0); // violates [1, ring] — broker-level
+ startController(1);
+ controller.registerConsumer("sub", "c1", 1L, ScalableConsumerType.STREAM,
+ mock(TransportCnx.class)).get();
+ controller.registerConsumer("sub", "c2", 2L, ScalableConsumerType.STREAM,
+ mock(TransportCnx.class)).get();
+ // Must complete normally and take no action (a 2-consumer surplus would otherwise
+ // split or rebucket the cold single segment).
+ controller.evaluateAutoScaleForTest().get();
+ assertEquals(activeSegmentCount(), 1,
+ "invalid broker-level policy must disable auto scaling, not fail or act");
+ }
+
@Test
public void testConsumerBurstConvergesWithoutTicks() throws Exception {
// A group of consumers joining in quick succession must converge to one segment
// each purely from the event-driven evaluations + post-split follow-up chain — no
- // periodic tick and no manual evaluation calls.
+ // periodic tick and no manual evaluation calls. Zero the split-vs-rebucket floor so
+ // the cold test topic stays in the split lane (this test is about the convergence
+ // chain; the bucket lane has its own coverage).
+ config.setScalableTopicSplitVsRebucketMinMsgRateInThreshold(0);
startController(1);
for (int i = 1; i <= 4; i++) {
controller.registerConsumer("sub", "c" + i, i, ScalableConsumerType.STREAM,
@@ -361,6 +387,127 @@ public class ScalableTopicControllerAutoScaleTest {
assertEquals(activeSegmentCount(), 3, "second split blocked by cooldown");
}
+ private int soleActiveBucketCount() throws Exception {
+ var active = controller.getLayout().get().getActiveSegments().values();
+ assertEquals(active.size(), 1, "expected a single active segment");
+ return active.iterator().next().bucketCount();
+ }
+
+ /**
+ * PIP-486 review: the post-rollover follow-up must be scheduled off the REBUCKET
+ * cooldown. With the split cooldown huge and the rebucket cooldown short, consumers
+ * joining inside the rebucket cooldown are absorbed by the follow-up evaluation — under
+ * the old post-split scheduling nothing would re-evaluate for an hour.
+ */
+ @Test
+ public void testPostRebucketFollowUpUsesRebucketCooldown() throws Exception {
+ config.setScalableTopicSplitCooldownSeconds(3600);
+ config.setScalableTopicRebucketCooldownSeconds(3);
+ config.setScalableTopicAutoScaleIntervalSeconds(3600);
+ startController(1); // one segment, N=4
+
+ for (int i = 1; i <= 5; i++) {
+ controller.registerConsumer("sub", "c" + i, i, ScalableConsumerType.STREAM,
+ mock(TransportCnx.class)).get();
+ }
+ Awaitility.await().atMost(Duration.ofSeconds(10)).untilAsserted(
+ () -> assertEquals(soleActiveBucketCount(), 8,
+ "five consumers on a cold topic roll the segment to 8"));
+
+ // More joins land inside the rebucket cooldown: their event-driven evaluations are
+ // blocked, so only the post-rollover follow-up can serve them.
+ for (int i = 6; i <= 9; i++) {
+ controller.registerConsumer("sub", "c" + i, i, ScalableConsumerType.STREAM,
+ mock(TransportCnx.class)).get();
+ }
+ Awaitility.await().atMost(Duration.ofSeconds(20)).untilAsserted(
+ () -> assertEquals(soleActiveBucketCount(), 16,
+ "the follow-up after the rebucket cooldown must absorb the late joins"));
+ }
+
+ /**
+ * PIP-486 review: a mid-batch rollover failure must still schedule the follow-up
+ * evaluation, which retries the remainder once the rebucket cooldown expires.
+ */
+ @Test
+ public void testMidBatchRebucketFailureStillSchedulesFollowUp() throws Exception {
+ config.setScalableTopicSplitCooldownSeconds(3600);
+ config.setScalableTopicRebucketCooldownSeconds(2);
+ config.setScalableTopicAutoScaleIntervalSeconds(3600);
+ resources.createScalableTopicAsync(topicName,
+ ScalableTopicController.createInitialMetadata(2, 4, Map.of())).get(); // 2 × N=2
+ AtomicBoolean injectedOnce = new AtomicBoolean();
+ controller = new ScalableTopicController(topicName, resources, brokerService,
+ coordinationService) {
+ @Override
+ public CompletableFuture<SegmentLayout> rebucketSegment(long segmentId,
+ int newBucketCount) {
+ if (segmentId == 1 && injectedOnce.compareAndSet(false, true)) {
+ return CompletableFuture.failedFuture(new RuntimeException("injected failure"));
+ }
+ return super.rebucketSegment(segmentId, newBucketCount);
+ }
+ };
+ controller.initialize().get();
+
+ // Seven consumers, cold topic: batch Rebucket([0,1] → 4). Segment 0 rolls, segment 1
+ // fails once; capacity is then 6 < 7, so the follow-up must retry it.
+ for (int i = 1; i <= 7; i++) {
+ controller.registerConsumer("sub", "c" + i, i, ScalableConsumerType.STREAM,
+ mock(TransportCnx.class)).get();
+ }
+ Awaitility.await().atMost(Duration.ofSeconds(20)).untilAsserted(() -> {
+ var active = controller.getLayout().get().getActiveSegments().values();
+ assertEquals(active.size(), 2);
+ for (var segment : active) {
+ assertEquals(segment.bucketCount(), 4,
+ "the follow-up must retry the failed remainder of the batch");
+ }
+ });
+ }
+
+ /**
+ * PIP-486 review: after a leader failover the rollover cooldown must be re-seeded from
+ * the layout (a same-range single-parent child is a rebucket successor), and the rollover
+ * must NOT be charged to the split cooldown.
+ */
+ @Test
+ public void testRebucketCooldownSurvivesLeaderFailover() throws Exception {
+ config.setScalableTopicSplitCooldownSeconds(3600);
+ config.setScalableTopicRebucketCooldownSeconds(3600);
+ config.setScalableTopicAutoScaleIntervalSeconds(3600);
+ startController(1); // one segment, N=4
+ for (int i = 1; i <= 5; i++) {
+ controller.registerConsumer("sub", "c" + i, i, ScalableConsumerType.STREAM,
+ mock(TransportCnx.class)).get();
+ }
+ Awaitility.await().atMost(Duration.ofSeconds(10)).untilAsserted(
+ () -> assertEquals(soleActiveBucketCount(), 8));
+
+ // Leadership moves. The new leader must know a rollover just ran…
+ controller.close().join();
+ controller = new ScalableTopicController(topicName, resources, brokerService,
+ coordinationService);
+ controller.initialize().get();
+
+ // …so another consumer-driven rollover is blocked by the seeded rebucket cooldown…
+ controller.registerConsumer("sub", "c9", 9L, ScalableConsumerType.STREAM,
+ mock(TransportCnx.class)).get();
+ controller.evaluateAutoScaleForTest().get();
+ assertEquals(soleActiveBucketCount(), 8,
+ "the seeded rebucket cooldown must block an immediate second rollover");
+
+ // …while a genuine load-driven split is NOT suppressed: the rollover must not have
+ // been charged to the split cooldown.
+ long successorId = controller.getLayout().get().getActiveSegments().keySet()
+ .iterator().next();
+ resources.reportSegmentLoadAsync(topicName, successorId,
+ new SegmentLoadStats(20_000, 0, 0, 0)).get();
+ controller.evaluateAutoScaleForTest().get();
+ assertEquals(activeSegmentCount(), 2,
+ "a hot-segment split must fire — the rollover is not a split");
+ }
+
@Test
public void testSplitCooldownSurvivesLeaderFailover() throws Exception {
config.setScalableTopicSplitCooldownSeconds(3600);
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/SegmentLayoutTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/SegmentLayoutTest.java
index fae5afaa100a..2da9bad009cc 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/SegmentLayoutTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/SegmentLayoutTest.java
@@ -153,6 +153,49 @@ public class SegmentLayoutTest {
assertEquals(merged.parentIds(), List.of(2L, 3L));
}
+ @Test
+ public void testRebucketSegment() {
+ // 1 segment, budget 4 -> the initial segment has N=4 buckets.
+ ScalableTopicMetadata metadata = ScalableTopicController.createInitialMetadata(1, 4, Map.of());
+ SegmentLayout layout = SegmentLayout.fromMetadata(metadata);
+
+ SegmentLayout after = layout.rebucketSegment(0, EntryBucketSplits.equalWidth(8), 123L);
+
+ assertEquals(after.getEpoch(), 1);
+ assertEquals(after.getActiveSegments().size(), 1);
+ assertEquals(after.getAllSegments().size(), 2);
+
+ SegmentInfo sealed = after.getAllSegments().get(0L);
+ assertTrue(sealed.isSealed());
+ assertEquals(sealed.childIds(), List.of(1L));
+ assertEquals(sealed.sealedAtMs(), 123L);
+
+ // The successor keeps the range and carries the new bucketing.
+ SegmentInfo successor = after.getAllSegments().get(1L);
+ assertTrue(successor.isActive());
+ assertEquals(successor.parentIds(), List.of(0L));
+ assertEquals(successor.hashRange(), sealed.hashRange());
+ assertEquals(successor.bucketCount(), 8);
+ assertEquals(successor.createdAtMs(), 123L);
+ }
+
+ @Test
+ public void testRebucketRejectsInvalidTargets() {
+ ScalableTopicMetadata metadata = ScalableTopicController.createInitialMetadata(1, 4, Map.of());
+ SegmentLayout layout = SegmentLayout.fromMetadata(metadata);
+
+ // Unknown segment.
+ assertThrows(IllegalArgumentException.class,
+ () -> layout.rebucketSegment(99, EntryBucketSplits.equalWidth(8), 0L));
+ // Unchanged bucketing (initial segment already has N=4).
+ assertThrows(IllegalArgumentException.class,
+ () -> layout.rebucketSegment(0, EntryBucketSplits.equalWidth(4), 0L));
+ // Sealed segment.
+ SegmentLayout afterSplit = layout.splitSegment(0, 0L);
+ assertThrows(IllegalArgumentException.class,
+ () -> afterSplit.rebucketSegment(0, EntryBucketSplits.equalWidth(8), 0L));
+ }
+
@Test
public void testSplitRecordsWallClockTimestamps() {
ScalableTopicMetadata metadata = ScalableTopicController.createInitialMetadata(1, 4, Map.of());
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/SubscriptionCoordinatorTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/SubscriptionCoordinatorTest.java
index 87bddbf21d55..1a2790713912 100644
--- a/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/SubscriptionCoordinatorTest.java
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/broker/service/scalable/SubscriptionCoordinatorTest.java
@@ -185,14 +185,18 @@ public class SubscriptionCoordinatorTest {
assertFalse(assigned.contains(4L), "child of un-drained parent must be blocked");
assertFalse(assigned.contains(5L), "child of un-drained parent must be blocked");
- // Mark the parent drained — the next poll should pick it up and the children
- // must end up assigned.
+ // Mark the parent drained — the next poll should pick it up: the children
+ // become assigned and the drained parent retires from the assignment (keeping
+ // it would pin consumers to a dead segment).
drained.add(0L);
Awaitility.await().atMost(5, TimeUnit.SECONDS).untilAsserted(() -> {
Set<Long> nowAssigned = new HashSet<>(segmentIds(
findByName(orderedCoordinator.currentAssignment(), "consumer-1")));
- assertTrue(nowAssigned.containsAll(Set.of(0L, 1L, 2L, 3L, 4L, 5L)),
- "after parent drain, all 6 segments must be assigned, got " + nowAssigned);
+ assertTrue(nowAssigned.containsAll(Set.of(1L, 2L, 3L, 4L, 5L)),
+ "after parent drain, children + active segments must be assigned, got "
+ + nowAssigned);
+ assertFalse(nowAssigned.contains(0L),
+ "the drained parent must retire from the assignment");
});
} finally {
orderedCoordinator.close();
@@ -516,6 +520,71 @@ public class SubscriptionCoordinatorTest {
// --- Helpers ---
+ /**
+ * PIP-486 review: a sealed parent must retire from the assignable set once drained.
+ * Rollover topology (parent sealed with 4 buckets, same-range successor with 8), five
+ * consumers: before the drain the parent's buckets cap the group at 4 owners (successor
+ * gated, one consumer idle); after the drain every consumer moves to the successor and
+ * none stays pinned to the dead parent.
+ */
+ @Test
+ public void testDrainedParentRetiresFromAssignment() throws Exception {
+ Set<Long> drained = ConcurrentHashMap.newKeySet();
+ SegmentDrainChecker checker = (segment, sub) ->
+ CompletableFuture.completedFuture(drained.contains(segment.segmentId()));
+ SegmentLayout base = SegmentLayout.fromMetadata(
+ ScalableTopicController.createInitialMetadata(1, 4, Map.of()));
+ SegmentLayout rolled = base.rebucketSegment(0, EntryBucketSplits.equalWidth(8), 0L);
+ SubscriptionCoordinator coordinator = new SubscriptionCoordinator("test-sub",
+ topicName, base, resources, scheduler, Duration.ofMillis(200),
+ checker, Duration.ofMillis(50), Duration.ofSeconds(5));
+ try {
+ for (int i = 1; i <= 5; i++) {
+ coordinator.registerConsumer("consumer-" + i, i, mock(TransportCnx.class)).get();
+ }
+ Map<ConsumerSession, ConsumerAssignment> before = coordinator.onLayoutChange(rolled).get();
+ assertEquals(countAssignedTo(before, 0L), 4,
+ "undrained parent caps the group at its 4 buckets");
+ assertEquals(countAssignedTo(before, 1L), 0,
+ "successor must be gated while the parent is undrained");
+ assertEquals(countIdle(before), 1, "one consumer beyond the parent's capacity idles");
+
+ drained.add(0L);
+ coordinator.markSegmentsDrained(Set.of(0L));
+ Map<ConsumerSession, ConsumerAssignment> after = coordinator.onLayoutChange(rolled).get();
+ assertEquals(countAssignedTo(after, 0L), 0,
+ "a drained parent must not be assigned to anyone");
+ assertEquals(countAssignedTo(after, 1L), 5,
+ "every consumer moves to the successor");
+ assertEquals(countIdle(after), 0);
+ } finally {
+ coordinator.close();
+ }
+ }
+
+ private static int countAssignedTo(Map<ConsumerSession, ConsumerAssignment> m, long segmentId) {
+ int count = 0;
+ for (ConsumerAssignment a : m.values()) {
+ for (var seg : a.assignedSegments()) {
+ if (seg.segmentId() == segmentId) {
+ count++;
+ break;
+ }
+ }
+ }
+ return count;
+ }
+
+ private static int countIdle(Map<ConsumerSession, ConsumerAssignment> m) {
+ int count = 0;
+ for (ConsumerAssignment a : m.values()) {
+ if (a.assignedSegments().isEmpty()) {
+ count++;
+ }
+ }
+ return count;
+ }
+
/**
* PIP-486 review: the identity guard on explicit unregister. A same-name rejoin attaches
* a new consumer id to the session; a leave carrying the OLD id (the departed consumer's)
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/client/api/v5/V5AutoRebucketTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/client/api/v5/V5AutoRebucketTest.java
new file mode 100644
index 000000000000..a7217898a1f7
--- /dev/null
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/client/api/v5/V5AutoRebucketTest.java
@@ -0,0 +1,192 @@
+/*
+ * 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.testng.Assert.assertEquals;
+import static org.testng.Assert.assertTrue;
+import java.nio.charset.StandardCharsets;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+import lombok.Cleanup;
+import org.apache.pulsar.client.api.v5.config.SubscriptionInitialPosition;
+import org.apache.pulsar.client.api.v5.schema.Schema;
+import org.apache.pulsar.common.policies.data.ScalableTopicMetadata;
+import org.apache.pulsar.common.scalable.HashRange;
+import org.apache.pulsar.common.scalable.ScalableTopicHashing;
+import org.awaitility.Awaitility;
+import org.testng.annotations.Test;
+
+/**
+ * PIP-486 segments-vs-buckets policy, UC#2 end to end: on a low-throughput topic (below the
+ * split-vs-rebucket rate floor), surplus stream consumers must be served by growing the
+ * segment's entry-buckets — an automatic rebucket rollover — instead of materializing physical
+ * segments for consumer count alone.
+ */
+public class V5AutoRebucketTest extends V5ClientBaseTest {
+
+ @Test
+ public void testConsumerSurplusOnColdTopicRebucketsInsteadOfSplitting() throws Exception {
+ String topic = newScalableTopic(1);
+ String subscription = "auto-rebucket";
+
+ // Five consumers on a cold one-segment topic (N=4 by default): the per-subscription
+ // surplus (5 > 1 segment) is below the 1k msg/s split floor and beyond the bucket
+ // capacity (5 > 4), so the controller must roll the segment over to 8 buckets.
+ List<StreamConsumer<String>> consumers = new ArrayList<>();
+ for (int i = 0; i < 5; i++) {
+ consumers.add(track(v5Client.newStreamConsumer(Schema.string())
+ .topic(topic)
+ .subscriptionName(subscription)
+ .subscriptionInitialPosition(SubscriptionInitialPosition.EARLIEST)
+ .subscribe()));
+ }
+
+ Awaitility.await().atMost(Duration.ofSeconds(30)).untilAsserted(() -> {
+ ScalableTopicMetadata md = admin.scalableTopics().getMetadata(topic);
+ List<ScalableTopicMetadata.SegmentInfo> active = md.getSegments().values().stream()
+ .filter(ScalableTopicMetadata.SegmentInfo::isActive).toList();
+ assertEquals(active.size(), 1,
+ "a cold topic must not split for consumer count — expected one active segment");
+ assertEquals(active.get(0).getEntryBucketSplits().size() + 1, 8,
+ "the surplus must be absorbed by an automatic rebucket to 8");
+ assertEquals(md.getSegments().size(), 2,
+ "exactly one rollover: sealed parent + successor");
+ });
+
+ // Once the (empty) parent drains, every consumer must move to the successor — none
+ // may stay pinned to the drained parent, and none may idle.
+ long successorId = admin.scalableTopics().getMetadata(topic).getSegments().values().stream()
+ .filter(ScalableTopicMetadata.SegmentInfo::isActive).findFirst().orElseThrow()
+ .getSegmentId();
+ String successorTopic = admin.scalableTopics().getStats(topic).getSegments().values()
+ .stream().filter(seg -> seg.name().endsWith("-" + successorId)).findFirst()
+ .orElseThrow().name();
+ Awaitility.await().atMost(Duration.ofSeconds(30)).untilAsserted(() -> {
+ var sub = getTopicReference(successorTopic).orElseThrow().getSubscription(subscription);
+ assertTrue(sub != null && sub.getConsumers().size() == 5,
+ "all five consumers must attach to the successor, got "
+ + (sub == null ? "no subscription" : sub.getConsumers().size()));
+ });
+
+ // The rebucketed segment serves all five consumers: keyed traffic must reach them
+ // collectively, per-key in order, with every key wholly on one consumer.
+ @Cleanup
+ Producer<String> producer = v5Client.newProducer(Schema.string())
+ .topic(topic)
+ .create();
+ // Deterministic key set covering every one of the successor's 8 buckets (at least two
+ // keys each), so every consumer — each owns at least one bucket — must receive traffic
+ // and the delivery assertion below can demand all five, not "some".
+ List<String> keys = bucketCoveringKeys(8, 2);
+ int perKey = 5;
+ Map<String, List<String>> sent = new HashMap<>();
+ for (String k : keys) {
+ sent.put(k, new ArrayList<>());
+ }
+ for (int i = 0; i < perKey; i++) {
+ for (String k : keys) {
+ String value = k + "-" + i;
+ producer.newMessage().key(k).value(value).send();
+ sent.get(k).add(value);
+ }
+ }
+
+ List<Map<String, List<String>>> got = new ArrayList<>();
+ List<Thread> drainers = new ArrayList<>();
+ List<Throwable> drainerFailures = new CopyOnWriteArrayList<>();
+ for (StreamConsumer<String> consumer : consumers) {
+ Map<String, List<String>> into = new ConcurrentHashMap<>();
+ got.add(into);
+ Thread t = new Thread(() -> {
+ try {
+ while (true) {
+ Message<String> msg = consumer.receive(Duration.ofSeconds(3));
+ if (msg == null) {
+ return;
+ }
+ String key = msg.key().orElseThrow();
+ into.computeIfAbsent(key, __ -> new ArrayList<>()).add(msg.value());
+ consumer.acknowledgeCumulative(msg.id());
+ }
+ } catch (Throwable t2) {
+ drainerFailures.add(t2);
+ }
+ });
+ t.start();
+ drainers.add(t);
+ }
+ for (Thread t : drainers) {
+ t.join();
+ }
+ assertTrue(drainerFailures.isEmpty(), "drainer failed: " + drainerFailures);
+
+ int receiving = 0;
+ for (String k : keys) {
+ List<String> combined = null;
+ for (Map<String, List<String>> into : got) {
+ List<String> values = into.get(k);
+ if (values == null) {
+ continue;
+ }
+ assertTrue(combined == null, "key " + k + " was split across consumers");
+ combined = values;
+ }
+ assertEquals(combined, sent.get(k), "per-key order/content for key=" + k);
+ }
+ for (Map<String, List<String>> into : got) {
+ if (!into.isEmpty()) {
+ receiving++;
+ }
+ }
+ assertEquals(receiving, consumers.size(),
+ "the key set covers every bucket, so every consumer must receive traffic");
+ }
+
+ /**
+ * Deterministic keys such that every one of {@code buckets} equal-width entry-buckets holds
+ * at least {@code minPerBucket} keys — computed with the same hashing the producer uses.
+ */
+ private static List<String> bucketCoveringKeys(int buckets, int minPerBucket) {
+ int bucketWidth = (HashRange.MAX_HASH + 1) / buckets;
+ int[] counts = new int[buckets];
+ List<String> keys = new ArrayList<>();
+ boolean covered = false;
+ for (int i = 0; !covered && i < 10_000; i++) {
+ String key = "key-" + i;
+ int hash = ScalableTopicHashing.entryBucketHash(
+ ScalableTopicHashing.murmur(key.getBytes(StandardCharsets.UTF_8)));
+ int bucket = Math.min(hash / bucketWidth, buckets - 1);
+ if (counts[bucket] < minPerBucket) {
+ counts[bucket]++;
+ keys.add(key);
+ }
+ covered = true;
+ for (int c : counts) {
+ covered &= c >= minPerBucket;
+ }
+ }
+ assertTrue(covered, "no key set covering all " + buckets + " buckets found");
+ return keys;
+ }
+}
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/client/api/v5/V5SegmentRebucketTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/client/api/v5/V5SegmentRebucketTest.java
new file mode 100644
index 000000000000..b78ff700879e
--- /dev/null
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/client/api/v5/V5SegmentRebucketTest.java
@@ -0,0 +1,164 @@
+/*
+ * 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.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNotNull;
+import static org.testng.Assert.assertTrue;
+import static org.testng.Assert.expectThrows;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import lombok.Cleanup;
+import org.apache.pulsar.client.admin.PulsarAdminException;
+import org.apache.pulsar.client.api.v5.config.SubscriptionInitialPosition;
+import org.apache.pulsar.client.api.v5.schema.Schema;
+import org.apache.pulsar.common.policies.data.ScalableTopicMetadata;
+import org.awaitility.Awaitility;
+import org.testng.annotations.Test;
+
+/**
+ * PIP-486 rebucket rollover: {@code admin.scalableTopics().rebucketSegment(...)} seals a segment
+ * and rolls it over to a same-range successor with a new entry-bucket count. The change rides the
+ * ordinary seal → successor flow, so producers redirect transparently and ordered consumption
+ * preserves per-key order across the boundary.
+ */
+public class V5SegmentRebucketTest extends V5ClientBaseTest {
+
+ @Test
+ public void testRebucketMidFlowPreservesPerKeyOrder() throws Exception {
+ String topic = newScalableTopic(1);
+
+ @Cleanup
+ Producer<String> producer = v5Client.newProducer(Schema.string())
+ .topic(topic)
+ .create();
+ @Cleanup
+ StreamConsumer<String> consumer = v5Client.newStreamConsumer(Schema.string())
+ .topic(topic)
+ .subscriptionName("rebucket-sub")
+ .subscriptionInitialPosition(SubscriptionInitialPosition.EARLIEST)
+ .subscribe();
+
+ List<String> keys = new ArrayList<>();
+ for (int i = 0; i < 16; i++) {
+ keys.add("key-" + i);
+ }
+ int perKey = 10;
+ Map<String, List<String>> sent = new HashMap<>();
+ for (String k : keys) {
+ sent.put(k, new ArrayList<>());
+ }
+
+ // Phase 1: lands on the initial segment under its original bucketing (N=4 by default).
+ for (int i = 0; i < perKey; i++) {
+ for (String k : keys) {
+ String value = k + "-" + i;
+ producer.newMessage().key(k).value(value).send();
+ sent.get(k).add(value);
+ }
+ }
+
+ long parentId = soleActiveSegmentId(topic);
+ admin.scalableTopics().rebucketSegment(topic, parentId, 8);
+
+ // The rollover seals the parent and creates one same-range successor with 8 buckets.
+ Awaitility.await().untilAsserted(() -> {
+ ScalableTopicMetadata md = admin.scalableTopics().getMetadata(topic);
+ List<ScalableTopicMetadata.SegmentInfo> active = md.getSegments().values().stream()
+ .filter(ScalableTopicMetadata.SegmentInfo::isActive).toList();
+ assertEquals(active.size(), 1, "rollover must keep exactly one active segment");
+ ScalableTopicMetadata.SegmentInfo successor = active.get(0);
+ assertTrue(successor.getSegmentId() != parentId, "successor must be a new segment");
+ assertEquals(successor.getParentIds(), List.of(parentId));
+ assertEquals(successor.getEntryBucketSplits().size() + 1, 8,
+ "successor must carry the new bucket count");
+ ScalableTopicMetadata.SegmentInfo parent = md.getSegments().get(parentId);
+ assertTrue(parent.isSealed(), "parent must be sealed");
+ assertEquals(parent.getHashRange().getStart(), successor.getHashRange().getStart());
+ assertEquals(parent.getHashRange().getEnd(), successor.getHashRange().getEnd());
+ });
+
+ // Phase 2: the producer re-routes to the successor (transparent segment-gone retry)
+ // and batches by the new 8-bucket boundaries.
+ for (int i = perKey; i < perKey * 2; i++) {
+ for (String k : keys) {
+ String value = k + "-" + i;
+ producer.newMessage().key(k).value(value).send();
+ sent.get(k).add(value);
+ }
+ }
+
+ // Ordered consumption across the rollover: the sealed parent must be fully consumed
+ // AND acknowledged before the controller serves the successor, so ack as we go (an
+ // order-sensitive application would) — holding every ack would leave the parent
+ // undrained and the successor unassigned.
+ Map<String, List<String>> received = new HashMap<>();
+ int total = keys.size() * perKey * 2;
+ for (int i = 0; i < total; i++) {
+ Message<String> msg = consumer.receive(Duration.ofSeconds(10));
+ assertNotNull(msg, "missed message #" + i);
+ String key = msg.key().orElseThrow(() -> new AssertionError("missing key"));
+ received.computeIfAbsent(key, __ -> new ArrayList<>()).add(msg.value());
+ consumer.acknowledgeCumulative(msg.id());
+ }
+
+ for (String k : keys) {
+ assertEquals(received.get(k), sent.get(k),
+ "per-key order across the rebucket rollover for key=" + k);
+ }
+ }
+
+ @Test
+ public void testRebucketRejectsInvalidRequests() throws Exception {
+ String topic = newScalableTopic(1);
+ long segmentId = soleActiveSegmentId(topic);
+
+ // All segment-level rejections are client errors: HTTP 412, never 500.
+ // Out-of-range bucket counts.
+ assertEquals(expectThrows(PulsarAdminException.class,
+ () -> admin.scalableTopics().rebucketSegment(topic, segmentId, 0))
+ .getStatusCode(), 412);
+ // Unchanged bucketing (the initial segment already has the budget-derived N=4).
+ assertEquals(expectThrows(PulsarAdminException.class,
+ () -> admin.scalableTopics().rebucketSegment(topic, segmentId, 4))
+ .getStatusCode(), 412);
+ // Unknown segment.
+ assertEquals(expectThrows(PulsarAdminException.class,
+ () -> admin.scalableTopics().rebucketSegment(topic, 12345, 8))
+ .getStatusCode(), 412);
+
+ // A valid rollover still works after the rejections, and the parent (now sealed)
+ // cannot be rolled over again.
+ admin.scalableTopics().rebucketSegment(topic, segmentId, 8);
+ assertEquals(expectThrows(PulsarAdminException.class,
+ () -> admin.scalableTopics().rebucketSegment(topic, segmentId, 16))
+ .getStatusCode(), 412);
+ }
+
+ private long soleActiveSegmentId(String topic) throws Exception {
+ ScalableTopicMetadata md = admin.scalableTopics().getMetadata(topic);
+ List<ScalableTopicMetadata.SegmentInfo> active = md.getSegments().values().stream()
+ .filter(ScalableTopicMetadata.SegmentInfo::isActive).toList();
+ assertEquals(active.size(), 1, "expected exactly one active segment");
+ return active.get(0).getSegmentId();
+ }
+}
diff --git a/pulsar-client-admin-api/src/main/java/org/apache/pulsar/client/admin/ScalableTopics.java b/pulsar-client-admin-api/src/main/java/org/apache/pulsar/client/admin/ScalableTopics.java
index b2f7632951e7..9fed01cf15fd 100644
--- a/pulsar-client-admin-api/src/main/java/org/apache/pulsar/client/admin/ScalableTopics.java
+++ b/pulsar-client-admin-api/src/main/java/org/apache/pulsar/client/admin/ScalableTopics.java
@@ -324,6 +324,26 @@ public interface ScalableTopics {
*/
CompletableFuture<Void> splitSegmentAsync(String topic, long segmentId);
+ /**
+ * Rebucket a segment: roll it over to a same-range successor segment with the given
+ * entry-bucket count (PIP-486). The sealed predecessor drains under its old buckets while
+ * the successor takes new writes under the new ones.
+ *
+ * @param topic Topic name in the format "tenant/namespace/topic"
+ * @param segmentId ID of the segment to rebucket
+ * @param bucketCount entry-bucket count for the successor segment
+ */
+ void rebucketSegment(String topic, long segmentId, int bucketCount) throws PulsarAdminException;
+
+ /**
+ * Rebucket a segment asynchronously.
+ *
+ * @param topic Topic name in the format "tenant/namespace/topic"
+ * @param segmentId ID of the segment to rebucket
+ * @param bucketCount entry-bucket count for the successor segment
+ */
+ CompletableFuture<Void> rebucketSegmentAsync(String topic, long segmentId, int bucketCount);
+
/**
* Merge two adjacent segments into one.
*
diff --git a/pulsar-client-admin-api/src/main/java/org/apache/pulsar/common/policies/data/AutoScalePolicyOverride.java b/pulsar-client-admin-api/src/main/java/org/apache/pulsar/common/policies/data/AutoScalePolicyOverride.java
index 30ecd78e5a7a..7444dbbabb28 100644
--- a/pulsar-client-admin-api/src/main/java/org/apache/pulsar/common/policies/data/AutoScalePolicyOverride.java
+++ b/pulsar-client-admin-api/src/main/java/org/apache/pulsar/common/policies/data/AutoScalePolicyOverride.java
@@ -61,6 +61,15 @@ public final class AutoScalePolicyOverride {
/** Minimum seconds between automatic merges. */
private Long mergeCooldownSeconds;
+ /**
+ * PIP-486 segments-vs-buckets floor: on consumer-driven scale-up, split only if the busiest
+ * segment's inbound msg/s is at or above this; below it, grow entry-buckets instead.
+ */
+ private Double splitVsRebucketMinMsgRateInThreshold;
+
+ /** Minimum seconds between automatic entry-bucket rollovers (rebuckets). */
+ private Long rebucketCooldownSeconds;
+
/** Seconds a segment pair must stay cold before becoming merge-eligible. */
private Long mergeWindowSeconds;
diff --git a/pulsar-client-admin-api/src/main/java/org/apache/pulsar/common/policies/data/ScalableTopicMetadata.java b/pulsar-client-admin-api/src/main/java/org/apache/pulsar/common/policies/data/ScalableTopicMetadata.java
index ce246a1340d6..4e5044f226af 100644
--- a/pulsar-client-admin-api/src/main/java/org/apache/pulsar/common/policies/data/ScalableTopicMetadata.java
+++ b/pulsar-client-admin-api/src/main/java/org/apache/pulsar/common/policies/data/ScalableTopicMetadata.java
@@ -83,6 +83,14 @@ public class ScalableTopicMetadata {
*/
private String legacyTopicName;
+ /**
+ * PIP-486 entry-bucket split points: the ascending start hashes of buckets
+ * {@code 1..N-1} within the segment's 16-bit entry-bucket ring (empty = a single
+ * bucket). The segment has {@code entryBucketSplits.size() + 1} entry-buckets;
+ * a segment's bucketing is immutable — a rebucket rolls over to a successor.
+ */
+ private List<Integer> entryBucketSplits;
+
public boolean isActive() {
return "ACTIVE".equals(state);
}
diff --git a/pulsar-client-admin-api/src/test/java/org/apache/pulsar/common/policies/data/ScalableTopicMetadataTest.java b/pulsar-client-admin-api/src/test/java/org/apache/pulsar/common/policies/data/ScalableTopicMetadataTest.java
index 6259d9799a46..75d874496b65 100644
--- a/pulsar-client-admin-api/src/test/java/org/apache/pulsar/common/policies/data/ScalableTopicMetadataTest.java
+++ b/pulsar-client-admin-api/src/test/java/org/apache/pulsar/common/policies/data/ScalableTopicMetadataTest.java
@@ -122,7 +122,7 @@ public class ScalableTopicMetadataTest {
@Test
public void testSegmentInfoHelpersForUnknownStateAreFalse() {
ScalableTopicMetadata.SegmentInfo seg = new ScalableTopicMetadata.SegmentInfo(
- 0L, hashRange(0, 0xFFFF), "UNKNOWN", List.of(), List.of(), 0L, -1L, null);
+ 0L, hashRange(0, 0xFFFF), "UNKNOWN", List.of(), List.of(), 0L, -1L, null, null);
assertFalse(seg.isActive());
assertFalse(seg.isSealed());
}
@@ -131,14 +131,14 @@ public class ScalableTopicMetadataTest {
public void testSegmentInfoLegacyFlag() {
// A null/empty legacyTopicName is a regular controller-managed segment.
ScalableTopicMetadata.SegmentInfo regular = new ScalableTopicMetadata.SegmentInfo(
- 1L, hashRange(0, 0xFFFF), "ACTIVE", List.of(), List.of(), 0L, -1L, null);
+ 1L, hashRange(0, 0xFFFF), "ACTIVE", List.of(), List.of(), 0L, -1L, null, null);
assertFalse(regular.isLegacy());
assertNull(regular.getLegacyTopicName());
// A non-empty legacyTopicName marks a legacy segment wrapping a persistent:// topic.
ScalableTopicMetadata.SegmentInfo legacy = new ScalableTopicMetadata.SegmentInfo(
0L, hashRange(0, 0xFFFF), "SEALED", List.of(), List.of(2L), 0L, 0L,
- "persistent://tenant/ns/x-partition-0");
+ "persistent://tenant/ns/x-partition-0", null);
assertTrue(legacy.isLegacy());
assertEquals(legacy.getLegacyTopicName(), "persistent://tenant/ns/x-partition-0");
}
@@ -186,7 +186,7 @@ public class ScalableTopicMetadataTest {
long createdAtEpoch) {
return new ScalableTopicMetadata.SegmentInfo(
id, hashRange(start, end), "ACTIVE",
- List.of(), List.of(), createdAtEpoch, -1L, null);
+ List.of(), List.of(), createdAtEpoch, -1L, null, null);
}
private static ScalableTopicMetadata.SegmentInfo sealedSegment(long id, int start, int end,
@@ -196,7 +196,7 @@ public class ScalableTopicMetadataTest {
long sealedAtEpoch) {
return new ScalableTopicMetadata.SegmentInfo(
id, hashRange(start, end), "SEALED",
- parents, children, createdAtEpoch, sealedAtEpoch, null);
+ parents, children, createdAtEpoch, sealedAtEpoch, null, null);
}
private static ScalableTopicMetadata.HashRange hashRange(int start, int end) {
diff --git a/pulsar-client-admin/src/main/java/org/apache/pulsar/client/admin/internal/ScalableTopicsImpl.java b/pulsar-client-admin/src/main/java/org/apache/pulsar/client/admin/internal/ScalableTopicsImpl.java
index 068101ad6e9d..9c294a067fd8 100644
--- a/pulsar-client-admin/src/main/java/org/apache/pulsar/client/admin/internal/ScalableTopicsImpl.java
+++ b/pulsar-client-admin/src/main/java/org/apache/pulsar/client/admin/internal/ScalableTopicsImpl.java
@@ -286,6 +286,20 @@ public class ScalableTopicsImpl extends BaseResource implements ScalableTopics {
return asyncPostRequest(path, Entity.entity("", MediaType.APPLICATION_JSON));
}
+ @Override
+ public void rebucketSegment(String topic, long segmentId, int bucketCount)
+ throws PulsarAdminException {
+ sync(() -> rebucketSegmentAsync(topic, segmentId, bucketCount));
+ }
+
+ @Override
+ public CompletableFuture<Void> rebucketSegmentAsync(String topic, long segmentId, int bucketCount) {
+ TopicName tn = validateTopic(topic);
+ WebTarget path = topicPath(tn).path("rebucket").path(String.valueOf(segmentId))
+ .queryParam("bucketCount", bucketCount);
+ return asyncPostRequest(path, Entity.entity("", MediaType.APPLICATION_JSON));
+ }
+
// --- Merge ---
@Override