Skip to content

[improve][broker] Load delayed message index segments lazily - #42

Open
nodece wants to merge 12 commits into
masterfrom
lazy-load-first-bucket-segment
Open

nodece wants to merge 12 commits into
masterfrom
lazy-load-first-bucket-segment

Conversation

@nodece

@nodece nodece commented Nov 24, 2026 •

Copy link
Copy Markdown
Owner

Motivation

Sealing a mutable bucket eagerly copies the first snapshot segment (up to delayedDeliveryMaxIndexesPerBucketSnapshotSegment entries × 24B ≈ 120KB per bucket) into sharedBucketPriorityQueue, 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

  • Lazy seal: MutableBucket no longer queues the first segment; a sealed bucket starts with currentSegmentEntryId = 0 ("no segment resident") and keeps only firstScheduleTimestamps in 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).
  • Due-driven loading: getScheduledMessages arms the loads of every bucket whose earliest unloaded timestamp is due, at most MAX_ARMED_SEGMENT_LOADS_PER_ROUND storage 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.
  • Timer correctness: nextDeliveryTime accounts for the unloaded segments' timestamps (cached minimum, invalidated on every head-changing event), otherwise the wheel timer would never fire to trigger the load.
  • Progressive delivery behind a timestamp barrier: positions strictly below the earliest unloaded or in-flight segment cannot be overtaken and are delivered while the rest of a catch-up loads; equal deliverAt values wait for the barrier, so the position order eager loading gave for equal timestamps is preserved without holding the whole round back.
  • Simplification: snapshotSegmentLastIndexMap (the segment-boundary detection) is removed entirely.
  • Recovery: restores metadata/bitmaps only; buckets are armed lazily. Fully-due buckets are still deleted during recovery.
  • Drained cleanup: a bucket whose segments are all loaded and whose tracked positions are all delivered has its snapshot deleted from a dispatch round (replacing the former "terminal segment load" cleanup); failed deletes are retried on later rounds, and a drained bucket is deleted even when every other bucket's next unloaded segment lies in the future.

Behavior changes / trade-offs

  • Each segment's first message waits for one BookKeeper read when its window becomes due; with the barrier a slow read only holds back positions at or after its timestamp, not the whole round. In the default (non-strict) mode the cutoff already includes one tick of lookahead, so the load is issued ahead of the due time; strict mode (isDelayedDeliveryDeliverAtTimeStrict=true) adds the read latency to the first message of each window.
  • While BookKeeper is entirely unavailable, eager loading keeps delivering the segments that were already resident at seal time, whereas lazy loading stops once the resident windows drain — the flip side of not keeping them in memory. (The head-of-line semantics themselves match eager loading: a persistently unreadable segment blocks later timestamps in both designs.)
  • During a large catch-up (e.g. restart with thousands of due buckets), loads are armed in batches of at most 256 reads and delivery progresses behind the barrier — no burst of concurrent reads, and earlier timestamps keep flowing while later windows load.
  • pulsar_delayed_message_index_loaded now 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#testBucketDelayedIndexMetrics was 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.
  • Dispatch-round behaviors of the lazy loading, each verified by an isolated revert turning its test red:
    • 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 through trackDelete, so a concurrent clear() 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 most maxArmedSegmentLoadsPerRound storage 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.
  • A/B vs master (JMH + residency probe): throughput on par, shared-queue residency 15.3 MB → ~3.5 KB at 5999 sealed buckets — see the benchmark comment.

Assisted-by: Claude Code

@github-actions github-actions Bot added the PIP label Nov 24, 2026
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
nodece force-pushed the lazy-load-first-bucket-segment branch from 781d021 to 23fa1e6 Compare November 24, 2026 12:51
… 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
@nodece

nodece commented Nov 25, 2026 •

Copy link
Copy Markdown
Owner Author

测试结果 vs master

JMH(80/20,initialMessages=8000,M1 Pro,方向性数据):

benchmark master PR
nextDeliveryTime 16T 14.38M ops/s 14.32M ops/s
containsMessage 8T 5.59M ops/s 5.87M ops/s
getScheduledMessages 2T 1.33M ops/s 1.62M ops/s
addMessage 4T 1.70k ops/s 1.92k ops/s
高竞争混合 32T 7.51k ops/s 7.69k ops/s
单线程混合 1T 9.42k ops/s 9.41k ops/s

内存探针(5999 桶 / 60 万条,不封顶):

指标 master PR
共享队列驻留 599,900 条 / 15.3MB 0 条 / 3.5KB
nextDeliveryTime 单次 42ns 76ns

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant