Skip to content

[fix][broker] Manage in-flight bucket work during clear - #26401

Merged
merlimat merged 5 commits into
apache:masterfrom
nodece:fix-bucket-async-races
Oct 22, 2026
Merged

merlimat merged 5 commits into
apache:masterfrom
nodece:fix-bucket-async-races

Conversation

@nodece

@nodece nodece commented Aug 21, 2026 •

Copy link
Copy Markdown
Member

Motivation

BucketDelayedDeliveryTracker.clear() can finish while bucket work is still in flight. Callers such as clear-backlog, and the cursor reset in #26420, rely on clear() as the point where the old delayed state is gone.

  • Late segment load. On master, clear() only waits for trimFuture. A segment load that is still running re-adds pre-clear indexes to sharedBucketPriorityQueue after the reset.
  • Untracked deletes. Snapshot deletes from recovery, merge and terminal segment loads are not waited for, so clear() returns while they are still running.
  • Failed deletes are lost. A failed delete is forgotten: the bucket is already out of immutableBuckets, so no later clear() retries it.
  • Failed merges leave sources behind. When a merged snapshot creation fails, the source buckets drop out of immutableBuckets but keep their snapshots. clear() can't find them, and a restart recovers them again.
  • Recovery fails on stale properties. Recovery's instanceof BucketNotExistException check never matches, because the exception arrives wrapped in a CompletionException. A stale cursor property therefore fails recovery instead of being removed.

Modifications

  • What clear() waits for. It waits for the trim/merge chain, the current pendingLoad and every tracked snapshot delete before resetting in-memory state.
  • Tracked deletes. Deletes from recovery, merge, terminal segment loads and clear() itself go through trackDelete(bucket, future).
    • A failed delete puts its bucket in uncleanedBuckets, and so do the sources of a failed merge.
    • clear() deletes those buckets too. While that cleanup fails, clear() fails, and the next clear() retries.
  • Delivery is not held by deletes. The terminal-segment delete is tracked separately rather than chained into pendingLoad, so getScheduledMessages() keeps delivering while it runs.
  • Merge failures. Merge source deletes are part of the merge future. They are skipped when the merged creation fails, so the source buckets stay recoverable.
  • Recovery. It unwraps the CompletionException before matching BucketNotExistException.

Fencing work that starts after clear() has begun, and revalidating trim/merge ownership, are left to a follow-up (see #26280).

Verifying this change

BucketDelayedDeliveryTrackerTest adds deterministic tests that use gated storage. They cover:

  • a load in flight
  • a terminal delete in flight, and delivery continuing while it runs
  • merge load, create and delete
  • a failing delete that is awaited, fails clear(), and is retried by the next clear()
  • clear() after a failed merge
  • recovering after a residual snapshot or property

All org.apache.pulsar.broker.delayed.* tests pass (110). The four new tests fail without the change.

@nodece

nodece commented Aug 21, 2026

Copy link
Copy Markdown
Member Author

Ping @void-ptr974 @Denovo1998

@void-ptr974

void-ptr974 commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for the fix. I think there are two edge cases that may still need attention.

  1. Merge snapshot creation failure followed by clear/restart

For example, suppose buckets [1,5] and [6,10] are being merged into [1,10]. If creating the [1,10] snapshot fails, the source bucket delete chain is skipped. At that point [1,5] and [6,10] may already have been removed from immutableBuckets, but their cursor properties can still remain.

A later clear() only cleans the buckets currently reachable from immutableBuckets, so those source bucket properties may not be removed. If the tracker is recreated with the same cursor/storage, the old [1,5] and [6,10] buckets can be recovered again.

  1. Conditional cursor-property removal with BadVersion retry

For example, suppose a stale delete is deleting bucket key #pulsar.internal.delayed.bucket_1_5 with old bucket id 0. removeBucketCursorPropertyIfCurrent() first reads the property and sees 0, so it proceeds to remove it. Before the remove succeeds, another operation recreates the same bucket key with new bucket id 999. The first remove attempt then hits BadVersionException.

The retry is only for removeCursorProperty(), so it does not re-read the current value. It can remove the property even though it now points to bucket id 999, which means the recreated bucket cursor property can still be removed.

@nodece
nodece marked this pull request as draft August 24, 2026 03:54
@nodece
nodece force-pushed the fix-bucket-async-races branch from 33d7c2c to 7f22e56 Compare August 24, 2026 04:56
@nodece nodece changed the title [fix][broker] Fix async races in bucket delayed delivery tracker [fix][broker] Manage in-flight bucket work during clear Aug 24, 2026
@nodece
nodece marked this pull request as ready for review August 24, 2026 05:03
@nodece nodece closed this Aug 24, 2026
@nodece nodece reopened this Aug 24, 2026
@nodece
nodece requested review from Denovo1998, dao-jun and lhotari and removed request for Denovo1998 August 24, 2026 05:03
@nodece nodece added this to the 5.0.0-M2 milestone Aug 24, 2026
@nodece nodece self-assigned this Aug 24, 2026
nodece added 2 commits August 24, 2026 21:25
The BucketNotExist branch in handleRecoverBucketSnapshotEntry never
matched: dependent future stages wrap the checked exception in a
CompletionException, so a stale cursor property pointing to a deleted
snapshot failed the whole recovery instead of being cleaned up.
Unwrap before the check so the bucket is deleted and the property is
removed, like the path was designed to do.

Also make MockBucketSnapshotStorage re-readable (parse from a slice,
same as the metadata read) and add recreate-tracker tests for both
cleanup-failure shapes: consistent snapshot+property residue loads
normally, property-only residue is removed on recovery.
A failed merged-bucket creation completes with the INVALID_BUCKET_ID
sentinel, so the source-delete chain still ran and deleted the source
snapshots although their ledger ranges were already removed from
immutableBuckets - after a restart the only durable delayed-index
state for those ranges was gone. Skip the source deletes when the
merged creation failed, so the source buckets stay recoverable from
their cursor properties.

@lhotari lhotari left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for working on this fix. Waiting for in-flight loads and deletes in clear() is the right direction, and the gated-storage tests show the waits deterministically.

One production point and two small test points are below.

On the #26420 question: this change makes clear() wait for the load that is in flight when it is called, including the state it publishes and its terminal snapshot delete. It also waits for the trim/merge chain and for tracked deletes. A load that starts after the captured one completes, and before the cleanup takes the tracker lock, is still not covered. That is the open generation/fencing discussion on clear(), so I am not repeating it here.

@codelipenghui codelipenghui left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Based on 97817549a80, I'd suggest:

  • Keep pendingLoad limited to index loading/publication. Track deletes separately by bucket identity, retaining failed cleanup for retry.
  • During clear(), fence new bucket work and preserve incoming delayed positions. Await existing load/create/merge callbacks, then drain the cleanup they scheduled.
  • Reset old state and resume only after cleanup succeeds; otherwise fail clear() and remain fenced until retry—an explicit availability tradeoff.

This avoids blocking ready deliveries on terminal deletion while establishing a clear boundary for old tracker work.

…bucket-clear-inflight

# Conflicts:
#	pulsar-broker/src/main/java/org/apache/pulsar/broker/delayed/bucket/BucketDelayedDeliveryTracker.java
…y failed cleanup in clear()

- The terminal-segment snapshot delete no longer holds pendingLoad, so
  getScheduledMessages() keeps delivering while it runs; clear() still
  waits for it through pendingDeletes.
- A failed tracked delete, and the source buckets of a failed merge, are
  kept and deleted by the next clear(). clear() fails while that cleanup
  fails, instead of reporting success.
- Tests: deterministic failing-delete test, delivery not blocked by the
  terminal delete, clear() after a failed merge, == 0 bucket assertion,
  storage closed in finally.
@merlimat

Copy link
Copy Markdown
Contributor

Thanks @nodece. I picked this up as part of the open-PR backlog triage, merged master (no rebase) and pushed one commit on top:

  • Merge with master. [fix][broker] Recover bucket delayed delivery tracker asynchronously to avoid blocking dispatcher threads #26105 moved recovery into the async recoverBucketSnapshot0(). The recovery delete is now tracked inside that block.
  • Terminal delete (@lhotari). It goes through trackDelete(...) and no longer holds pendingLoad, so delivery doesn't wait on cleanup I/O, and a failed delete isn't counted as a load failure. testTerminalSegmentLoadDeleteDoesNotBlockDelivery covers it.
  • Failed cleanup (@Denovo1998). A failed tracked delete is kept, along with the source buckets of a failed merge, and the next clear() deletes them. While that cleanup keeps failing, clear() fails instead of reporting success, so [fix][broker] Clear delayed delivery state before resetting the cursor #26420 can rely on it. Master already fails clear() when deleting a bucket it still tracks fails.
  • Tests.
    • The failing-delete test is now gated and checks both the failure and the retry.
    • New: clear() after a failed merge.
    • == 0 after clear().
    • storage.close() moved into finally.

Fencing work that starts after clear() has begun is still left to the follow-up.

@merlimat
merlimat merged commit 865e9be into apache:master Oct 22, 2026
44 checks passed
lhotari pushed a commit that referenced this pull request Oct 22, 2026
nodece added a commit to nodece/pulsar that referenced this pull request Nov 18, 2026
resetCursorInternal() reset the cursor without touching the delayed
delivery tracker, although a reset moves the consumption baseline the
tracker state was derived from: bucket snapshots, index bits and queued
entries from before the reset survived into the replay, and in-flight
trims/loads/deletes could race the replayed state. Clear the delayed
messages and wait for the clear to settle after disconnecting consumers
and before asyncResetCursor, with the whole reset flow chained into a
single error path. Without a dispatcher, clean the residual bucket
snapshots like the unsubscribe path does, so a later consumer reconnect
cannot recover pre-reset buckets from the cursor properties.

Review-feedback follow-ups folded in: restore the disconnect-failure
branch (SubscriptionBusyException / HTTP 412, resetCloseFuture on both
outcomes), unwrap CompletionException in the terminal error path so
typed exceptions pass through unwrapped, and await the clear via
thenCompose so the reset only starts after the clear settles (a handle()
stage does not flatten a returned future, which let asyncResetCursor
race the bucket cursor-property writes and fail with BadVersion).

Rebased onto master: preserves the nonDurableCursorCleanupStarted guard,
lastCursorResetFuture publication, and the compaction fallback to
forceReset=false from intervening commits; inherits apache#26401, which made
BucketDelayedDeliveryTracker.clear() also wait for in-flight segment
loads and deletes.

Assisted-by: Claude Code
nodece added a commit to nodece/pulsar that referenced this pull request Nov 18, 2026
Fix delayed-delivery bucket trim and segment-loading races that could
stall progress or break cleanup:

- In getScheduledMessages(), process the snapshot-segment boundary
  transition before dropping an orphaned tail entry, while still
  suppressing delivery of that orphaned entry. Previously the orphan
  check ran before the cutoff check, so a segment whose tail entry
  lived below the first live ledger never advanced its boundary and
  the next snapshot segment was never loaded. Cutoff gating is kept:
  the next segment is not loaded before the cutoff and is loaded once
  the cutoff is reached.
- Remove the INVALID_BUCKET_ID sentinel: a failed snapshot creation now
  propagates through the create future's exceptional completion, and
  ImmutableBucket.resolveBucketIdForDelete() converts it into
  "nothing to delete" so the sequential trim chain keeps going instead
  of failing on a failed create. The no-create-future path resolves the
  bucket id through a failed CompletableFuture instead of throwing
  synchronously, and the merged-bucket terminal keeps the source
  snapshots (keepUncleaned) when the merged creation fails.
- deleteBucketSnapshot() revalidates range-to-bucket ownership before
  starting the delete and again before removing tracker state, so a
  bucket replaced while the delete is in flight is neither deleted nor
  scrubbed twice.

The reset-cursor changes previously carried in this PR moved to apache#26420,
which owns the reset path and its delayed-state cleanup semantics.

Rebased onto master: clear() waiting for in-flight segment loads and
pending deletes, and the tracked snapshot deletes on every path, are
now provided by apache#26401 and are not duplicated here.

Assisted-by: Claude Code
nodece added a commit to nodece/pulsar that referenced this pull request Nov 20, 2026
resetCursorInternal() reset the cursor without touching the delayed
delivery tracker, although a reset moves the consumption baseline the
tracker state was derived from: bucket snapshots, index bits and queued
entries from before the reset survived into the replay, and in-flight
trims/loads/deletes could race the replayed state. Clear the delayed
messages and wait for the clear to settle after disconnecting consumers
and before asyncResetCursor, with the whole reset flow chained into a
single error path. Without a dispatcher, clean the residual bucket
snapshots like the unsubscribe path does, so a later consumer reconnect
cannot recover pre-reset buckets from the cursor properties.

Review-feedback follow-ups folded in: restore the disconnect-failure
branch (SubscriptionBusyException / HTTP 412, resetCloseFuture on both
outcomes), unwrap CompletionException in the terminal error path so
typed exceptions pass through unwrapped, and await the clear via
thenCompose so the reset only starts after the clear settles (a handle()
stage does not flatten a returned future, which let asyncResetCursor
race the bucket cursor-property writes and fail with BadVersion).

Rebased onto master: preserves the nonDurableCursorCleanupStarted guard,
lastCursorResetFuture publication, and the compaction fallback to
forceReset=false from intervening commits; inherits apache#26401, which made
BucketDelayedDeliveryTracker.clear() also wait for in-flight segment
loads and deletes.

Assisted-by: Claude Code
nodece added a commit to nodece/pulsar that referenced this pull request Nov 24, 2026
resetCursorInternal() reset the cursor without touching the delayed
delivery tracker, although a reset moves the consumption baseline the
tracker state was derived from: bucket snapshots, index bits and queued
entries from before the reset survived into the replay, and in-flight
trims/loads/deletes could race the replayed state. Clear the delayed
messages and wait for the clear to settle after disconnecting consumers
and before asyncResetCursor, with the whole reset flow chained into a
single error path. Without a dispatcher, clean the residual bucket
snapshots like the unsubscribe path does, so a later consumer reconnect
cannot recover pre-reset buckets from the cursor properties.

Review-feedback follow-ups folded in: restore the disconnect-failure
branch (SubscriptionBusyException / HTTP 412, resetCloseFuture on both
outcomes), unwrap CompletionException in the terminal error path so
typed exceptions pass through unwrapped, and await the clear via
thenCompose so the reset only starts after the clear settles (a handle()
stage does not flatten a returned future, which let asyncResetCursor
race the bucket cursor-property writes and fail with BadVersion).

Rebased onto master: preserves the nonDurableCursorCleanupStarted guard,
lastCursorResetFuture publication, and the compaction fallback to
forceReset=false from intervening commits; inherits apache#26401, which made
BucketDelayedDeliveryTracker.clear() also wait for in-flight segment
loads and deletes.

Assisted-by: Claude Code
nodece added a commit to nodece/pulsar that referenced this pull request Nov 24, 2026
resetCursorInternal() reset the cursor without touching the delayed
delivery tracker, although a reset moves the consumption baseline the
tracker state was derived from: bucket snapshots, index bits and queued
entries from before the reset survived into the replay, and in-flight
trims/loads/deletes could race the replayed state. Clear the delayed
messages and wait for the clear to settle after disconnecting consumers
and before asyncResetCursor, with the whole reset flow chained into a
single error path. Without a dispatcher, clean the residual bucket
snapshots like the unsubscribe path does, so a later consumer reconnect
cannot recover pre-reset buckets from the cursor properties.

Review-feedback follow-ups folded in: restore the disconnect-failure
branch (SubscriptionBusyException / HTTP 412, resetCloseFuture on both
outcomes), unwrap CompletionException in the terminal error path so
typed exceptions pass through unwrapped, and await the clear via
thenCompose so the reset only starts after the clear settles (a handle()
stage does not flatten a returned future, which let asyncResetCursor
race the bucket cursor-property writes and fail with BadVersion).

Rebased onto master: preserves the nonDurableCursorCleanupStarted guard,
lastCursorResetFuture publication, and the compaction fallback to
forceReset=false from intervening commits; inherits apache#26401, which made
BucketDelayedDeliveryTracker.clear() also wait for in-flight segment
loads and deletes.

Assisted-by: Claude Code
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants