Skip to content

[fix][ml] Prevent cursor close from racing ledger switch - #27671

Merged
codelipenghui merged 6 commits into
apache:masterfrom
NimeshXTV:fix/cursor-close-ledger-switch
Nov 23, 2026
Merged

codelipenghui merged 6 commits into
apache:masterfrom
NimeshXTV:fix/cursor-close-ledger-switch

Conversation

@NimeshXTV

Copy link
Copy Markdown
Contributor

Fixes #27047

Motivation

Closing a managed cursor while its metadata ledger is being created or switched can race with acknowledgements queued during that switch.

The close operation can persist the cursor position before the queued mark-delete operation finishes. Concurrent metadata updates can then conflict, potentially losing the latest durable acknowledgement and causing acknowledged messages to be redelivered after the cursor is reopened.

Modifications

  • Added a completion barrier for cursor metadata-ledger switches.
  • Made cursor close wait for both the ledger switch and mark-delete operations queued behind it.
  • Kept the barrier active while the cursor transitions back to Open and queued acknowledgements are still being persisted.
  • Propagated ledger-switch and mark-delete failures to the close callback.
  • Allowed an already-started ledger switch to finish after the cursor enters the Closing state.
  • Added a deterministic regression test covering close during ledger creation and the subsequent queued mark-delete write.

Verifying this change

  • Make sure that the change passes the CI checks.

This change added tests and can be verified as follows:

  • Added ManagedCursorCloseDuringLedgerSwitchTest, which pauses cursor-ledger creation and the queued mark-delete write independently and verifies that close waits for both.
  • Verified that the final metadata-store position matches the acknowledged entry.
  • Ran the following focused tests successfully:
./gradlew :managed-ledger:test \
  --tests 'org.apache.bookkeeper.mledger.impl.ManagedCursorCloseDuringLedgerSwitchTest' \
  --tests 'org.apache.bookkeeper.mledger.impl.ManagedCursorTest.testSwitchLedgerFailed' \
  --tests 'org.apache.bookkeeper.mledger.impl.ManagedCursorTest.cursorPersistence2'
  • Ran the managed-ledger formatting and static checks successfully:
./gradlew :managed-ledger:quickCheck

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

If the box was checked, please highlight the changes

  • 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

The cursor close sequence now waits for an active metadata-ledger switch and its queued mark-delete operations to complete before persisting the final cursor position.

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

Request changes. The async barrier fixes the tested close-during-switch sequence, and all seven focused tests passed. But a cursor-ledger creation failure can now prevent unload from saving acknowledgements that already completed, and a stale write count can release a later switch’s barrier too early.

@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 tracking this race down and for the deterministic regression test. It does reproduce the original problem: without the change, close persists through the metadata store while the cursor-ledger switch is still gated.

Making close wait for the switch is the right direction, but close is now coupled to the switch's outcome, which brings in a few new failure modes:

  • Close fails whenever the switch fails (bookies unavailable, a failed queued add). The cursor then stays in Closing without persisting anything. Before this change, close still wrote the position and ranges to the metadata store.
  • Close can hang forever when cursor-ledger creation ends without calling either switch callback.
  • The barrier can complete too early: on the NoLedger metadata-store fallback, and through a stale counter snapshot in decrementPendingMarkDeleteCount.

The smaller points are ledger creation in closed states and test coverage for the failure paths. Details are inline.

Please use Personal CI to get CI feedback and to ensure that CI passes for your changes without waiting for maintainer approval.

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

Request changes remains my recommendation. The head is unchanged, so neither earlier finding is resolved: close can still skip saving acknowledged progress after a switch failure, and a stale write count can still release the barrier early. The new review corroborates both and identifies two additional ordering problems: a create timeout can strand close, and close can race the metadata fallback. The requests for a fix, regression tests, and Personal CI are directed to the PR author; no reply from us is required.

@NimeshXTV

Copy link
Copy Markdown
Contributor Author

Addressed the review findings and added regression coverage for the cursor-ledger switch failure and ordering scenarios.

Personal CI passed successfully:
https://github.com/NimeshXTV/pulsar/actions/runs/44880136779

Could you please take another look?

@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 thorough follow-up. The new commits address most of the earlier points: close always persists the final position after the barrier, a creation that never delivers a handle now fails the switch, the counter decrement moved under the monitor, the barrier waits for the metadata-store fallback, and deferred creation no longer starts while the cursor is being deleted. The new tests cover the failure paths I asked about.

One ordering gap remains in operationFailed: a mark-delete failure callback that runs during the fallback flush can start a new switch, and the outer handler then completes the new switch's barrier early. There are also two smaller test robustness points. Details are inline.

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

Request changes. The revision addresses the previously reported cases: close preserves completed acknowledgements after a create error, the count and barrier decision share a lock, the create timeout settles the switch, the barrier waits for metadata fallback, and deletion blocks deferred creation. All nine focused tests passed. One new regression remains: close can persist a forward cursor reset after reporting that the reset failed.

Keep close waiting on the active cursor-ledger switch when a failure callback starts a replacement switch, and prevent failed cursor resets from becoming the close snapshot. Add deterministic regression coverage and harden the related timing tests.

@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 turnaround. The replacement-switch guard in createNewMetadataLedger resolves the re-entrant failure-callback case, and testCloseWaitsForReplacementSwitchStartedByFailureCallback covers it. Both test robustness points are fixed too.

The new resetsCursor check in internalMarkDelete fixes the failed-reset case, but it opens the opposite gap: a successful forward reset can now be lost when close overlaps its write. The new reset test can also pass without exercising the fix. Separately, the two new switch-tracking booleans could be a single enum, which would make the switch lifecycle easier to follow. Details are inline.

@NimeshXTV
NimeshXTV requested a review from lhotari November 23, 2026 12:52

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

LGTM. Thanks for working through all of these. A reset now updates lastMarkDeleteEntry when it is submitted and rolls it back only if its write fails (ManagedCursorImpl.java:2872-2873, ManagedCursorImpl.java:2914-2917), so a close that overlaps a successful reset keeps the reset position. testClosePersistsSuccessfulForwardResetWhileWriteIsInProgress covers that case. Because getProperties() reads lastMarkDeleteEntry, the compaction cursor keeps the reset entry's properties as well. The switch lifecycle is now a single LedgerSwitchPhase, and the failed-reset test arms its failure before the switch starts, so it is deterministic.

@codelipenghui
codelipenghui merged commit b939dd7 into apache:master Nov 23, 2026
43 checks passed
codelipenghui added a commit to codelipenghui/incubator-pulsar that referenced this pull request Nov 24, 2026
Resolve the conflicts in ManagedCursorImpl and adapt the publication path to
the cursor changes on master:

- apache#27703 rebuilds the cursor properties in updateCursorLedgerStat, so drop
  adoptStoredCursorInfo and keep only the deletion of retained ledgers there.
  Sample the version and the properties as one pair in publishCursorLedger as
  well as in persistPositionMetaStore, and pass them to buildManagedCursorInfo.
- apache#27652 assigns a publication ID in MetaStoreImpl during the write. Assign it
  in publishCursorLedger before taking the attempted bytes, so that
  reconciliation still recognizes a committed publication.
- apache#27671 makes a closing cursor wait for an in-flight ledger switch, so allow
  that switch to publish while the cursor is Closing.
- apache#26817 closes the read-only cursor ledger in asyncDeleteCursorLedger; keep
  that next to the deletion of retained ledgers.

MetaStoreImpl now calls the put overload with options, so the fault-injection
stubs in ManagedCursorTest target that overload.

Assisted-by: Claude Code (Claude Opus 5.5)
lhotari pushed a commit that referenced this pull request Nov 24, 2026
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.

[Bug] Unloading a topic while a cursor switches to a new cursor ledger loses the cursor's acks

3 participants