Skip to content

[fix][broker] Clear delayed delivery state before resetting the cursor - #26420

Draft
nodece wants to merge 13 commits into
apache:masterfrom
nodece:fix-reset-clear-delayed-messages
Draft

nodece wants to merge 13 commits into
apache:masterfrom
nodece:fix-reset-clear-delayed-messages

Conversation

@nodece

@nodece nodece commented Aug 25, 2026 •

Copy link
Copy Markdown
Member

Motivation

PersistentSubscription#resetCursorInternal reset the cursor without touching the delayed delivery tracker. The tracker state is a derived cache of the backlog (the source of truth is deliverAtTime in the message metadata), and a reset moves the consumption baseline, so the whole derivation is invalidated:

  • bucket snapshots, index bits and queued entries from before the reset survived into the replay, and re-added messages deduped against the stale index instead of being re-tracked cleanly;
  • in-flight trims/loads/deletes from before the reset could race the replayed state;
  • the bucket cursor properties stayed on the cursor, so a later tracker recovery would load pre-reset buckets — for a forward reset the recovered snapshots are not even filtered by the new mark-delete position.

clearBacklog and unsubscribe already clear the delayed state for the same reason; the reset path was the odd one out.

Modifications

The bucket-storage hardening this PR originally carried (missing-ledger -25 handling, the superseded-ledger delete before a replacement snapshot is allocated, and the compare-and-remove guards for the bucket cursor property) moved to #27673 and lands first; this PR now reviews only the cursor-reset semantics. A reset-level missing-ledger regression will be re-added once #27673 is in.

  • resetCursorInternal now clears the delayed messages and waits for the clear to settle after disconnecting consumers and before asyncResetCursor. With a dispatcher this goes through clearDelayedMessagesAfterCursorReset(); without a dispatcher — the state right after a topic unload or a broker restart — it runs cleanResidualSnapshots(cursor) behind the same guards as the unsubscribe path, so a later consumer reconnect cannot recover pre-reset buckets from the cursor properties. Since [fix][broker] Manage in-flight bucket work during clear #26401, BucketDelayedDeliveryTracker#clear() also waits for in-flight segment loads and deletes, so the whole derivation settles before the reset.
  • A cleanup failure is non-fatal for the reset: the delayed state is a derived cache, so the clear stage logs a WARN and the reset proceeds with asyncResetCursor. The clear future only settles once every cursor-property write has completed (waitForAll is allOf), so continuing cannot race the reset persistence. A failed reset remains the only thing that unfences with an error; a subscription whose cleanup failed stays usable and a retry re-runs the cleanup. The recovery handler wraps the cleanup futures inside the successful-disconnect continuation, so a disconnect failure still fails the reset with SubscriptionBusyException instead of being downgraded to a cleanup warning.
  • The reset does not wait for a pending delayed-tracker creation: clearDelayedMessagesAfterCursorReset() invalidates any in-flight creation, so a backlog clear waiting on that creation fails instead of running a second residual cleanup that could race the reset, a late creation retry closes instead of installing pre-reset state, and the post-reset replay starts a fresh creation.
  • After the dispatcher clear settles, the reset also runs cleanResidualSnapshots: a dispatcher without a bucket tracker (subscription type switched to Exclusive/Failover, or a tracker that fell back to the in-memory implementation) leaves the bucket cursor properties behind on an otherwise successful clear, and for a healthy bucket tracker the extra pass is a no-op.

Trade-off: the reset/seek latency now includes the bucket-snapshot cleanup (trim/merge wait, snapshot deletes, one cursor-property removal per bucket) while consumers are disconnected and reconnects are parked on inProgressResetCursorFuture, and the wait is unbounded (delayedDeliveryMaxNumBuckets is unbounded by default). In exchange, the replay after the reset starts from a clean tracker and does not re-snapshot the whole delayed backlog against stale state — the rewind path deliberately keeps the snapshots, a reset deliberately does not.

The tracker-less cleanup guard is intentionally not shared with PersistentTopic#asyncDeleteCursorWithClearDelayedMessage and PersistentDispatcherMultipleConsumers#clearDelayedMessages: the failure semantics differ (unsubscribe fails on a cleanup failure, a reset degrades to a WARN), so a shared helper would have to take the failure policy as a parameter for three call sites.

Verifying this change

  • Make sure that the change passes the CI checks.

This change added tests and can be verified as follows (BucketDelayedDeliveryTest, PersistentDispatcherMultipleConsumersTest, PersistentSubscriptionTest):

  • testResetCursorClearsDelayedMessages: tracks 100 delayed messages, resets the cursor to the earliest position and verifies the tracker count is 0 and the bucket cursor properties are removed. Without the fix the tracker still reports 100 delayed messages and the bucket cursor property survives the reset.
  • testResetCursorWithoutDispatcherCleansResidualBucketSnapshots: after a topic unload with no consumer connected, a reset still removes the residual bucket cursor properties.
  • testResetCursorSucceedsWhenSnapshotCleanupFails: injects a LedgerFencedException for the snapshot delete; the reset itself succeeds, the subscription is not fenced, a retry succeeds and a new consumer can subscribe.
  • testResetCursorRedeliversDelayedMessagesAfterReset: after a reset to the earliest position, a reconnecting consumer receives every delayed message exactly once (100 unique / 100 total).
  • testForwardResetSkipsDelayedMessagesAfterReset: a forward reset skips the pre-reset delayed messages; the replay delivers only the messages after the reset position.
  • testResetCursorFailsBusyWhenDisconnectFails: a failed disconnect fails the reset with SubscriptionBusyException without reaching asyncResetCursor, and a retry after a successful disconnect proceeds.
  • testRepeatedResetFailsBusyWhileInProgressThenSucceeds: while the first reset is fenced, a repeated reset fails busy instead of racing it; after the first completes, a later reset proceeds.
  • testCursorResetInvalidationFailsWaitingBacklogClear: a reset invalidates the creation a backlog clear is waiting on; the waiting clear fails instead of running a second residual cleanup that could race the reset.
  • testResetCleansResidualSnapshotsAfterSubscriptionTypeSwitch: after a Shared-to-Exclusive switch, a reset still removes the residual bucket cursor properties.

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

Documentation

@nodece
nodece force-pushed the fix-reset-clear-delayed-messages branch 2 times, most recently from 0b30bc7 to 15f944a Compare August 25, 2026 10:02
@nodece
nodece requested review from dao-jun and lhotari August 28, 2026 12:45

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

Net assessment: the change is directionally right. Clearing the delayed-delivery state before asyncResetCursor closes a real gap, the flattened chain reads much better than the old callback pyramid, and it incidentally fixes a latent hang — in the base revision a synchronous throw inside the whenComplete body (e.g. from the getTopicCompactionService() block) would have left the returned future uncompleted forever, hanging the admin request.

Two things I would like resolved before merge:

  1. The dispatcher == null branch cleans nothing, so the third motivation bullet — pre-reset bucket cursor properties surviving into a later tracker recovery — is not fixed exactly when there is no dispatcher. The same method already routes the equivalent "dispatcher present but no tracker" state through cleanResidualSnapshots(cursor), and the unsubscribe path cited as precedent handles dispatcher == null explicitly.
  2. clear() waits for in-flight trims but not for an in-flight bucket segment load, so the second motivation bullet ("in-flight trims/loads/deletes from before the reset could race the replayed state") is only partly achieved.

Plus one test-robustness note: the new test races the client's automatic reconnect, and one note on a silently changed failure branch.

@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 the quick follow-up. Three of the four threads are fixed in the new commits. The delta is only the requested edits, and I found no new problems in it.

One point is still open: clear() does not wait for an in-flight bucket segment load. You plan to fix that through #26401 and rebase. That is fine with me. Because you saw the full BucketDelayedDeliveryTest suite fail without it, this PR should merge after #26401, or include the fix.

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

Thanks for working on this. Clearing the delayed-delivery state on reset is the right direction: a reset moves the mark-delete position, unlike the dispatcher's plain rewind, so starting from a clean slate matches what clearBacklog and unsubscribe already do.

What I verified locally (JDK 21, -PtestRetryCount=0)

  • Bug reproduced: with the unpatched merge-base PersistentSubscription, both new tests fail as described. The delayed count stays at 100 instead of 0, and the bucket cursor property survives the reset. Both tests pass on this head.
  • Suite without #26401: the full BucketDelayedDeliveryTest (35 tests, including the inherited DelayedDeliveryTest cases) passes on this head without #26401. The earlier "suite fails every time" looks like the handle() flattening bug that 803173d fixed. Merging after #26401 still makes sense so clear() also covers in-flight loads and deletes (see the open thread). One clean run is weak evidence for a race, though.
  • Delivery after a reset: after a reset to earliest, a reconnecting consumer received all 100 delayed messages exactly once, both with and without the fix. So the effect shown here is the stale stats and stale persisted snapshots, not lost or duplicated messages.

Why I'm requesting changes (first inline comment). The bucket-snapshot cleanup is now a hard precondition of reset and consumer seek(). When a snapshot ledger is already gone, the cleanup fails on every retry:

  • the default metadata-store: BK driver returns NoSuchLedgerExistsOnMetadataServerException (-25) for a missing ledger;
  • BookkeeperBucketSnapshotStorage only treats -7 as "already deleted";
  • I confirmed rc=-25 at runtime, and on this head, injecting it makes resetCursor return 500 while the bucket property stays.

What I'd like to see before approving

  1. Make a cleanup failure non-fatal for the reset (log a WARN and continue), or run the cleanup only after the reset has succeeded. Either way, handle -25 like -7 in BookkeeperBucketSnapshotStorage.deleteLedger/openLedger, here or in a PR that lands first.
  2. Update the PR description. It still says nothing is cleared without a dispatcher, and "Verifying this change" lists only one of the two new tests.
  3. Add a test for the failure path and one that checks delivery after the reset (see the test comment).
  4. Merge after #26401, as discussed in the open thread. The branch is about 340 commits behind master. GitHub reports it mergeable, but merging master and re-running CI would be good, given the related dispatcher changes there (#26687, #26868, #26809).

The other inline comments are lower priority: the latency/cost trade-off, a nit, and test suggestions.

Comment on lines +1008 to +1020
.thenCompose(__ -> {
if (dispatcher != null) {
return dispatcher.clearDelayedMessages();
}

forceReset.thenAccept(forceResetValue -> {
cursor.asyncResetCursor(finalPosition, forceResetValue, new AsyncCallbacks.ResetCursorCallback() {
@Override
public void resetComplete(Object ctx) {
log.debug()
.attr("finalPosition", finalPosition)
.log("Successfully reset subscription to position");
if (dispatcher != null) {
dispatcher.cursorIsReset();
dispatcher.afterAckMessages(null, finalPosition);
}
IS_FENCED_UPDATER.set(PersistentSubscription.this, FALSE);
inProgressResetCursorFuture = null;
future.complete(null);
if (topic.isDelayedDeliveryEnabled()
&& topic.getBrokerService().getDelayedDeliveryTrackerFactory()
instanceof BucketDelayedDeliveryTrackerFactory bucketDelayedDeliveryTrackerFactory) {
return bucketDelayedDeliveryTrackerFactory.cleanResidualSnapshots(cursor);
}

@Override
public void resetFailed(ManagedLedgerException exception, Object ctx) {
log.error()
.attr("finalPosition", finalPosition)
.exception(exception)
.log("Failed to reset subscription to position");
IS_FENCED_UPDATER.set(PersistentSubscription.this, FALSE);
inProgressResetCursorFuture = null;
// todo - retry on InvalidCursorPositionException
// or should we just ask user to retry one more time?
if (exception instanceof InvalidCursorPositionException) {
future.completeExceptionally(new SubscriptionInvalidCursorPosition(exception.getMessage()));
} else if (exception instanceof ConcurrentFindCursorPositionException) {
future.completeExceptionally(new SubscriptionBusyException(exception.getMessage()));
} else {
future.completeExceptionally(new BrokerServiceException(exception));
}
return 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.

[Medium] Cleanup is now a hard precondition of reset/seek, and a missing snapshot ledger makes it fail every time

Any failure in this stage now fails the reset: HTTP 500 for admin, UnknownError for consumer seek(), which goes through the same path (ServerCnx.java:2892/2913). Before this change, reset never touched snapshot storage.

Trigger. A bucket cursor property can outlive its ledger:

  • cleanResidualSnapshots deletes the ledger, then removes the property without retrying;
  • asyncDeleteBucketSnapshot gives up after its retries;
  • the broker can crash between the two steps.

With the default metadata-store: BK driver, deleting a ledger that no longer exists returns NoSuchLedgerExistsOnMetadataServerException (-25):

Impact. The delete fails and the property stays, so every later reset/seek fails again whenever the subscription has no live bucket tracker:

  • no dispatcher since the topic loaded, which is the usual "stop consumers, then reset" flow;
  • or a dispatcher that hasn't read a delayed message yet, for example a consumer that seeks right after subscribing.

The property can't be removed through the admin API, because setCursorProperties rejects #pulsar.internal.* keys. Unsubscribe fails on the same condition (PersistentTopic#asyncDeleteCursorWithClearDelayedMessage), so the subscription can't be recreated either.

Verified locally:

  • PulsarLedgerManager.removeLedgerMetadata() on a missing ledger returns rc=-25 (memory store).
  • On this head, after unload/reload with no consumer, injecting -25 for the snapshot delete makes admin.topics().resetCursor(...) return 500 No such ledger exists on Metadata Server - ledger=8 - operation=Delete ledger, and the bucket property stays.
  • With the injection removed, the next reset succeeds, so the error path does unfence.
  • PulsarMockBookKeeper returns -7 for missing ledgers, which is why the existing tests can't see this.

Suggestion. The delayed state is a derived cache, so failing the user's reset over it seems like the wrong trade-off. Two options:

  • If the clear fails, log a WARN and continue to asyncResetCursor. clear() has already reset the in-memory state, and stale snapshot positions at or below the new mark-delete are filtered by asyncReplayEntries.
  • Or run the destructive cleanup only after the reset has succeeded.

Independently, deleteLedger/openLedger should treat -25 like -7, either here or in a PR that lands first.

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 suggestions are implemented in af38a2b:

  • deleteLedger and openLedger now use managed-ledger's Errors.isNoSuchLedgerExistsException, so both -7 and -25 mean "ledger gone" — the delete succeeds, and openLedger maps both to BucketNotExistException, which recovery already drops the bucket for, so a stale property self-heals on the next tracker recovery too.
  • The clear is no longer fatal for the reset: the clear stage logs a WARN and continues to asyncResetCursor (your first option). The clear future only settles once every cursor-property write has completed (waitForAll is allOf), so continuing cannot race the reset persistence.
  • Regression test testResetCursorSucceedsWhenSnapshotLedgerAlreadyDeleted injects rc=-25 for the snapshot delete after an unload with no dispatcher: without the fix it fails with the exact "No such ledger exists on Metadata Server" you reproduced; with it the reset succeeds and the property 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.

The -25 handling moved to #27673 together with the other bucket-storage hardening, so this PR reviews only the cursor-reset semantics (f2b1a27 dropped the bucket files; #27673 lands first). deleteLedger/openLedger there use Errors.isNoSuchLedgerExistsException, with testMissingLedgerOnMetadataServerIsTreatedAsAlreadyDeleted / testOpenLedgerMapsMissingOnMetadataServerToBucketNotExist covering both codes; I will re-add the reset-level regression (reset succeeds on an already-deleted snapshot ledger) here once #27673 is in.

}
})
.thenCompose(__ -> {
if (dispatcher != 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.

[Low] Reset/seek latency now grows with bucket-snapshot I/O while the subscription is fenced

For a bucket tracker, this stage:

  • waits for any in-flight trim/merge (trimFuture);
  • waits for each bucket's pending snapshot creation;
  • deletes every snapshot ledger;
  • removes one cursor property per bucket. The removals are serialized through the tracker's sequencer, and each one rewrites the full ManagedCursorInfo (BucketDelayedDeliveryTracker#clear/cleanImmutableBuckets, ImmutableBucket#asyncDeleteBucketSnapshot).

None of this has a timeout. Meanwhile the consumers are disconnected, and reconnects are parked on inProgressResetCursorFuture. After the reset, the replay re-snapshots the whole delayed backlog. The rewind path avoids that on purpose ("Don't clean up BucketDelayedDeliveryTracker, otherwise we will lose the bucket snapshot" in PersistentDispatcherMultipleConsumers#addConsumer).

This applies to every consumer seek() and to reader rollback (PersistentTopic#resetSubscriptionCursor), and delayedDeliveryMaxNumBuckets is unbounded by default. It's fine for small states. Please mention the trade-off in the PR description. A bounded wait (e.g. orTimeout, then continue as suggested in the comment above) would cap the impact.

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.

Trade-off documented in the description ("Trade-off:" under Modifications): the reset/seek waits for trim/merge, the snapshot deletes and the property removals while reconnects park on inProgressResetCursorFuture, unbounded like delayedDeliveryMaxNumBuckets, in exchange for a tracker that the replay re-derives cleanly. I left orTimeout out deliberately: a timed-out clear keeps deleting in the background, and its cursor-property writes could then race the reset persistence — the BadVersion mode this PR's third commit fixed. If the fenced window turns out to matter, the cleaner shape is your second option (destructive cleanup only after the reset settles), which removes it entirely.

if (topic.isDelayedDeliveryEnabled()
&& topic.getBrokerService().getDelayedDeliveryTrackerFactory()
instanceof BucketDelayedDeliveryTrackerFactory bucketDelayedDeliveryTrackerFactory) {
return bucketDelayedDeliveryTrackerFactory.cleanResidualSnapshots(cursor);

ghost Oct 13, 2026

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.

[Nit] Description is out of date, and the cleanup logic is duplicated

The PR description still says "Without a dispatcher there is no in-flight work … so there is nothing to clear", but since f16e705 this branch cleans residual snapshots. Please update it, since it becomes the squash commit message. "Verifying this change" also lists only one of the two new tests.

This tracker-less cleanup is now the third copy of the same logic, after PersistentTopic#asyncDeleteCursorWithClearDelayedMessage and PersistentDispatcherMultipleConsumers#clearDelayedMessages. A small shared helper would keep the guards (isDelayedDeliveryEnabled(), factory type) consistent.

ghost Nov 18, 2026

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.

Description rewritten: the no-dispatcher branch now documents cleanResidualSnapshots, and all five tests are listed. On the dedup: kept the copies separate on purpose — the failure semantics differ (unsubscribe fails the operation when the cleanup fails; a reset degrades to WARN-and-continue), so a shared helper would need the failure policy as a parameter across three call sites for two lines of guards each. Happy to consolidate if you prefer.

Comment on lines +166 to +173
admin.topics().resetCursor(topic, "sub", MessageId.earliest);

assertEquals(dispatcher.getNumberOfDelayedMessages(), 0,
"The delayed delivery tracker should be cleared by the cursor reset");
List<String> bucketKeysAfterReset =
((AbstractPersistentDispatcherMultipleConsumers) dispatcher).getCursor().getCursorProperties()
.keySet().stream().filter(x -> x.startsWith(CURSOR_INTERNAL_PROPERTY_PREFIX)).toList();
assertTrue(bucketKeysAfterReset.isEmpty(),

ghost Oct 13, 2026

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.

[Test gap] Only internal state is asserted

Neither test checks what consumers receive or the new failure path. Suggested additions:

  1. End-to-end: after the reset, reconnect with a short deliverAfter and assert every message is delivered exactly once. A local version of this passes on this head (100 unique / 100 total).
  2. Forward reset: reset to latest or to a middle position. Assert the tracker is cleared and the skipped messages are not delivered after reconnect. This is the forward-reset case from the no-dispatcher thread.
  3. Failure path: make the cleanup fail, then assert the error status, that the subscription is unfenced, and that a later reset or subscribe works. With the mock BK, after unload/reload, failAfter(0, rc) + failAfter(1, rc) with rc = NoSuchLedgerExistsOnMetadataServerException hits the close and then the delete of the cached snapshot ledger handle.
  4. Optional: assert the snapshot ledgers are gone from the mock BK, not only the cursor properties.

ghost Nov 18, 2026

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 (1) and (3): testResetCursorRedeliversDelayedMessagesAfterReset (100 messages with a 10s deliverAfter, reset to earliest, reconnecting consumer receives 100 unique / 100 total) and testResetCursorSucceedsWhenSnapshotCleanupFails (LedgerFencedException on the snapshot delete: the reset succeeds, the subscription is not fenced, a retry succeeds, a new consumer can subscribe). The -25 case is covered in the reply to your first comment. I skipped (2): the no-dispatcher branch runs cleanResidualSnapshots regardless of reset direction and the existing test asserts the properties are gone, so the forward-reset delivery behavior seemed covered structurally — say the word and I'll add the explicit assertion. (4) not added; the property removal is what the recovery path keys off, so that is what the tests assert.

ghost Nov 18, 2026

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 the forward-reset case: testForwardResetSkipsDelayedMessagesAfterReset snapshots 100 delayed messages, resets the cursor to MessageId.latest, reconnects a consumer, and asserts that no skipped message is delivered, the tracker count is 0, and the bucket cursor properties are removed.

ghost 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.

The rebased head fixes the missing-ledger error (-25), includes #26401, and documents the cost of cleanup. All five reset tests passed without retries. I would still request changes: a failing tracker factory can leave the subscription fenced, and some successful resets leave old snapshots behind. The new recovery handler also catches disconnect errors, not just cleanup errors.

})
.thenCompose(__ -> {
if (dispatcher != null) {
return dispatcher.clearDelayedMessages();

ghost Nov 18, 2026

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.

Do not keep reset fenced across tracker-creation retries

A Shared subscription has encountered a delayed message, its configured tracker factory keeps failing creation, and an operator seeks past that message. The consumers disconnect, but the cursor never advances and reconnects wait on the unfinished reset. This is not just slow snapshot I/O: even after a creation attempt has definitively failed, the reset still waits for a future successful attempt.

'clearDelayedMessages()' waits on 'delayedDeliveryTrackerCreateFuture'. On creation failure the dispatcher completes a different future, 'delayedDeliveryTrackerCreateFailureFuture', and schedules a retry. The new WARN-and-continue handler therefore never sees this failure. The existing dispatcher retry test confirms that an ordinary clear is still pending after a failed attempt; backlog clear already observes the separate failure signal.

Give reset a cleanup path that observes tracker-creation failure as well as success, without leaving a late retry able to install pre-reset pending positions. Extend the gated-factory test to seek to latest after creation fails and verify that the reset settles and reconnect is released without waiting for a successful retry.

ghost Nov 18, 2026

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 6839f92. The reset now clears through clearDelayedMessagesAfterBacklogClear() instead of clearDelayedMessages(): it races the pending creation against delayedDeliveryTrackerCreateFailureFuture (applyToEither), so the clear settles exceptionally once an attempt has definitively failed, and it completes delayedDeliveryTrackerRecoverySkipFuture with the mark-delete filter, so a late successful retry cannot install pre-reset pending positions. I reused the backlog-clear method rather than adding a third clear variant to the Dispatcher interface — from the dispatcher's side both operations are "the cursor is moving past the state the trackers were derived from"; its javadoc now says so. testClearAfterCursorResetSettlesOnTrackerCreationFailure uses an always-failing factory and asserts the reset-path clear settles exceptionally while an ordinary clear keeps waiting for a successful retry.

ghost Nov 18, 2026

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 f80cae7. You were right that the earlier fix only released the reset fence; it did not actually prevent a late retry from installing pre-reset positions.

clearDelayedMessagesAfterBacklogClear() filtered messagesPendingDelayedDeliveryTracker only against the pre-reset mark-delete position, so a forward reset left positions between the old and new cursor positions waiting. A retry that succeeded after the reset was released installed those positions into the tracker, and positions in the same ledger below the new mark-delete position could still be delivered.

The reset path now drops every pre-reset pending position when the cursor is about to move. The reset has already canceled pending reads by this point, so the pending set contains only pre-reset positions; valid positions are re-derived by the replay from the new cursor position, and skipped positions stay skipped.

Added testLateTrackerCreationAfterCursorResetDoesNotInstallPendingMessages: the first tracker-creation attempt fails, the reset-path clear settles exceptionally, the pending position is gone, then a gated retry succeeds and installs an empty tracker without calling addMessage. I ran it together with the existing creation-failure test; both pass.

}
})
.thenCompose(__ -> {
if (dispatcher != null) {

ghost Nov 18, 2026

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.

Clean residual snapshots when the dispatcher does not own them

A durable Shared subscription creates bucket snapshots. Its consumers disconnect, an Exclusive or Failover consumer attaches to the same subscription, and the cursor is reset. A similar case occurs when bucket recovery falls back to an in-memory tracker. Reset succeeds without removing the bucket properties or ledgers, even when storage is healthy. A later Shared tracker can restore the pre-reset indexes and count messages skipped by a forward reset as delayed.

'reuseOrCreateDispatcher' permits the subscription-type switch once the old consumers have gone. Closing the Shared dispatcher closes its tracker without deleting snapshots. The replacement single-active dispatcher inherits the default no-op 'clearDelayedMessages()'. Likewise, clearing an installed in-memory fallback does not touch cursor properties. The early return here bypasses 'cleanResidualSnapshots' in both cases.

After clearing the current dispatcher, check for remaining delayed-bucket properties and clean them through the bucket factory when no bucket tracker owns them. Add a forward-reset case that creates snapshots under Shared, switches to Exclusive, resets, then checks the properties before reconnecting as Shared.

ghost Nov 18, 2026

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 6839f92. After the dispatcher clear settles (either outcome), the reset additionally runs cleanResidualSnapshots(cursor) behind the usual bucket-factory guards: for a dispatcher whose clearDelayedMessages() is the interface no-op (Exclusive/Failover switch) or an installed in-memory fallback, this removes the bucket properties and ledgers; for a healthy bucket tracker whose clear already removed them it is a no-op; and when the dispatcher clear itself failed, the extra pass retries the cleanup. testResetCleansResidualSnapshotsAfterSubscriptionTypeSwitch covers the Shared-to-Exclusive case (snapshots under Shared, switch, reset, properties gone) — verified it fails on the previous head.

.exception(throwable)
.log("Failed to clear delayed delivery state before cursor reset, continuing");
}
return null;

ghost Nov 18, 2026

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.

Preserve the old snapshot ledger ID when replay follows a failed live-tracker delete

A live bucket tracker exhausts its delete retries during a reset to earliest. Storage recovers, the consumer reconnects and replay seals the same ledger range again, then the topic unloads before another clear. Replay overwrites the only durable reference to the undeleted snapshot. After unload, normal cleanup can find the replacement ledger but not the old one, leaving BookKeeper storage allocated.

'cleanImmutableBuckets()' removes the bucket from the active map before deletion; failed deletes are retained in the in-memory 'uncleanedBuckets' set. 'ImmutableBucket.bucketKey()' depends only on the ledger range, and saving its replacement writes the new ID under that same cursor property. 'closeAsync()' does not drain 'uncleanedBuckets'. The new failure test unloads before injection and retries before reconnect, so it does not exercise this sequence.

Keep the failed snapshot discoverable until its deletion succeeds. For example, keep replayed indexes in memory for that range rather than replacing its persisted ID while deletion is outstanding. Test a failed live-tracker delete followed by replay and unload, and verify the original ledger is still reachable for cleanup or has been deleted.

ghost Nov 18, 2026

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 6839f92 along the lines of your suggestion. ImmutableBucket.asyncSaveBucketSnapshot now calls deleteSupersededSnapshotLedger before putBucketKeyId: if the bucket cursor property already references a different ledger, that superseded ledger is deleted first; if the delete fails, the just-created replacement ledger is deleted, the save fails, and the bucket downgrades to memory mode — so the property keeps referencing the superseded ledger and a later save retries, instead of overwriting the only durable reference. A malformed old value is skipped with a WARN. This also heals the same leak after a failed unsubscribe cleanup. testReplayDeletesSupersededSnapshotLedgerOnReseal covers the sequence you described: a reset whose snapshot deletes fail (property survives), a reconnect that re-seals the same range, and the assertion that the superseded ledger is gone from BookKeeper while the property references the replacement — verified it fails on the previous head (the superseded ledger stays reachable forever). Note this touches ImmutableBucket in the same file as #26280 but a different method (asyncSaveBucketSnapshot vs asyncDeleteBucketSnapshot), so the two PRs merge independently of order.

ghost Nov 20, 2026

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 superseded-ledger delete moved to #27673 (f2b1a27 dropped the bucket files from this PR). There, ImmutableBucket.asyncSaveBucketSnapshot deletes the ledger the property still references before allocating the replacement — refined from the rollback design you reviewed: the delete now runs before the replacement is created, so a failed delete fails the save without ever allocating a replacement to roll back. testSaveDoesNotAllocateReplacementWhenSupersededDeleteFails locks it.

// The delayed state is a derived cache of the backlog; a failed clear must not make the
// reset unusable. The clear future only settles once every cursor-property write has
// completed, so continuing cannot race the reset persistence.
.handle((ignore, throwable) -> {

ghost Nov 18, 2026

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.

Limit WARN-and-continue to delayed-state cleanup

'disconnectActiveConsumers(true)' returns an exceptionally completed future. Reset skips cleanup, misreports the disconnect error as a cleanup warning, and calls 'asyncResetCursor' without a successful disconnect. The caller can receive success instead of 'SubscriptionBusyException'.

The first 'handle' explicitly throws 'SubscriptionBusyException' on disconnect failure. That skips 'thenCompose' at line 1071, but this second 'handle' still runs and returns 'null', clearing the exception. This is a regression from the previous head's explicit disconnect-failure branch; the built-in dispatchers normally complete their close futures successfully.

Attach the recovery handler to the cleanup future inside the successful-disconnect continuation. Test with a failed disconnect future and verify that the caller receives 'SubscriptionBusyException' and 'asyncResetCursor' is never invoked.

ghost Nov 18, 2026

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 6839f92 — you caught a regression from the previous round. The recovery handler now wraps the cleanup futures inside the successful-disconnect continuation (clearDelayedStateForReset()), so it only sees delayed-state cleanup failures; a disconnect failure propagates to the terminal handler and the reset fails with SubscriptionBusyException. testResetCursorFailsBusyWhenDisconnectFails stubs a failed disconnectActiveConsumers(true) and asserts the reset fails with SubscriptionBusyException, asyncResetCursor is never invoked, and a retry after a successful disconnect proceeds. Verified the test fails on the previous head.

@nodece
nodece requested a review from codelipenghui November 18, 2026 10:39

ghost 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.

The four new commits fix disconnect-error propagation, clean snapshots after a subscription-type switch, and release reset when tracker creation fails. All 15 focused test cases passed. I still recommend changes: ordinary backlog clear can now discard a live delayed message, a late recovery can install a tracker backed by deleted ledgers, and snapshot replacement still has cleanup paths that can orphan a ledger.

// pre-clear pending position: a late tracker-creation retry must not install them
// after a forward reset, and the replay re-derives the positions that remain valid
// from the new cursor position.
messagesPendingDelayedDeliveryTracker.clear();

ghost Nov 18, 2026

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.

Keep delayed positions newer than an ordinary backlog clear

'clearBacklog()' captures position N. Before its asynchronous mark-delete callback reaches this method, the dispatcher reads a newly published delayed message at N+1 and queues it for tracker creation. The creation attempt fails and is retried. N+1 was not part of the cleared backlog, but its pending entry is erased. The consumer stays connected and the read cursor has already passed it, so a successful tracker retry cannot schedule it. Delivery can remain stalled until a rewind or reconnect.

'asyncClearBacklog' marks 'ledger.getLastPosition()' as captured at invocation. Unlike reset, 'PersistentSubscription.clearBacklog()' neither disconnects consumers nor rewinds the read cursor. The previous head removed only positions at or below mark-delete; this unconditional 'clear()' also removes N+1. The install-time filter cannot restore a removed entry.

Separate reset cleanup from backlog-clear cleanup. Drop all pending positions for a fenced reset; preserve positions above mark-delete for an ordinary clear and install them after the old tracker state is cleared. Add a gated test with N+1 already pending when the backlog-clear callback runs, then verify delivery without reconnecting.

ghost Nov 19, 2026

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 f6fc6fc. Reset and ordinary backlog clear now use separate paths: clearDelayedMessagesAfterCursorReset() invalidates the pending creation and drops pre-reset pending positions, while clearDelayedMessagesAfterBacklogClear() keeps positions above mark-delete. testBacklogClearPreservesPendingPositionsAboveMarkDelete verifies that a position published after the clear capture stays pending and is installed by the retry.

ghost Nov 19, 2026

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.

Additional fix in fdf50f0: if the pending tracker creation succeeds during the backlog clear, the preserved post-clear positions are reinstalled after clearDelayedMessages() runs, instead of being cleared with the old tracker state. testBacklogClearReinstallsPendingPositionsAfterCreationSuccess covers this success path; the existing failure/retry path remains covered by testBacklogClearPreservesPendingPositionsAboveMarkDelete.

if (topic.isDelayedDeliveryEnabled()
&& topic.getBrokerService().getDelayedDeliveryTrackerFactory()
instanceof BucketDelayedDeliveryTrackerFactory bucketDelayedDeliveryTrackerFactory) {
return bucketDelayedDeliveryTrackerFactory.cleanResidualSnapshots(cursor)

ghost Nov 18, 2026

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.

Invalidate a pending tracker retry before deleting the snapshots it recovered

A configured bucket-factory subclass fails creation once. Its retry recovers a multi-segment bucket but has not yet installed the tracker when a backward reset starts. Reset can delete the snapshot and then install the pre-reset tracker. Replay deduplicates against its restored bitmap, but when the dispatcher reaches the next segment it repeatedly tries to read a ledger that no longer exists. Those delayed messages can stop progressing.

The first failure settles 'delayedDeliveryTrackerCreateFailureFuture', so the reset can proceed to residual deletion without waiting for the retry. Only the exact built-in factory receives 'skipRecovery'; subclasses use the one-argument 'newTrackerAsync'. Clearing 'messagesPendingDelayedDeliveryTracker' does not clear indexes recovered inside that tracker, and the unchanged creation future still passes the identity check at installation. The late-retry test returns an empty mock tracker.

Invalidate the pre-reset creation attempt under the dispatcher lock so a late tracker is closed rather than installed; let post-reset replay create a fresh tracker. Test with a real recovered tracker whose installation is gated until after reset, and verify delivery across a segment boundary.

ghost Nov 19, 2026

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 f6fc6fc. Reset invalidates the in-flight creation under the dispatcher lock and completes the old create/skip signals, so delayedDeliveryTrackerCreated treats the late result as stale and closes the tracker instead of installing state recovered from snapshots the reset deleted. testCursorResetInvalidatesInFlightTrackerCreation gates a creation until after reset and asserts the tracker is closed and no messages are installed.

if (ex != null) {
// Roll back the replacement, so the property keeps referencing the
// superseded ledger and a later save can retry the delete.
ctx.bucketSnapshotStorage().deleteBucketSnapshot(newBucketId);

ghost Nov 18, 2026

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.

Do not lose the replacement ledger when rollback fails

Replay creates replacement ledger B. Deleting superseded ledger A fails, and the same storage failure also prevents the compensating delete of B. The cursor property still names A, but no property or retry record names B. Later cleanup can find A, not B; repeated reseals can leak BookKeeper storage.

The callback discards the future returned by 'deleteBucketSnapshot(newBucketId)'. The save fails before 'setBucketId(newBucketId)', and the failed-create handler removes the bucket and falls back to memory. Neither path owns B after the rollback failure. The reseal test covers a successful delete of A, not this branch.

Avoid allocating B while A still needs deletion, or compose the rollback and retain B's ID for cleanup if rollback fails. Add a test that fails both deletes, restores storage, and verifies that B is removed without losing the reference to A.

ghost Nov 19, 2026

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 f6fc6fc. The superseded snapshot ledger is now deleted before the replacement is allocated; if the superseded delete fails, the save fails before creating the replacement, so no compensating delete can orphan a new ledger. testSaveDoesNotAllocateReplacementWhenSupersededDeleteFails asserts create is never called and the property still references the superseded ledger.

}
}), BucketSnapshotPersistenceException.class, MaxRetryTimes).thenCompose(newBucketId -> {
}), BucketSnapshotPersistenceException.class, MaxRetryTimes).thenCompose(newBucketId ->
deleteSupersededSnapshotLedger(bucketKey, newBucketId).thenCompose(__ -> {

ghost Nov 18, 2026

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.

Prevent an old cleanup retry from removing the replacement's cursor property

Reset fails to delete A and retains its bucket in 'uncleanedBuckets'. Replay later deletes A and publishes B under the same range key. On a subsequent clear, deleting B fails but retrying A succeeds because A is already gone. A's retry removes the property that now names B. B still exists, but after topic unload the broker has no durable reference with which to retry its deletion.

The replacement deletes A in storage without retiring A's tracker cleanup record. 'cleanImmutableBuckets()' retries that record on the next clear. 'asyncDeleteBucketSnapshot()' deletes by ledger ID but removes the cursor property by range key alone; a missing ledger counts as a successful delete. The residual scan cannot repair a key that has already been removed.

Remove a bucket property only if it still names the ledger being deleted. Check the expected ID inside the sequenced operation on every metadata-version retry. Extend the reseal regression with a second clear where B's delete fails, and assert that the property still points to B.

ghost Nov 19, 2026

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 f6fc6fc. asyncDeleteBucketSnapshot now removes the cursor property only if it still references the ledger being deleted, re-checking inside the sequenced operation on every BadVersion retry. testDeleteDoesNotRemoveReplacementCursorProperty verifies that a stale cleanup cannot remove a replacement's property.

@nodece
nodece requested a review from codelipenghui November 19, 2026 02:29

ghost 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 the thorough follow-up and for rebasing onto #26401. The one thread I had left open is resolved: clear() now waits for the pending load and deletes before cleaning, and the reset path reaches it.

I have two remaining concerns, both in the new clearAndReinstallPreservedPending path in PersistentDispatcherMultipleConsumers that handles an ordinary backlog clear (not the reset itself), and a test that would pass without the code it covers. See the inline comments. Splitting the backlog-clear changes into a separate PR would also keep this one focused on the reset fix.

ghost 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.

The four previous findings are addressed in their reported paths. The ordinary backlog-clear change was removed from #26420; reset now rejects a late tracker installation, deletes the old snapshot before allocating a replacement, and protects the replacement property from stale tracker deletes. All 17 focused cases passed. My recommendation remains request changes: reset can wake a waiting backlog clear whose independent snapshot cleanup then outlives the reset.

messagesPendingDelayedDeliveryTracker.clear();
}
if (createFuture != null) {
createFuture.complete(null);

ghost Nov 19, 2026

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.

Do not wake an independent snapshot cleanup when invalidating tracker creation

An ordinary backlog clear is waiting on a pending tracker creation that has not failed, and a reset invalidates that creation. This is reachable with a gated bucket-factory subclass, which does not receive the built-in skip-recovery signal. Keep the backlog clear's snapshot delete callback pending while the reset runs. The reset can finish and replay can publish a replacement snapshot under the same bucket key. The old backlog clear can then remove the replacement's cursor property, leaving its BookKeeper ledger unreferenced after unload. There is no need for the two metadata writes to overlap.

Completing the old creation future normally at line 1792 runs the backlog clear's continuation at lines 1754–1757. The dispatcher has already nulled the creation future and has no installed tracker, so that continuation starts 'cleanResidualSnapshots()' with its own property snapshot and sequencer. The reset starts and awaits a different cleanup at line 1797. The factory deletes by the captured ledger ID but removes by key unconditionally; the new ID check in 'ImmutableBucket' does not cover this path. BookKeeper's already-missing handling lets the reset delete and unpublish the original snapshot even if the first delete's callback is delayed.

Signal invalidation distinctly from successful creation so a waiting backlog clear cannot start a second residual cleanup, or have both operations join the same cleanup future before reset proceeds. Add a gated backlog-clear/reset test that releases the older delete only after a replacement property is published and verifies that the property survives.

ghost Nov 20, 2026

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 9b4a559. clearDelayedMessagesAfterCursorReset() now completes the invalidated creation future exceptionally instead of normally, so an ordinary backlog clear waiting on that creation fails and does not run a second cleanResidualSnapshots(). BucketDelayedDeliveryTrackerFactory#cleanResidualSnapshots also removes a cursor property only when it still references the deleted ledger. Added testCursorResetInvalidationFailsWaitingBacklogClear.

@nodece
nodece force-pushed the fix-reset-clear-delayed-messages branch from 657447d to f2b1a27 Compare November 20, 2026 11:30

ghost 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 the follow-up split. With the backlog-clear handling in #27666 and the bucket snapshot hardening in #27673, this PR now covers only the cursor-reset semantics, which makes it much easier to review. I checked the new head: clearDelayedMessagesAfterBacklogClear() in PersistentDispatcherMultipleConsumers.java:1743-1768 matches master again. Failing the invalidated creation future in PersistentDispatcherMultipleConsumers.java:1791-1796 closes the reset-vs-backlog-clear interleaving I asked about, and testCursorResetInvalidationFailsWaitingBacklogClear covers it. Since BucketDelayedDeliveryTrackerFactory is no longer touched, the malformed-property point I had in mind for the residual cleanup no longer applies: master still parses inside the sequenced supplier.

One small Javadoc nit below; otherwise the reset path looks good to me. The Preconditions check is currently failing, so the PR probably still needs its doc label.

ghost 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.

LGTM. Thanks for restoring the Javadoc. Dispatcher.java now differs from master only by the new clearDelayedMessagesAfterCursorReset() method, and the reset-path behaviour I checked in the previous round is unchanged.

Two things before merging: the PR is still marked as a draft, and the Preconditions check fails because there is no doc label yet (doc-not-needed looks right, since this is an internal broker change).

Zixuan Liu added 13 commits November 24, 2026 17:42
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
…r reset

Address the review findings on the reset-clears-delayed-state change:

- BookkeeperBucketSnapshotStorage only treated NoSuchLedgerExistsException
  (-7) as "ledger gone"; the default metadata-store BK driver reports
  NoSuchLedgerExistsOnMetadataServerException (-25) for a missing ledger,
  so once a snapshot ledger was deleted while its cursor property
  survived, every later reset/seek failed permanently (HTTP 500 for
  admin reset, UnknownError for consumer seek) and the property could
  not be cleaned up. deleteLedger and openLedger now use
  Errors.isNoSuchLedgerExistsException, which accepts both codes, so a
  stale property self-heals on the next recovery as well.
- The delayed state is a derived cache of the backlog, so a cleanup
  failure no longer fails the reset: log a WARN and continue with
  asyncResetCursor. The clear future only settles once every
  cursor-property write has completed (waitForAll is allOf), so
  continuing cannot race the reset persistence with a BadVersion.

Tests: a missing snapshot ledger (injected -25) no longer fails the
reset and the bucket properties are removed; a failing snapshot delete
(LedgerFencedException) leaves the reset usable, the retry succeeds and
a consumer can subscribe again; after a reset to the earliest position
every delayed message is redelivered exactly once.

Assisted-by: Claude Code
…e handling

Address the second review round on resetting delayed-delivery state:

- The WARN-and-continue handler was attached to the chain instead of the
  cleanup future, so a disconnect failure was downgraded to a cleanup
  warning: the reset proceeded without a successful disconnect and could
  report success instead of SubscriptionBusyException. The recovery
  handler now wraps the cleanup futures inside the successful-disconnect
  continuation, so only delayed-state cleanup failures are downgraded.
- clearDelayedMessages() never settles while a tracker creation retry is
  pending, which fenced the reset until a retry succeeded. The reset now
  clears through clearDelayedMessagesAfterBacklogClear(), which also
  observes the creation-failure signal and releases a pending recovery,
  so a late retry cannot install pre-reset positions.
- A dispatcher that does not own a bucket tracker (subscription type
  switched to Exclusive/Failover, or a tracker that fell back to the
  in-memory implementation) left the bucket cursor properties behind on
  a successful reset. After the dispatcher clear settles, the reset now
  also runs cleanResidualSnapshots, a no-op when a bucket tracker has
  already removed the properties.
- Replaying a reset re-seals the same ledger range and overwrote the
  bucket cursor property, the only durable reference to a snapshot
  ledger whose delete had failed. Saving a replacement snapshot now
  deletes the superseded ledger first; if that delete fails the
  replacement is rolled back and the save fails, so the property keeps
  referencing the superseded ledger until a later save retries.

Tests: a failed disconnect fails the reset with SubscriptionBusyException
without reaching asyncResetCursor; the reset-path clear settles on a
failed tracker creation while an ordinary clear keeps waiting; a reset
after a Shared-to-Exclusive switch removes the residual bucket
properties; and a replay after a failed clear deletes the superseded
snapshot ledger instead of orphaning it.

Assisted-by: Claude Code
clearDelayedMessagesAfterBacklogClear() removed pending positions only against the pre-reset mark-delete position, so a forward reset could leave positions between the old and new cursor positions waiting in messagesPendingDelayedDeliveryTracker. A tracker-creation retry that succeeded after the reset was released installed those pre-reset positions, and the tracker could deliver messages the reset had skipped.

The reset path now drops every pending position before releasing recovery. The reset cancels pending reads before this point, so the map contains only pre-reset positions; valid positions are re-derived by the replay from the new cursor position, and skipped positions stay skipped.

Adds a regression test with a failing creation followed by a gated successful retry, asserting the reset settles and the late retry installs an empty tracker without calling addMessage.

Assisted-by: Claude Code
…acker

A pending position can still arrive after the reset/backlog-clear has drained the pending map, for example from an in-flight read on the backlog-clear path. When a tracker-creation retry finally installs the tracker, addPendingMessagesToTracker() now drops every pending position at or below the current mark-delete position instead of installing entries the cursor has moved past.

Adds testTrackerInstallDropsPendingPositionsAtOrBelowMarkDeletePosition: after a failed creation and a released reset clear, a stale position at the new mark-delete position is dropped while a live position after it is still installed by the late retry.

Assisted-by: Claude Code
… cleanup

Adds testForwardResetSkipsDelayedMessagesAfterReset: delayed messages are snapshotted, the cursor is reset to latest, and a reconnecting consumer must not receive the skipped messages. The test also verifies the tracker count is zero and the pre-reset bucket cursor properties are removed.

Assisted-by: Claude Code
… and stale deletes

Addresses the four follow-up review findings:

- Separate reset cleanup from backlog-clear cleanup. Reset invalidates any in-flight tracker creation and drops pre-reset pending positions; an ordinary backlog clear only drops positions at or below mark-delete, preserving messages published after the clear was captured.

- Invalidate a pending tracker-creation attempt under the dispatcher lock, so a late retry closes the tracker instead of installing state recovered from snapshots that the reset deleted. Post-reset replay starts a fresh creation.

- Delete the superseded snapshot ledger before allocating its replacement. If the superseded delete fails, the save fails before creating the replacement, so no replacement ledger can be orphaned by a failed compensating delete.

- Remove a bucket cursor property only if it still references the ledger being deleted. A stale uncleaned-bucket retry cannot remove the property of a replacement snapshot.

Adds positive and negative tests for backlog-clear preservation, reset invalidation, install-time mark-delete filtering, superseded-delete failure, and stale cleanup property removal.

Assisted-by: Claude Code
The bucket snapshot storage/ledger fixes (-25 handling, superseded ledger deletion before replacement, conditional cursor-property removal) and their tests are moving to a separate ledger-lifecycle PR. This keeps apache#26420 focused on the reset-cursor delayed-state cleanup path.

Assisted-by: Claude Code
The bucket snapshot ledger fixes (-25 handling, superseded ledger deletion before replacement, conditional cursor-property removal) are part of the reset/replay cleanup path, so they stay in this PR. The backlog-clear pending-position handling is split into its own PR.

Assisted-by: Claude Code
… not run second cleanup

When a reset invalidates a tracker creation that an ordinary backlog clear is waiting on, completing the creation future normally wakes the backlog clear continuation and can start an independent cleanResidualSnapshots while the reset is deleting and republishing the same bucket keys. Complete it exceptionally instead, so the waiting clear fails rather than running a second cleanup. cleanResidualSnapshots also removes a cursor property only when it still references the ledger being deleted.

Adds testCursorResetInvalidationFailsWaitingBacklogClear.

Assisted-by: Claude Code
A repeated reset during an in-flight reset must fail with SubscriptionBusyException, and a later reset must succeed after the first completes. Adds testRepeatedResetFailsBusyWhileInProgressThenSucceeds.

Assisted-by: Claude Code
The missing-ledger handling (-25), the superseded-ledger delete before a
replacement snapshot is allocated, and the compare-and-remove guards for
the bucket cursor property moved to apache#27673, together with their tests, so
this PR reviews only the cursor-reset semantics. The reset cleanup
invokes those paths through unchanged APIs; re-add the reset-level
missing-ledger regression after apache#27673 lands.

Assisted-by: Claude Code
The reset path now has its own method and Javadoc; the backlog-clear
method's description no longer needs to cover the reset case.

Assisted-by: Claude Code
@nodece
nodece force-pushed the fix-reset-clear-delayed-messages branch from 124a6c4 to fdb8f5d Compare November 24, 2026 09:46

ghost 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.

LGTM. Thanks for rebasing onto master now that #27666 is in. I compared this head with the one I approved: the broker changes are the same, and the only test change is where two of master's tests ended up (see the inline note).
I'll re-review after this PR has been moved from draft to ready for review.

}

@Test
public void testBacklogClearPreservesPendingPositionsAboveMarkDelete() throws Exception {

ghost Nov 25, 2026

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.

[NIT] the rebase moves two unchanged master tests, adding diff churn

The rebase moved testBacklogClearPreservesPendingPositionsAboveMarkDelete and testTrackerInstallDropsPendingPositionsAtOrBelowMarkDeletePosition, which are already on master, below the new cursor-reset tests. Their content is identical to master, but the PR now deletes and re-adds about 100 lines of master's tests, which makes the diff and git blame harder to follow. Could you leave both where master has them (after testBacklogClearInstallsPreservedPositionsWhenClearFails) and add the new tests after them?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants