Repository navigation
Conversation
Sealing a mutable bucket currently copies the first snapshot segment
(up to delayedDeliveryMaxIndexesPerBucketSnapshotSegment entries) into
the shared in-memory priority queue, where it stays resident until
delivery. With many sealed buckets this pins buckets x ~120KB of heap
for timestamps that are far in the future.
Load segments lazily instead: a sealed bucket keeps only the earliest
timestamp of its next unloaded segment resident, and the segment is
fetched from BookKeeper on the dispatch round where it becomes due.
While a snapshot creation is still in flight, its segments are served
from the in-memory list, so delivery of a freshly sealed bucket does not
wait for the BK persist.
- MutableBucket no longer queues the first segment and seals buckets
with currentSegmentEntryId = 0 ("no segment resident"); the full
segment list stays resident until the create completes, keeping the
failed-create downgrade path intact
- getScheduledMessages loads due segments upfront (single BK read in
flight, re-triggered on completion); the segment-boundary map
snapshotSegmentLastIndexMap is no longer needed and is removed
- nextDeliveryTime accounts for unloaded segments' timestamps so the
timer still fires in time
- recovery restores metadata/bitmaps only and arms buckets lazily
- a drained bucket (every segment loaded, no tracked position left) has
its snapshot deleted from a dispatch round, replacing the former
terminal-load cleanup; a failed delete is retried on later rounds
- merge eligibility keeps the eager-loading semantics: a lazy bucket
counts as if its first segment were loaded
Assisted-by: Claude Code
nodece
force-pushed
the
lazy-load-first-bucket-segment
branch
from
November 24, 2026 12:51
781d021 to
23fa1e6
Compare
… bucket tracker nextDeliveryTime scanned every bucket to include unloaded segments' timestamps, which addMessage reaches via updateTimer on the hot write path: ~260us with 6000 sealed buckets, tens of CPU-cores at high publish rates. Cache the minimum under the tracker lock and invalidate it at every head-changing event (bucket added/removed, segment loaded, recovery). getScheduledMessages also uses the cached minimum to skip the per-bucket scan entirely while the earliest unloaded segment is still in the future. With 5999 buckets / 600k messages (JMH + probe): - nextDeliveryTime: 40ns vs 42ns on master (was 260us uncached) - shared queue residency: ~3.5KB vs 15.3MB on master - addMessage / getScheduledMessages / mixed throughput: on par Assisted-by: Claude Code
…ents are loaded The single-flight segment load let a round deliver whatever was already resident (e.g. the mutable tail) while earlier positions of the same due window were still being fetched, so positions with equal deliverAt could be returned out of order across rounds. testOrderingDispatch (a Shared-subscription e2e test asserting position order) caught this. Arm the loads of every due bucket together and gate the round on the whole batch: once it settles, the re-triggered round sees every source due at that cutoff in the shared queue and returns them position- ordered, as eager loading did. Side effects: - getScheduledMessages early-returns a mutable TreeSet (callers may addAll into the result) - the drained-bucket delete now also self-heals a cursor property whose removal failed (retried from dispatch rounds) instead of waiting for tracker recreation - metrics: pulsar_delayed_message_index_loaded now only counts the mutable tail while nothing is due (sealed buckets hold no resident segment), test updated accordingly, and its topic-level metric is no longer read from the bucket_total series Assisted-by: Claude Code
Remove an unused import and give the new containsLedger javadoc a summary sentence. Assisted-by: Claude Code
Owner
Author
测试结果 vs masterJMH(80/20,initialMessages=8000,M1 Pro,方向性数据):
内存探针(5999 桶 / 60 万条,不封顶):
CI:43/43 绿。 |
- name the cache sentinels (MIN_UNLOADED_DIRTY uses Long.MIN_VALUE, MIN_UNLOADED_NONE) instead of bare -2/-1 - split loadDueSegments into loadNextSegment / serveResidentSegment / loadSegmentFromStorage, keeping the arm-all-due-batches semantics - move the merge-eligibility "lazy bucket counts as one loaded segment" folding into ImmutableBucket.mergeEligibilityLoadedSegments No behavior change. Assisted-by: Claude Code
… is in the future The loadDueSegments fast path skips the per-bucket scan as soon as the cached minimum unloaded timestamp lies in the future — which also starved the drained-bucket cleanup that only happens inside that scan. A drained bucket's snapshot (BookKeeper data, cursor property, memory bookkeeping) could then linger for as long as the longest remaining delay of any other bucket. Track the buckets whose segments are all loaded in a set: the fast path takes effect only while that set is empty, so fully loaded buckets keep being examined for drained cleanup. The set is maintained where segment pointers advance, buckets are removed, and recovery detaches everything. Reproduced by testDrainedBucketDeletedWhileAnotherBucketHasFutureSegments. Assisted-by: Claude Code
loadDueSegments armed the loads of every due bucket at once. In the catch-up burst the lazy loading targets (thousands of sealed buckets becoming due together, e.g. after a restart) that issues every BookKeeper read simultaneously and lets the slowest one of the batch hold back the delivery of the whole round. Arm at most MAX_ARMED_SEGMENT_LOADS_PER_ROUND storage reads per round; loadDueSegments reports whether due segments were left unarmed and getScheduledMessages delivers nothing until they are armed by the rounds the settling batch re-triggers — the ordering guarantee needs every source of a due window resident before a round pops. Also guard the failed-create downgrade: a bucket whose snapshot delete has already claimed it (trim/clear) must not have its segments re-queued by the create failure, and document the one-segment merge-eligibility difference for recovered buckets. New regression test: resident-segment delivery followed by a failing create must not deliver anything twice. Assisted-by: Claude Code
…merge eligibility The failed-create guard now logs when it refuses to re-queue a bucket that a delete already claimed or that was replaced in the range map, so the silent skip is observable instead of dropping tracked positions without a trace. mergeEligibilityLoadedSegments documents that a bucket recovered with k skipped due segments is eligible one segment earlier than the eager baseline, which is safe because merging reads every segment from storage. Assisted-by: Codex
…ment catch-up The batch gate held every position of a dispatch round until the whole due window was resident: one slow segment read delayed the entire round, and a large catch-up (e.g. after a restart) delivered nothing until every due segment across all buckets had loaded. Replace it with a timestamp barrier: positions strictly below the earliest unloaded or in-flight segment cannot be overtaken, so they are delivered while the rest loads, preserving timestamp order (equal deliverAt values still wait for the barrier). The loadDueSegments scan now rotates its start so a due batch spreads across buckets instead of letting the leading buckets monopolize the per-round load cap. Assisted-by: Codex
… ordering Four dispatch-round behaviors of the lazy loading had no regression coverage: - testSegmentLoadFailureIsRetriedAndDeliveryResumes: a failed segment read is re-armed by the next round (the failed future must not stay in pendingLoads) and delivery resumes once the retry succeeds; - testPendingSegmentLoadOnlyBlocksLaterTimestamps: an in-flight load holds back only positions at or after its earliest timestamp, earlier resident ones keep being delivered; - testArmedSegmentLoadsAreLimitedAndRotatedPerRound: a round arms at most maxArmedSegmentLoadsPerRound storage reads and the scan start rotates, so the first three armed reads span three two-segment buckets instead of draining the first bucket; the limit is now @VisibleForTesting-injectable; - testEqualDeliverAtWaitsForTheSegmentBarrier: a position whose deliverAt equals the earliest timestamp of an unloaded segment waits for its load, preserving position order for equal timestamps. Each behavior was verified by an isolated revert turning its test red. Assisted-by: Claude Code
…ck's injection slot testPermanentlyFailedSegmentHoldsBackOnlyLaterTimestamps: a segment whose read keeps failing is retried by every later dispatch round and holds back positions at or after its earliest timestamp — its own messages and a later resident position stay tracked — while an earlier resident timestamp keeps being delivered. Removing the timestamp barrier turns the test red. testSegmentLoadFailureIsRetriedAndDeliveryResumes now uses the existing injectGetSegmentException slot of MockBucketSnapshotStorage instead of a local subclass. Assisted-by: Claude Code
…d cleanup and clears - A round now serves every due resident segment of a bucket, not one: a deliverAt spanning several segments delivered nothing (the barrier held the equal timestamps back), armed no load, and nothing triggered a later round. - The drained-bucket check moved from the load scan to after the delivery loop, keyed by the ledgers the round popped: the round that delivers the last position is the only one that can detect the drained bucket, because the timer stops once nothing is due. A failed drained delete is retried by a later round through a dedicated retry set, which is empty while deletes succeed, so the load-scan fast path no longer degrades to a full scan. - The fullyLoadedBuckets set is gone: load completions could re-add buckets that a concurrent merge or trim had already removed, leaking them and permanently disabling the fast path. - The failed-create downgrade re-queues only the segments that were not served yet: re-queuing the served ones left duplicates in the shared queue that no later round removes once the index is empty. - The drained delete runs through trackDelete, so clear() waits for it instead of issuing a second delete for the same bucket. Each fix has a regression whose isolated revert turns it red. Assisted-by: Claude Code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Motivation
Sealing a mutable bucket eagerly copies the first snapshot segment (up to
delayedDeliveryMaxIndexesPerBucketSnapshotSegmententries × 24B ≈ 120KB per bucket) intosharedBucketPriorityQueue, where it stays resident until delivery. For topics with many sealed buckets (e.g. 150M all-delayed messages ≈ 3000 buckets) this pins hundreds of MB of heap for timestamps far in the future, even though only a small time window around "now" is ever deliverable.Changes
MutableBucketno longer queues the first segment; a sealed bucket starts withcurrentSegmentEntryId = 0("no segment resident") and keeps onlyfirstScheduleTimestampsin memory. The full segment list stays resident until the snapshot create completes, so the failed-create downgrade still re-queues everything (logged when a delete has already claimed the bucket and the re-queue is skipped).getScheduledMessagesarms the loads of every bucket whose earliest unloaded timestamp is due, at mostMAX_ARMED_SEGMENT_LOADS_PER_ROUNDstorage reads per round, with a rotating scan start so a large catch-up does not let the leading buckets monopolize the rounds. While a create is still in flight, segments are served from the resident in-memory list, so delivery of a freshly sealed bucket does not wait for the BK persist.nextDeliveryTimeaccounts for the unloaded segments' timestamps (cached minimum, invalidated on every head-changing event), otherwise the wheel timer would never fire to trigger the load.deliverAtvalues wait for the barrier, so the position order eager loading gave for equal timestamps is preserved without holding the whole round back.snapshotSegmentLastIndexMap(the segment-boundary detection) is removed entirely.Behavior changes / trade-offs
isDelayedDeliveryDeliverAtTimeStrict=true) adds the read latency to the first message of each window.pulsar_delayed_message_index_loadednow counts only the resident positions (mutable tail plus loaded segments), so while nothing is due it is near zero instead of tracking every bucket's first segment.BucketDelayedDeliveryTest#testBucketDelayedIndexMetricswas updated accordingly.Testing
./gradlew :pulsar-broker:test --tests "org.apache.pulsar.broker.delayed.*" --tests "org.apache.pulsar.broker.service.persistent.BucketDelayedDeliveryTest"— 170 tests green, including failure paths (create-fail downgrade incl. after resident delivery, load retry, merge-create failure, delete retry), drained-bucket deletion while other buckets' segments are far in the future, and progressive catch-up../gradlew :pulsar-broker:test --tests "org.apache.pulsar.broker.delayed.*" --tests "org.apache.pulsar.broker.service.persistent.BucketDelayedDeliveryTest"— 170 tests green, including failure paths (create-fail downgrade incl. after resident delivery, load retry, merge-create failure, delete retry), drained-bucket deletion while other buckets' segments are far in the future, and progressive catch-up.testSegmentLoadFailureIsRetriedAndDeliveryResumes— a failed segment read is re-armed by the next round and delivery resumes once the retry succeeds;testPermanentlyFailedSegmentHoldsBackOnlyLaterTimestamps— a segment whose read keeps failing is retried by every later round and holds back only positions at or after its earliest timestamp, while earlier resident ones keep being delivered;testDrainedBucketIsDeletedInTheRoundThatDeliversTheLastPosition— the round that delivers the last position starts the drained-bucket delete itself, without a later round to drive it;testAllDueResidentSegmentsAreServedInOneRound— a deliverAt spanning several resident segments has all of them served in one round, so the round is not stranded delivering nothing;testFailedCreateRequeueSkipsAlreadyServedSegments— the failed-create downgrade re-queues only the unserved segments, leaving no duplicates in the shared queue;testClearWaitsForAnInFlightDrainedBucketDelete— the drained delete runs throughtrackDelete, so a concurrentclear()waits instead of deleting the same bucket again;testPendingSegmentLoadOnlyBlocksLaterTimestamps— an in-flight load holds back only positions at or after its earliest timestamp; earlier resident ones keep being delivered;testArmedSegmentLoadsAreLimitedAndRotatedPerRound— a round arms at mostmaxArmedSegmentLoadsPerRoundstorage reads (now@VisibleForTesting-injectable) and the scan start rotates across buckets;testEqualDeliverAtWaitsForTheSegmentBarrier— a position whose deliverAt equals the earliest timestamp of an unloaded segment waits for its load, preserving position order.Assisted-by: Claude Code