Skip to content

[fix][broker] Move newPosition to nextValidLedger:-1 to avoid cursor position and ledger inconsistency in ManagedCursorImpl - #25117

Merged
lhotari merged 8 commits into
apache:masterfrom
oneby-wang:async_mark_delete_trim_ledger
Nov 23, 2026
Merged

lhotari merged 8 commits into
apache:masterfrom
oneby-wang:async_mark_delete_trim_ledger

Conversation

@oneby-wang

@oneby-wang oneby-wang commented Dec 28, 2025 •

Copy link
Copy Markdown
Contributor

Motivation

Since nextValidLedger:-1 is a valid markDeletePosition, we should move newPosition to nextValidLedger:-1 to avoid cursor position and ledger inconsistency in ManagedCursorImpl whenever possible.

PR #25087 also made this change.

Modifications

  1. Modify ManagedCursorImpl.asyncMarkDelete() method, move newPosition to nextValidLedger:-1 if we reach the following conditions:
    a. if lastConfirmedEntry >= newPosition, and next ledger exists, and current ledger entries are all consumed.
    b. if lastConfirmedEntry < newPosition, next ledger exists, and newPosition == nextValidLedger:-1.

I think the previous code might have a little problem.
a. If newPosition == nextValidLedger:n, n is an non-negative number, we might set new newPosition to nextValidLedger:n which is greater than lastConfirmedEntry, which is the biggest problem.
b. We can not mark delete lac many times if we already moved markDeletePosition to nextValidLedger:-1.
c. We can not mark delete nextValidLedger:-1 directly if markDeletePosition is less than lac.

Position newPosition = ackBatchPosition(position);
if (ledger.getLastConfirmedEntry().compareTo(newPosition) < 0) {
boolean shouldCursorMoveForward = false;
try {
long ledgerEntries = ledger.getLedgerInfo(markDeletePosition.getLedgerId()).get().getEntries();
Long nextValidLedger = ledger.getNextValidLedger(ledger.getLastConfirmedEntry().getLedgerId());
shouldCursorMoveForward = nextValidLedger != null
&& (markDeletePosition.getEntryId() + 1 >= ledgerEntries)
&& (newPosition.getLedgerId() == nextValidLedger);
} catch (Exception e) {
log.warn("Failed to get ledger entries while setting mark-delete-position", e);
}

And snapshot positions into a local variable to avoid race condition.

  1. Add testAsyncMarkDeleteMoveToNextLedgerInNonRolloverScenario, testAsyncMarkDeleteMayMoveToNextLedgerInRolloverScenario, testAsyncMarkDeleteMoveToNextLedgerOneByOne, testAsyncMarkDeleteNextLedgerMinusOneEntryIdPosition tests in ManagedCursorTest to verify the code change.

  2. Fix tests due to this PR's code change.

  3. Fix some flaky tests introduced by PR [fix][broker] Fix cursor position persistence in ledger trimming #25087.

Verifying this change

  • Make sure that the change passes the CI checks.

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

Documentation

  • doc
  • doc-required
  • doc-not-needed
  • doc-complete

Matching PR in forked repository

PR in forked repository: oneby-wang#19

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 fixes cursor position and ledger inconsistency in ManagedCursorImpl by moving the mark delete position to nextValidLedger:-1 when all entries in the current ledger are consumed. This addresses potential inconsistencies where the cursor position and ledger state could become misaligned.

Key Changes

  • Modified ManagedCursorImpl.asyncMarkDelete() to intelligently move cursor position to nextValidLedger:-1 when appropriate
  • Added snapshot positions to local variables to prevent race conditions
  • Added four comprehensive test cases to verify the new mark delete behavior
  • Updated existing tests to reflect the new cursor positioning behavior

Reviewed changes

Copilot reviewed 8 out of 8 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/ManagedCursorImpl.java Core logic change to move cursor position to nextValidLedger:-1 when ledger entries are fully consumed; snapshots positions to avoid race conditions
managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedCursorTest.java Added four new test cases (testAsyncMarkDeleteMoveToNextLedgerInNonRolloverScenario, testAsyncMarkDeleteMayMoveToNextLedgerInRolloverScenario, testAsyncMarkDeleteMoveToNextLedgerOneByOne, testAsyncMarkDeleteNextLedgerMinusOneEntryIdPosition) and updated existing tests to use relaxed assertions
managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerTest.java Updated testNoRetention test to use Awaitility for proper async handling and updated assertions for cursor position validation; fixed flaky tests
pulsar-broker/src/test/java/org/apache/pulsar/compaction/CompactedTopicTest.java Updated test assertions to expect cursor position at currentLedgerId:-1 after compaction
pulsar-broker/src/test/java/org/apache/pulsar/broker/service/persistent/PersistentTopicProtectedMethodsTest.java Changed exact equality assertions to greater-than-or-equal assertions for mark delete position
pulsar-broker/src/test/java/org/apache/pulsar/broker/service/PersistentMessageFinderTest.java Updated message expiry tests to expect mark delete position at nextLedgerId:-1
pulsar-broker/src/test/java/org/apache/pulsar/broker/service/MessageTTLTest.java Fixed spelling from "exacly" to "exactly" and updated test to expect cursor at currentLedgerId:-1
pulsar-broker/src/test/java/org/apache/pulsar/broker/service/BacklogQuotaManagerTest.java Updated assertions to reflect that mark deleting moves cursor to nextLedgerId:-1

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@codecov-commenter

codecov-commenter commented Jan 2, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 73.68421% with 5 lines in your changes missing coverage. Please review.
✅ Project coverage is 74.56%. Comparing base (9c5e1c3) to head (cb0364f).
⚠️ Report is 16 commits behind head on master.

Files with missing lines Patch % Lines
...che/bookkeeper/mledger/impl/ManagedCursorImpl.java 73.68% 4 Missing and 1 partial ⚠️
Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff              @@
##             master   #25117      +/-   ##
============================================
+ Coverage     74.44%   74.56%   +0.12%     
- Complexity    34046    34077      +31     
============================================
  Files          1899     1899              
  Lines        149655   149711      +56     
  Branches      17393    17405      +12     
============================================
+ Hits         111412   111636     +224     
+ Misses        29368    29199     -169     
- Partials       8875     8876       +1     
Flag Coverage Δ
inttests 26.35% <47.36%> (+0.21%) ⬆️
systests 23.08% <15.78%> (+0.09%) ⬆️
unittests 74.08% <73.68%> (+0.09%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
...che/bookkeeper/mledger/impl/ManagedCursorImpl.java 78.49% <73.68%> (-0.48%) ⬇️

... and 93 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

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

avoid cursor position and ledger inconsistency in ManagedCursorImpl whenever possible.

Could you share which test can show the inconsistency? I see some tests are added to ManagedCursorTest, which only verify the new behavior of this PR. But it's still confusing to me that what's wrong with the current behavior.

@oneby-wang

oneby-wang commented Jan 8, 2026 •

Copy link
Copy Markdown
Contributor Author

This PR is inspired by #25087.

If a cursor consumes the last entry of previous ledger, I think we should move the markDeletePosition to nextValidLedger:-1. If we don't move the markDeletePosition, once the previous ledger is trimmed, cursor's markDeletePosition is inconsistent with ledger data.

Could you share which test can show the inconsistency?

ManagedCursorTest.testAsyncMarkDeleteMoveToNextLedgerInNonRolloverScenario() and ManagedCursorTest.testAsyncMarkDeleteMoveToNextLedgerOneByOne().

But, unfortunately, we can not ensure happens-before between ManagedCursoImplr.asyncMarkDelete() and ManagedLedgerImpl.maybeUpdateCursorBeforeTrimmingConsumedLedger() in ledger rollover, so this is the only inconsistency reason after this PR(could be handled by ledger trim process), see also ManagedCursorTest.testAsyncMarkDeleteMayMoveToNextLedgerInRolloverScenario

But it's still confusing to me that what's wrong with the current behavior.

I think current behavior is not wrong, they all worked well besides the following code(see PR description).

Position newPosition = ackBatchPosition(position);
if (ledger.getLastConfirmedEntry().compareTo(newPosition) < 0) {
boolean shouldCursorMoveForward = false;
try {
long ledgerEntries = ledger.getLedgerInfo(markDeletePosition.getLedgerId()).get().getEntries();
Long nextValidLedger = ledger.getNextValidLedger(ledger.getLastConfirmedEntry().getLedgerId());
shouldCursorMoveForward = nextValidLedger != null
&& (markDeletePosition.getEntryId() + 1 >= ledgerEntries)
&& (newPosition.getLedgerId() == nextValidLedger);
} catch (Exception e) {
log.warn("Failed to get ledger entries while setting mark-delete-position", e);
}

@BewareMyPower

Copy link
Copy Markdown
Contributor

once the previous ledger is trimmed, cursor's markDeletePosition is inconsistent with ledger data.

Could there be any real issue caused by this inconsistency? It would be helpful if you can share a test to show the impacts. For example, generally computing (x, y+1) as the next position of (x, y) works in most cases even if there is no entry located in (x, y+1) because the compareTo implementation guarantees (x, y) < (x, y+1) < (x+1, 0).

I think it's a bit different from #25087. From what I understand, #25087 mainly fixes the bug that onCursorMarkDeletePositionUpdated is called directly without calling asyncMarkDelete.

@oneby-wang

oneby-wang commented Jan 8, 2026 •

Copy link
Copy Markdown
Contributor Author

I think at least we should snapshot immutable positions into local variables to avoid race condition, or phenomena and logs will not match. The volatile positions may be updated by other threads when retrieving it again or logging.

@oneby-wang

Copy link
Copy Markdown
Contributor Author

Could there be any real issue caused by this inconsistency?

In continuous consuming, this should rarely happens.

I was intened to do this thing: make sure markDeletePosition is moved to nextValidLedger:-1 once the new ledger is created. But as mentioned before, we can not ensure happens-before between ManagedCursoImplr.asyncMarkDelete() and ManagedLedgerImpl.maybeUpdateCursorBeforeTrimmingConsumedLedger().

Now, I intend to consolidate all the logic for moving the markDeletePosition to nextValidLedger:-1 into the asyncMarkDelete() method. Both maybeUpdateCursorBeforeTrimmingConsumedLedger() and the ledger trim process can reuse this part of the logic.

@oneby-wang

Copy link
Copy Markdown
Contributor Author

After this PR, if we want to move markDeletePosition to nextValidLedger:-1, we just do cursor.asyncMarkDelete(cursor.getMarkDeletePosition()). In non-move-forward case, mark deleting current mark-deleted position is safe, see also:

@Test(timeOut = 20000, dataProvider = "useOpenRangeSet")
void testMarkDeleteTwice(boolean useOpenRangeSet) throws Exception {
ManagedLedger ledger = factory.open("my_test_ledger", new ManagedLedgerConfig()
.setUnackedRangesOpenCacheSetEnabled(useOpenRangeSet).setMaxEntriesPerLedger(2));
ManagedCursor cursor = ledger.openCursor("c1");
Position p1 = ledger.addEntry("entry1".getBytes());
cursor.markDelete(p1);
cursor.markDelete(p1);
assertEquals(cursor.getMarkDeletedPosition(), p1);
}

@oneby-wang
oneby-wang force-pushed the async_mark_delete_trim_ledger branch 2 times, most recently from ad55d0b to ffa7d8f Compare January 9, 2026 09:26
@oneby-wang

oneby-wang commented Jan 12, 2026 •

Copy link
Copy Markdown
Contributor Author

Wrong behaviours in previous code that could cause test failures: ManagedCursorTest.testMarkDeletePositionNeverExceedLacOrNextLedgerMinusOneEntryIdPos() and ManagedCursorTest.testMarkDeletePreviousLacManyTimesInRolloverScenario().

@oneby-wang
oneby-wang force-pushed the async_mark_delete_trim_ledger branch from 526e841 to 039a822 Compare January 13, 2026 00:59
@oneby-wang
oneby-wang marked this pull request as draft January 13, 2026 01:49
@oneby-wang
oneby-wang force-pushed the async_mark_delete_trim_ledger branch 2 times, most recently from 91202bb to 667d3c8 Compare January 13, 2026 01:58
@oneby-wang
oneby-wang force-pushed the async_mark_delete_trim_ledger branch from 667d3c8 to 5d285ee Compare January 13, 2026 02:07
@oneby-wang

Copy link
Copy Markdown
Contributor Author

Another inconsistent test case is: ManagedLedgerTest.testTrimmerRaceConditionInNonDurableCursor().

If we don't move markDeletedPosition to nextValidLedger:-1, non-durable cursor's markDeletedPosition will be inconsistent with ledger data. See assert: assertEquals(cursor.getMarkDeletedPosition(), PositionFactory.create(emptyLedgerId, -1)).

Without this PR, the assert should be assertEquals(cursor.getMarkDeletedPosition(), PositionFactory.create(p, 0)).

@oneby-wang
oneby-wang marked this pull request as ready for review January 14, 2026 08:34
@oneby-wang

Copy link
Copy Markdown
Contributor Author

Squashed commits and rebased master, ready for review.

@lhotari lhotari modified the milestones: 4.2.0, 4.3.0 Apr 27, 2026
@lhotari lhotari modified the milestones: 5.0.0-M1, 5.0.0 Sep 12, 2026

@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 detailed reply. You are right about getNextValidLedger, and I have no further concern about that point. I found one rollover race in the new check and I would also like a test for partially acked batches. Details are inline and in the thread.

Signed-off-by: Matteo Merli <[email protected]>

# Conflicts:
#	managed-ledger/src/main/java/org/apache/bookkeeper/mledger/impl/ManagedCursorImpl.java
#	managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedCursorTest.java
#	managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/ManagedLedgerTest.java
#	pulsar-broker/src/test/java/org/apache/pulsar/broker/service/MessageTTLTest.java
#	pulsar-broker/src/test/java/org/apache/pulsar/broker/service/persistent/PersistentTopicProtectedMethodsTest.java
… mark-delete position

While a ledger is open its LedgerInfo has entries == 0, and the closed
info is stored before the next ledger is added. Reading the ledger info
first could pair the open ledger's placeholder with the next ledger of a
concurrent rollover, so the cursor jumped to nextLedger:-1 and skipped
unconsumed entries.

Also add a test for a partly and a fully acked batch on the last entry of
a rolled-over ledger, and adapt two tests added on master since this PR
was opened to the new mark-delete behavior.

Assisted-by: Claude Code (claude-opus-5-5)
…stimator test

testEstimatedUnackedSizeRejectsUnconfirmedEntryInEmptyLedger relied on
asyncMarkDelete accepting an entry of the next ledger beyond the last
confirmed entry. That is now rejected, so assert it and set the invalid
position directly to keep testing the estimator guard.

Assisted-by: Claude Code (claude-opus-5-5)
@merlimat

Copy link
Copy Markdown
Contributor

Hi @oneby-wang, I picked this up as part of the open-PR backlog pass (dev@ thread) and pushed a few commits on top of yours. Your authorship of the change is unchanged:

  • Merged master (no rebase). I resolved the conflicts and converted the new log statements to slog (PIP-467). Master had already deflaked testNoRetention and PersistentTopicProtectedMethodsTest, so I kept its versions of those.
  • Rollover race (lhotari's comment): asyncMarkDelete now reads getNextValidLedger() before getLedgerInfo(). ledgerClosed stores the closed LedgerInfo before the next ledger is added, so an open ledger's placeholder (entries == 0) can no longer be paired with a freshly added next ledger.
  • Partly acked last batch: added testAsyncMarkDeleteBatchOnLastEntryOfRolledOverLedger. A partly acked batch on the last entry of a rolled-over ledger keeps the cursor on the previous entry; a fully acked one moves it to next:-1.
  • Three master tests added since this PR was opened assumed the old behavior, and I adapted them: recoverCursorPropertiesWhenCursorLedgerIsEmpty, testAdvanceCursorsIfNecessaryNeverLoseMarkDeleteProperties and testEstimatedUnackedSizeRejectsUnconfirmedEntryInEmptyLedger. The last one relied on asyncMarkDelete accepting an entry of the next ledger beyond LAC, which this PR now correctly rejects.

@lhotari, could you take another look?

@merlimat merlimat modified the milestones: 5.0.0, 5.1.0 Oct 26, 2026

@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 picking this up and addressing both follow-ups. Reading the next ledger before the ledger info closes the rollover race, and the new batch test covers the partly and fully acked last entry. I have one small question about acknowledging an entry just past the end of a rolled-over ledger.

@lhotari

lhotari commented Nov 19, 2026

Copy link
Copy Markdown
Member

Thanks for picking this up. I looked at the new commits: the swapped read order closes the rollover race, and the batch test pins the partly and fully acked cases. The adapted tests look sound. I left one small question inline about accepting an entry just past the end of a rolled-over ledger.

…_trim_ledger

# Conflicts:
#	pulsar-broker/src/test/java/org/apache/pulsar/broker/service/BacklogQuotaManagerTest.java
@oneby-wang

Copy link
Copy Markdown
Contributor Author

@merlimat @lhotari Thanks for picking this up. I merged master into the PR branch and resolved the conflict in BacklogQuotaManagerTest. I kept the explicit quota check from master and the PR’s assertions that eviction leaves one empty ledger and clears the backlog. All tests passed in my personal CI.

@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 merging master and for explaining the reasoning behind >=. The merge leaves the PR's own changes as they were; the BacklogQuotaManagerTest conflict keeps master's explicit backlogQuotaCheck() call and the PR's assertions that eviction trims down to one empty ledger, which looks right.

The one open question is the >= normalization, answered in that thread.

@oneby-wang
oneby-wang requested a review from lhotari November 23, 2026 09:44

@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 adding the test and the comment. testMarkDeleteOnePastEndWithEmptyNextLedger (ManagedCursorTest.java:7957) covers the exact case: LAC stays at A:1, the next ledger is empty, and markDelete(A:2) ends at B:-1. It also pins the >=, because with == that call would be rejected as ahead of LAC. The note at ManagedCursorImpl.java:2690-2691 explains why the condition is intentional, and the comment in testMarkDeletePositionNeverExceedLacOrNextLedgerMinusOneEntryIdPos now describes the older-ledger case it actually covers.

@lhotari
lhotari merged commit b94351a into apache:master Nov 23, 2026
43 checks passed
lhotari pushed a commit that referenced this pull request Nov 24, 2026
…position and ledger inconsistency in ManagedCursorImpl (#25117)

(cherry picked from commit b94351a)
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.

6 participants