Skip to content

[fix][broker] Fail queued mark-deletes when the cursor closes - #27743

Open
Jeremiah-D wants to merge 2 commits into
apache:masterfrom
Jeremiah-D:fix/27709-fail-queued-mark-deletes
Open

Jeremiah-D wants to merge 2 commits into
apache:masterfrom
Jeremiah-D:fix/27709-fail-queued-mark-deletes

Conversation

@Jeremiah-D

@Jeremiah-D Jeremiah-D commented Nov 25, 2026 •

Copy link
Copy Markdown

Fixes #27709

asyncClearBacklog is a thin shell over asyncMarkDelete, and every early return in there calls the callback. The hole is in close: asyncClose persists just the last mark-delete entry and never touches pendingMarkDeleteOps, so a mark-delete that queued while reads were in flight (or a ledger switch was running) sits there with its callback never firing. I checked the other drain points and they all group the queue onto a persisted entry — close is the only path that doesn't.

Since #27666 merged, the broker only releases its backlog-clear fence from that callback, so a dropped callback leaves the fence set for good. This drains the queue in persistPositionAndCompleteClose and fails whatever is left with CursorAlreadyClosedException, the same exception the metadata-ledger failure path already uses in this file.

One regression test holds a read in flight, calls asyncClearBacklog so it queues, then closes the cursor and asserts the clear callback fires with CursorAlreadyClosedException and the close still completes.

I couldn't run the tests locally (no Gradle toolchain on this machine), so please let CI be the judge on that part.

I left the reset path alone — clearing the queue there without calling back looks fragile too, but I couldn't build a reachable interleaving for it, so that's a separate discussion.

Update: CI caught a deadlock in the new test itself — with the entries cached the held read can complete inline on the test thread, so the callback blocked there waiting for releaseRead and the test timed out before it ever reached asyncClearBacklog. Pushed d3d64a0: the read is now issued from its own thread (the callback blocks there instead) and joined before the ledger closes. The fix itself is unchanged; the only failing check was that one test (641 passed, 1 failed).

Copilot AI balanced review requested due to automatic review settings November 25, 2026 05:28

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.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

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

Verified independently against master, as the reporter of #27709:

  • The bug is real and precisely located: internalAsyncMarkDelete queues entries while PENDING_READ_OPS > 0 under Open, readOperationCompleted only flushes under Open, and persistPositionAndCompleteClose persists just lastMarkDeleteEntry without ever touching pendingMarkDeleteOps — so a mark-delete queued behind an in-flight read loses its callback at close. Since #27666, the broker releases its backlog-clear fence and buffering gate only from the clear callback, so this pins them forever; that is exactly #27709.
  • The fix follows the existing precedent at the ledger-switch drain site: the established pendingMarkDeleteOps monitor, drain inside, failMarkDeletes outside the lock so callbacks never run under it, and CursorAlreadyClosedException matching what the switch path already uses.
  • No residual race: a mark-delete arriving after the drain, while the state is Closing, still gets a failed callback through internalAsyncMarkDelete's default branch.
  • asyncClearBacklog is indeed a thin shell over asyncMarkDelete, so the failed entry surfaces as clearBacklogFailed — the settle path #27666 waits for.
  • The test models the exact interleaving (read held open → clear queues → close → callback fires with CursorAlreadyClosedException, close still completes).

Non-blocking, pre-existing: the default branch reports a generic "invalid state" message rather than CursorAlreadyClosedException for Closing; and agree the reset-path queue handling is worth a separate discussion.

…klogFailsOnCloseWithPendingReads

With the entries cached the read can complete inline on the calling
thread, so the callback blocked the test thread itself waiting for
releaseRead and TestNG timed the test out before asyncClearBacklog
was even called (CI - Unit - Other). Issuing the read from a
dedicated thread keeps the read in flight while the test thread
drives clear-backlog and close; the thread is joined before the
ledger closes.

Signed-off-by: Jeremiah-D <[email protected]>

@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 down and for the clear write-up of where the queued mark-delete gets stranded.

I couldn't run the tests locally (no Gradle toolchain on this machine), so please let CI be the judge on that part.

Being able to build and run the tests locally is a prerequisite for contributing changes like this one, so please get that working before the next round. The good news is that it's quick to set up: you don't need to install Gradle separately. With Java 25 installed, ./gradlew bootstraps everything. https://pulsar.apache.org/contribute/setup-building/ has the details.
Please also keep our AI contribution policy in mind: https://github.com/apache/pulsar/blob/master/AGENTS.md#licensing-and-provenance-read-first. AI-assisted contributions are welcome, but we rely on the contributor to validate the change. Without that validation, a PR gives us little beyond what we would get by running an agent on the backlog issue ourselves.

You can run the full Pulsar CI in your own fork with Personal CI. It is very useful: CI runs on PRs from external contributors wait here until a maintainer approves them, while in your fork they start right away, and running the early CI rounds in your fork's own GitHub Actions saves the project's CI resources. Add the link to the PR in your fork in the "Matching PR in forked repository" section of the description.

Draining pendingMarkDeleteOps in persistPositionAndCompleteClose and failing what is left looks like the right direction to me. The main problem is the regression test: as written, it cannot reach the queued-on-close path, so it fails with the fix as well (details inline). There are also a few smaller points: one throwing callback can now block the close, durable cursor deletion has the same gap, and there is an optional idea about persisting the queued position instead of failing it.

On the reset path you left out (ManagedCursorImpl.java:1894): one reachable interleaving is a reset whose write is in flight on an Open cursor, then a read starts, then an individual asyncDelete queues behind it (asyncDelete has no reset-in-progress guard). When the reset succeeds, it clears the queue without calling that delete's callback. That is pre-existing and fine to handle in a separate issue.


// Without the fix the clear callback never fires and this times out.
assertTrue(clearDone.await(10, TimeUnit.SECONDS));
assertNotNull(clearFailure.get());

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.

[BUG] The new test cannot reach the queued-mark-delete-on-close path, so it fails with the fix too

Two things keep asyncClearBacklog from ever queuing behind a read here:

  • No read is in flight while the callback blocks. OpReadEntry.checkReadCompletion calls cursor.readOperationCompleted() before complete(ctx) invokes the user callback (OpReadEntry.java:303-305). By the time readStarted counts down, the pending-read count is already 0.
  • A freshly opened cursor is in NoLedger (ManagedCursorImpl.java:1028). The first mark-delete takes the case NoLedger branch: it queues and starts a metadata-ledger switch. asyncClose waits on ledgerSwitchFuture, and the switch's flushPendingMarkDeletes persists the clear successfully (the switch rejects Closed only, not Closing).

Either way clearBacklogComplete fires. clearFailure stays null and assertNotNull here fails. If the blocked callback lands on a thread the cursor-ledger creation needs, the test fails one line earlier, on the clearDone timeout. The comment above ("Without the fix the clear callback never fires") does not match what happens either.

To hold a read for real, testResetCursorIsNotDroppedByAckQueuedBehindIt (ManagedCursorTest.java:8410-8440) has a pattern you can reuse:

  1. Install bkc.setReadHandleInterceptor(...) and call cursor.setInactive() before adding the entries, so reads go to the bookie instead of the cache.
  2. markDelete once, so the cursor reaches Open.
  3. Turn on the hold and issue the read.
  4. Assert getPendingReadOpsCount() == 1 and that the clear is still pending before you call asyncClose.
  5. Release the held read in a finally.

With that, it would be worth checking that the test actually fails without the production change.

assertNotNull(clearFailure.get());
assertTrue(clearFailure.get() instanceof ManagedLedgerException.CursorAlreadyClosedException);
assertTrue(closeDone.await(10, TimeUnit.SECONDS));
releaseRead.countDown();

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.

[QUALITY] Test cleanup and callback failures are not reliable

releaseRead.countDown(), readThread.join() and ledger.close() run only when every assertion passes. On a failure, the read callback stays parked in releaseRead.await() with no timeout, and the ledger is left open. Please move the release, join and close into a finally (and bound the await).

Also, fail(...) inside readEntriesFailed and closeFailed runs on a library thread. OpReadEntry catches and logs a throwing callback, so a real read or close failure only shows up as a latch timeout. Recording the exception in an AtomicReference (or a CompletableFuture) and asserting on it from the test thread gives a useful failure message.

synchronized (pendingMarkDeleteOps) {
queuedMarkDeletes = drainPendingMarkDeletes();
}
failMarkDeletes(queuedMarkDeletes,

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.

[BUG] A throwing mark-delete callback now prevents the close from completing

failMarkDeletes calls each caller's markDeleteFailed with no per-entry isolation, and it runs before persistPositionWhenClosing. The whole method is the action of switchFuture.thenRun(...) (ManagedCursorImpl.java:3699), and that stage's result is discarded.

If one callback throws:

  • the remaining callbacks are skipped;
  • the final position is never persisted;
  • the cursor stays in Closing and the CloseCallback never fires;
  • nothing is logged.

A later asyncClose then reports success right away, because Closing counts as closed. One way to hit this: PersistentSubscription's clearBacklogFailed submits to topic.getOrderedExecutor() (PersistentSubscription.java:948), and that submission can be rejected while the broker is shutting down.

Wrapping each callback in a try/catch that logs (in failMarkDeletes), or failing the queue after starting the close persistence, would keep the close path independent of callers.

// A mark-delete queued while reads were in flight is never flushed once the state moves to
// Closing: readOperationCompleted only flushes while Open, and closing persists just the
// last mark-delete entry. Fail the leftovers here so their callers (e.g. asyncClearBacklog)
// complete instead of hanging forever. The switch paths already drained or failed the

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.

[INTENT MISMATCH] Durable cursor deletion leaves queued mark-deletes unanswered the same way

The description says close is the only drain point that does not settle the queue, but ManagedLedgerImpl.asyncDeleteCursor has the same gap. It moves a durable cursor straight from Open to Deleting (ManagedLedgerImpl.java:1385) and deletes the cursor ledger without going through asyncClose. Nothing there touches pendingMarkDeleteOps, and readOperationCompleted flushes only when the state is Open (ManagedCursorImpl.java:4488).

So if a dispatcher read is in flight, a clear-backlog (or cumulative ack) queues, and the subscription is then unsubscribed, the clear callback never fires and the #27666 fence is never released. Could you either drain and fail the queue on the delete path as well, or narrow the claim in the comment and description and open a follow-up issue?

@@ -3701,6 +3701,17 @@ public void asyncClose(final AsyncCallbacks.CloseCallback callback, final Object

private void persistPositionAndCompleteClose(AsyncCallbacks.CloseCallback callback, Object ctx) {
MarkDeleteEntry entry = lastMarkDeleteEntry;

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.

[QUALITY] Suggestion (non-blocking): close could persist the queued position instead of failing it

This is a pre-existing behavior that the fix now makes visible, so it is not a blocker for this PR.

Before an entry is queued, asyncMarkDelete and asyncDelete have already applied it in memory through setAcknowledgedPosition. That moves markDeletePosition and trims individualDeletedMessages (ManagedCursorImpl.java:2686). Close then persists the older lastMarkDeleteEntry position together with the already-trimmed ranges. After a topic unload with reads in flight, the subscription can redeliver the queued window, and even individual acks that were persisted earlier.

The throttled mark-delete path already relies on close persisting the newest position (updateLastMarkDeleteEntryToLatest followed by markDeleteComplete). An alternative would be:

  • fold the newest non-reset queued entry into the close write (take the max with lastMarkDeleteEntry);
  • complete or fail those callbacks from the close outcome;
  • keep failing any queued reset entry.

If failing is the intended behavior, a sentence in the comment saying these acks are deliberately not persisted would help the next reader.

@Jeremiah-D

Copy link
Copy Markdown
Author

Thanks — all fair. I'll rewrite the test around the held-read pattern so it actually reaches the queued path and fails without the fix, isolate the callbacks in failMarkDeletes, and cover the delete-cursor gap as well. And I'll get the local build working and run Personal CI before the next push — point taken on validating first.

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

Since this is your first contribution to Apache Pulsar: you can run the full Pulsar CI in your own fork with Personal CI. It is very useful: CI runs on PRs from first-time contributors wait here until a maintainer approves them, while in your fork they start right away, and running the early CI rounds in your fork's own GitHub Actions saves the project's CI resources. Add the link to the PR in your fork in the "Matching PR in forked repository" section of the description.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[bug] A dropped asyncClearBacklog callback pins the broker's backlog-clear fence and the buffering gate forever

4 participants