Skip to content

[fix][broker] Fix bucket snapshot trim and segment loading - #26280

Closed
nodece wants to merge 3 commits into
apache:masterfrom
nodece:fix-bucket-trim-and-loading
Closed

nodece wants to merge 3 commits into
apache:masterfrom
nodece:fix-bucket-trim-and-loading

Conversation

@nodece

@nodece nodece commented Aug 6, 2026 •

Copy link
Copy Markdown
Member

Motivation

Fix delayed-delivery bucket recovery and trim races that could stall progress or break cleanup:

  • Segment-boundary advancement could be skipped when the current tail entry is orphaned (ledger below first live ledger), leaving the next snapshot segment unloaded: the orphan check ran before the cutoff check, so a segment whose tail entry lived below the first live ledger never advanced its boundary.
  • Trim/delete could race with snapshot creation and bucket-id resolution, including failed-create and missing/malformed cursor-property paths.
  • The INVALID_BUCKET_ID sentinel blurred the create-future's outcome: callers had to inspect the completed value for -1, and an unhandled exceptional completion could stop the sequential trim chain.

Modifications

  • In getScheduledMessages(), process the snapshot-segment boundary transition before dropping an orphaned tail entry, while still suppressing delivery of that orphaned entry. A bucket that spans the first live ledger still advances its segment boundary when its tail entry is orphaned. Cutoff gating is kept: the next segment is not loaded before the cutoff and is loaded once the cutoff is reached.
  • Removed the INVALID_BUCKET_ID sentinel. A failed snapshot creation now propagates through the create future's exceptional completion (whenComplete in afterCreateImmutableBucket), and consumers handle it explicitly:
    • ImmutableBucket.resolveBucketIdForDelete() converts a failed creation into Optional.empty() ("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;
    • the merged-bucket terminal keeps the source snapshots (keepUncleaned) when the merged creation fails, so their delayed indexes stay recoverable and clear() deletes them.
  • deleteBucketSnapshot() delegates the snapshot lifecycle to ImmutableBucket.asyncDeleteBucketSnapshot() and 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 trim chain intentionally waits for an in-flight snapshot creation whose bucket it selected (the bucket id is only known after creation) rather than skipping it; the chain stays serialized through trimFuture so clear() observes a single ordered chain.

Out of scope: the resetCursor delayed-state cleanup that this PR originally carried is now owned by
#26420 (a separate open PR, rebased on the same master; nothing from it is in apache/master yet). This
PR deliberately no longer touches PersistentSubscription — the reset behavior is not lost, it lands
through #26420, and these two PRs are meant to be reviewed and merged as a pair.

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

Verifying this change

  • Make sure that the change passes the CI checks.

This change added tests and can be verified as follows (BucketDelayedDeliveryTrackerTest):

  • testLoadsNextSnapshotSegmentAfterCutoff: after recovery with a mark-delete position inside the bucket, advancing past the cutoff loads the next snapshot segment. This fails on master without the boundary-advancement fix.
  • testDoesNotLoadNextSnapshotSegmentBeforeCutoff: the next segment is not loaded before the cutoff is reached.
  • testTrimSkipsFailedSnapshotCreation: blocks the first bucket's snapshot creation, triggers the trim while the bucket id is unavailable, then fails the creation — the trim chain must not stop and every orphaned bucket is still cleaned up. Locks the failed-create behavior across the sentinel removal.

The pre-existing testClearWaitsForInFlightSegmentLoad (from #26401) and testTrimWaitsForInFlightSnapshotCreation cover the wait-for-create and clear-waits-load interactions on the rebased code.

Does this pull request potentially affect one of the following parts:

Check the boxes that apply

  • Dependencies (add or upgrade a dependency)
  • The public API
  • The schema
  • The default values of configurations
  • The threading model
  • The binary protocol
  • The REST endpoints
  • The admin CLI options
  • The metrics
  • Anything that affects deployment

@nodece

nodece commented Aug 6, 2026

Copy link
Copy Markdown
Member Author

@Denovo1998 Fix: #26251 (comment)

@void-ptr974 void-ptr974 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.

Two edge cases remain around resolving the bucket ID.

.orElseGet(() -> CompletableFuture.completedFuture(getAndUpdateBucketId()));

return bucketIdFuture.thenCompose(bucketId ->
executeWithRetry(() -> ctx.bucketSnapshotStorage().deleteBucketSnapshot(bucketId),

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.

Nice improvement to make deletion wait for snapshot creation; it closes the missing bucketId race. Two edge cases remain:

  1. If snapshot creation fails after trim has started, afterCreateImmutableBucket() resolves the future with INVALID_BUCKET_ID (-1), and this path calls deleteBucketSnapshot(-1). A storage failure would stop the sequential trim chain and skip the subsequent merge. Since no snapshot was persisted, storage deletion should be skipped while orphan-bucket cleanup continues.
  2. When no creation future exists, getAndUpdateBucketId() is evaluated before completedFuture() is created. A missing or malformed cursor property therefore throws synchronously. The failure should instead be propagated through the returned CompletableFuture so callers can handle it consistently.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Thanks for the detailed review. Addressed both points in the latest commits:

  1. asyncDeleteBucketSnapshot() now resolves bucket id via Optional and skips storage deletion when snapshot creation failed, so trim does not call deleteBucketSnapshot(-1) and the chain is not broken by the old sentinel path.
  2. The no-create-future path now catches getAndUpdateBucketId() failures and returns a failed CompletableFuture instead of throwing synchronously, so callers handle failures consistently through the async chain.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Both edge cases are handled in ImmutableBucket.resolveBucketIdForDelete() on the rebased head: a failed
create resolves to Optional.empty() so the storage delete is skipped and the sequential trim chain keeps
going, and the no-create-future path catches getAndUpdateBucketId() failures and returns a failed
CompletableFuture instead of throwing synchronously. testTrimSkipsFailedSnapshotCreation covers the
failed-create trim path.

}))
.orElseGet(() -> CompletableFuture.completedFuture(getAndUpdateBucketId()));

return bucketIdFuture.thenCompose(bucketId ->

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.

Waiting for snapshot creation here resolves the missing bucketId race condition, but the trim decision itself is made earlier in BucketDelayedDeliveryTracker.asyncTrimImmutableBuckets(). Once this future completes, the range is no longer revalidated—neither to confirm it is still orphaned nor to verify that the same bucket remains mapped to the selected range.

#26260 performed both checks after the snapshot‑create future completed, and this PR is intended to subsume that fix. In the current implementation, a cursor reset, backward movement of the mark‑delete position, or a bucket mapping change while snapshot creation is pending can make the original trim decision stale before storage deletion begins.

Could this lifecycle coordination be kept within the tracker—revalidating firstActiveLedgerId() and the exact range‑to‑bucket identity before starting deletion? Ideally, the ownership/eligibility guard should also cover the asynchronous delete completion before tracker state is removed.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Good point on stale trim decisions. The tracker now keeps lifecycle coordination in BucketDelayedDeliveryTracker: it revalidates exact range->bucket ownership before starting deletion and revalidates ownership again before removing tracker state in the async completion. This prevents deleting/removing state for a bucket that has been replaced while delete is in flight.

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.

Thanks for hardening the snapshot-create/delete path. One lifecycle issue remains: asyncTrimImmutableBuckets() decides eligibility before asyncDeleteBucketSnapshot() waits for snapshot creation. The new checks only revalidate range-to-bucket ownership, not whether the range is still eligible after that wait.

For example, bucket [1, 5] is selected when mark-delete is 100. A reset to 3 while creation is pending makes [3, 5] live again, but ownership is unchanged, so the current flow still deletes its snapshot and indexes. Reset replay may see the old index, skip reinsertion, and then lose it when the pending trim completes.

I recommend using mark-delete only for delivery filtering and managedLedger.getLedgersInfo().firstKey() for destructive snapshot/index trim. The retained-ledger boundary is monotonic across cursor resets: [1, 5] becomes removable only after the boundary advances to 6, when those positions are no longer readable. Keeping mark-delete as the destructive boundary instead requires reset/replay to be fenced against the entire async create/delete lifecycle, which the current tracker lifecycle does not provide.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The reset cursor race has been fixed. When the reset cursor, the dispatcher clear the tracker data and then the memory data is consistent.

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.

Thanks, the new fencing closes the stale-trim race. My concern is that it couples reset and consumer recovery to the snapshot lifecycle, since consumers are disconnected before clear() waits for trimFuture and bucket cleanup. In the worst case, a pending snapshot creation could prevent asyncResetCursor() from starting and keep the subscription fenced.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Usually, working well is enough. Pulsar is a big project that requires continuous improvement.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The rebased head revalidates range-to-bucket ownership in deleteBucketSnapshot() twice: before starting
the delete, and again in the completion before removing snapshotSegmentLastIndexMap entries, the bucket
range and the index bits. A bucket replaced while the delete is in flight is neither deleted nor scrubbed.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

You are right that isCurrentBucket covers ownership, not eligibility-after-wait. The full closure is at
the reset level rather than the trim level: #26420 makes a reset clear the tracker and wait for the
in-flight trim chain (which #26401 extended to loads and pending deletes) before asyncResetCursor, so
the reset replay always re-derives from a clean tracker instead of racing a stale index. Within this PR I
kept the trim-level ownership revalidation only, to avoid duplicating the reset semantics here.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fair concern — and the rebased head no longer couples them here: this PR no longer touches
PersistentSubscription; the reset path is owned by #26420, which documents the trade-off (a failed clear
WARNs and continues, so a reset never blocks indefinitely on snapshot I/O; a slow clear still does, which
is the documented latency trade-off). Thanks for pushing on this.

.attr("bucketKey", bucketKey)
.exception(ex)
.log("Failed to delete bucket snapshot");
CompletableFuture<Long> bucketIdFuture = getSnapshotCreateFuture()

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.

The PR description states that buckets with unfinished snapshot creation are skipped, but the current implementation instead waits for the creation future. Since asyncTrimImmutableBuckets() is part of the global trimFuture chain, a slow or stalled snapshot creation can keep trimFuture.isDone() false, which blocks subsequent trim/merge attempts and causes clear() to wait on the same future.

The latest commit also removed the prior isDone() filtering from asyncTrimImmutableBuckets(). Would it be safer to skip CREATING buckets and retrigger or rescan for trimming once creation finishes, rather than holding the global trim/merge gate? If waiting is intentional, we should at least define and test a bounded-completion guarantee.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Thanks, agreed this is important. The implementation keeps creation gating in the delete path and adds deterministic coverage to ensure we do not start deletion while create is blocked, then cleanup proceeds once create completes (testTrimDefersDeleteUntilSnapshotCreateCompletes). The trim/merge flow remains serialized by trimFuture intentionally so clear/trim observe a single ordered chain.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The description now says the trim chain waits for an in-flight creation whose bucket it selected —
the bucket id is only known after creation, and keeping the chain serialized through trimFuture means
clear() observes a single ordered chain. That is intentional; sorry the earlier description said "skip".

verify(localStorage, atLeastOnce()).getBucketSnapshotSegment(anyLong(), anyLong(), anyLong());
});
}

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.

The PR also addresses the snapshot-create/trim race condition mentioned in the motivation, though the new regression tests only cover snapshot-segment loading.

Could we add a deterministic trim test that:

  • Blocks createBucketSnapshot()
  • Triggers a trim while the bucket ID is still unavailable
  • Verifies that deletion does not begin prematurely
  • Then releases the snapshot creation and confirms that cleanup completes

It would also be useful to test revalidation when the bucket ceases to be orphaned while creation is pending. #26260 already includes deterministic coverage for both scenarios that could be adapted for this purpose.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Added deterministic tests for the requested race scenarios in BucketDelayedDeliveryTrackerTest:

  • testTrimDefersDeleteUntilSnapshotCreateCompletes
  • testTrimDeletesAfterCreateCompletesDespiteMarkDeleteChange

They block createBucketSnapshot(), trigger trim while bucket id is unavailable, verify no premature delete, then release create and assert cleanup behavior.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

testTrimSkipsFailedSnapshotCreation blocks the first bucket's snapshot creation
(BlockingFirstCreateStorage), triggers the trim while the bucket id is unavailable, verifies the first
bucket is still present (no premature delete), then fails the creation and asserts every orphaned bucket
is still cleaned up. testTrimWaitsForInFlightSnapshotCreation (pre-existing) covers the
deletion-after-create-completes ordering.

@nodece
nodece force-pushed the fix-bucket-trim-and-loading branch 2 times, most recently from 7182e42 to c55199e Compare August 11, 2026 09:27
@nodece
nodece requested review from Denovo1998 and void-ptr974 and a lite review from Copilot and removed request for Denovo1998 and void-ptr974 August 11, 2026 09:58

Copilot AI 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.

Pull request overview

This PR addresses correctness issues in the broker’s delayed-delivery “bucket snapshot” flow, particularly around recovery/segment transitions and trim/delete races that could stall progress or prevent cleanup.

Changes:

  • Adjust bucket snapshot segment loading behavior in getScheduledMessages() to handle segment-boundary transitions even when the tail entry is orphaned, while still suppressing delivery of that orphaned entry.
  • Harden snapshot delete/trim lifecycles (bucket-id resolution, ownership revalidation during delete, and reset-cursor sequencing with delayed-delivery cleanup).
  • Add regression tests covering cutoff-gated segment loading behavior.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 1 comment.

File Description
pulsar-broker/src/test/java/org/apache/pulsar/broker/delayed/bucket/BucketDelayedDeliveryTrackerTest.java Adds deterministic tests validating cutoff-gated snapshot segment loading behavior.
pulsar-broker/src/main/java/org/apache/pulsar/broker/service/persistent/PersistentSubscription.java Ensures cursor reset waits for delayed-delivery cleanup before proceeding.
pulsar-broker/src/main/java/org/apache/pulsar/broker/delayed/bucket/ImmutableBucket.java Hardens bucket-id resolution for snapshot deletion and avoids sync throws during delete path resolution.
pulsar-broker/src/main/java/org/apache/pulsar/broker/delayed/bucket/BucketDelayedDeliveryTracker.java Fixes segment transition behavior and strengthens trim/delete flow with revalidation checks.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@lhotari lhotari added this to the 5.0.0-M2 milestone Aug 14, 2026
Comment on lines 905 to 909
return bucket.getSnapshotCreateFuture().orElse(NULL_LONG_PROMISE)
.thenCompose(bucketId -> INVALID_BUCKET_ID.equals(bucketId)
.thenCompose(bucketId -> bucketId == null
? CompletableFuture.<Void>completedFuture(null)
: doDeleteBucketSnapshot(ledgerName, range, bucket));
}

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.

The failed-create path remains broken at the current head. snapshotCreateFuture now completes exceptionally because afterCreateImmutableBucket() uses whenComplete(), but the outer thenCompose() does not handle that exceptional completion.

Consequently, doDeleteBucketSnapshot() is never reached, and ImmutableBucket.resolveBucketIdForDelete() cannot convert the failed create into Optional.empty(). The sequential trim chain still fails on a snapshot-create failure.

Could we either handle the create future here—using handle or exceptionallyCompose—to convert a failed creation into "nothing to delete," or remove this duplicated create-future guard and make ImmutableBucket.asyncDeleteBucketSnapshot() the single place responsible for resolving the snapshot lifecycle?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

ImmutableBucket.asyncDeleteBucketSnapshot() has been handled this issue. The PR has been updated.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Addressed exactly along those lines on the rebased head: resolveBucketIdForDelete() converts a failed
creation into Optional.empty() via handle, so doDeleteBucketSnapshot's equivalent path resolves to
"nothing to delete" and the chain continues. The merged-bucket terminal was converted the same way — it
maps the create outcome to a boolean with handle and either keepUncleaned(buckets) or runs the tracked
source deletes. testTrimSkipsFailedSnapshotCreation locks the behavior.

}

@Override
public synchronized CompletableFuture<Void> clear() {

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.

resetCursorInternal() now uses clearDelayedMessages() as a quiescence barrier before moving the cursor. However, BucketDelayedDeliveryTracker.clear() only waits for trimFuture, but it does not wait for or fence the current pendingLoad operation.

A snapshot segment read that was already started by getScheduledMessages() could therefore complete after clear() has cleared the sharedBucketPriorityQueue, index, and snapshotSegmentLastIndexMap. Its completion callback then reacquires the tracker lock and repopulates snapshotSegmentLastIndexMap and sharedBucketPriorityQueue with the pre-reset state.

Because PersistentDispatcherMultipleConsumers.clearDelayedMessages() keeps the same tracker instance in use, this stale callback can mutate the tracker after the reset.

Could clear() also wait for or cancel the current pendingLoad? Alternatively, could it introduce a tracker generation or epoch so that callbacks started before clear cannot publish their results afterward? A deterministic regression test could block getBucketSnapshotSegment(), start clear/reset, release the load after the in-memory state is cleared, and verify that no old segment state is restored.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Good catch, pendingLoad has been handled.

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.

@nodece
Closing the stale segment callback race by waiting for pendingLoad prevents some issues, but clear() still does not appear to wait for all asynchronous snapshot cleanups, which can modify cursor properties.

For instance, in the merge path, source-bucket asyncDeleteBucketSnapshot() futures are started from the merged bucket's creation callback without returning or tracking that cleanup chain. Likewise, the terminal segment-load path calls asyncDeleteBucketSnapshot() without composing its future.

This is important for reset because asyncDeleteBucketSnapshot() ultimately calls removeBucketCursorProperty(bucketKey). An old cleanup may therefore complete after clear() or reset, while replay has already created a new bucket with the same range and stored a new ID under the same key. The delayed cleanup could then remove the recovery pointer for the new bucket.

Could all bucket cleanup operations that modify cursor properties be tracked by the tracker and included in the clear() quiescence barrier, or could property removal be conditional on the expected bucket ID or generation?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Resolved by the rebase: master now contains #26401, where clear() awaits trimFuture, then
pendingLoad and the pending deletes, before cleaning the in-memory state. This PR's own pendingLoad wait
was dropped as a subset of that.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Also resolved by the rebase: #26401 routes every async snapshot delete through trackDelete — the merge
source deletes started from the merged bucket's creation callback, the terminal segment-load delete, the
recovery deletes and the cleanImmutableBuckets retries — so clear() waits for all of them and retries
the failed ones.

@nodece
nodece force-pushed the fix-bucket-trim-and-loading branch from 5ce893e to 81f5604 Compare August 17, 2026 06:58
@nodece
nodece marked this pull request as draft August 17, 2026 07:21
@nodece
nodece requested a review from Denovo1998 August 17, 2026 07:38
@nodece
nodece marked this pull request as ready for review August 17, 2026 07:38
@nodece

nodece commented Aug 17, 2026

Copy link
Copy Markdown
Member Author

/pulsarbot rerun-failure-test

Comment on lines +1007 to +1009
clearDelayedMessagesFuture = dispatcher != null
? dispatcher.clearDelayedMessages()
: CompletableFuture.completedFuture(null);

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.

When the dispatcher is null, resetting completely skips delayed-delivery cleanup. Is preserving existing bucket snapshot properties intentional here?

A durable subscription may retain bucket cursor properties from a previous broker/dispatcher lifecycle even before its dispatcher is created. In contrast, PersistentDispatcherMultipleConsumers.clearDelayedMessages() calls cleanResidualSnapshots(cursor) when a dispatcher exists but no tracker has been instantiated.

It would be helpful to document why these two cases intentionally have different reset semantics, or to handle the no-dispatcher case consistently if they should not differ.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The reset changes were moved out of this PR (the head no longer touches PersistentSubscription). The
no-dispatcher reset semantics you raised are now handled in #26420: resetCursorInternal runs
cleanResidualSnapshots(cursor) behind the same guards as the unsubscribe path when no dispatcher
exists, with a regression test (testResetCursorWithoutDispatcherCleansResidualBucketSnapshots).

@nodece
nodece marked this pull request as draft August 17, 2026 13:54
@lhotari lhotari removed this from the 5.0.0-M2 milestone Sep 12, 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
…apshot

asyncDeleteBucketSnapshot() recorded a delete trigger event before
resolving the bucket id, so the failed-creation path (Optional.empty,
nothing to delete) counted a trigger without ever recording a success
or failure. Record the trigger and the start time only when there is
an actual snapshot to delete.

Assisted-by: Claude Code
@nodece
nodece force-pushed the fix-bucket-trim-and-loading branch from 76aa038 to 6b34230 Compare November 18, 2026 03:59
@nodece
nodece marked this pull request as ready for review November 18, 2026 03:59
@nodece
nodece requested a review from Denovo1998 November 18, 2026 04:01

// Trigger the segment loading
clockTime.set(600);
tracker2.getScheduledMessages(10);

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.

Could we avoid discarding the result of this first getScheduledMessages() call? If the segment futures complete quickly, this call can already return and consume 4:4, so the following Awaitility check will keep polling an empty queue and time out. Removing this call, or accumulating the results including this first one, would make the test independent of completion timing.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in ce39d6b: the test now accumulates the results of every getScheduledMessages() call, starting with the load-triggering one, so a fast-completing segment future that already consumed (4, 4) in the first call no longer leaves the polling assertion with an empty queue. Thanks for catching the timing dependency.

…completion timing

testLoadsNextSnapshotSegmentAfterCutoff discarded the result of the
first getScheduledMessages() call that triggers the load. When the
segment futures complete quickly that call already consumes (4, 4), so
the polling assertion kept observing an empty queue and timed out.
Accumulate the results of every call instead.

Assisted-by: Claude Code
@nodece
nodece requested a review from Denovo1998 November 18, 2026 10:45
@nodece

nodece commented Nov 20, 2026

Copy link
Copy Markdown
Member Author

This PR is superseded by three focused PRs:

The original combined changes have been split to keep each dimension reviewable independently. This PR is intentionally left open until the replacements land.

@nodece
nodece marked this pull request as draft November 20, 2026 07:39
@nodece

nodece commented Nov 23, 2026

Copy link
Copy Markdown
Member Author

Closing in favor of #27673, which carries this PR's content in full: the trim/segment-loading fixes (the orphaned-tail boundary advance, isCurrentBucket), the INVALID_BUCKET_ID sentinel removal, and the failed-creation cleanup hardening (resolveBucketIdForDelete, keepUncleaned). Please continue the review there.

@nodece nodece closed this Nov 23, 2026
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.

5 participants