Repository navigation
[fix][broker] Preserve pending delayed positions after backlog clear - #27666
Conversation
…clear An ordinary backlog clear only discards the entries up to the mark-delete position captured when the clear started. Positions published after that capture must remain pending and be installed after the old tracker state is cleared, including when the pending tracker creation succeeds during the clear. The preserved positions are skipped during the initial tracker install while the backlog clear is in flight, then installed exactly once after clearDelayedMessages() settles; a clear failure still reinstalls them so they are not stranded. Positions at or below the current mark-delete position are dropped at install time. Adds positive and negative tests: preserved positions on failure/retry, reinstall after creation success, already-due position installed once, reinstall on clear failure, and install-time mark-delete filtering. Assisted-by: Claude Code
Simplify the backlog-clear fix: when a tracker creation is pending, invalidate it and keep positions above the captured mark-delete position. After clearDelayedMessages() settles, start a fresh tracker creation that installs the preserved positions exactly once. This avoids a clear-pending flag, an install-time skip, and a reinstall path, and the old late creation is closed instead of installed. Tests cover preserved positions on failure, old-creation invalidation, already-due single install, clear-failure without strand, and install-time mark-delete filtering. Assisted-by: Claude Code
|
If |
…clear settles An ordinary backlog clear can invalidate the pending tracker creation and then clear while a newly read position starts a different creation. That new creation can install the preserved position before the clear removes it. Keep positions arriving during the backlog clear in messagesPendingDelayedDeliveryTracker, skip the initial install while the clear is in flight, and install them once after the old tracker state has been cleared (or start a fresh creation when no tracker is installed). Adds tests for preserved positions, positions arriving during the clear, already-due single install, clear-failure reinstall, and install-time mark-delete filtering. Assisted-by: Claude Code
|
Good catch. The new head keeps positions arriving during the backlog clear in |
Assisted-by: Claude Code
A repeated clearBacklog while the first cleanup is in flight must join the same cleanup future. Without this, the second clear can run after the first one reinstalls the preserved pending positions and remove them again. Adds testRepeatedBacklogClearJoinsInFlightClear. Assisted-by: Claude Code
codelipenghui
left a comment
There was a problem hiding this comment.
Overlapping dispatcher cleanups now share one future, but that does not close the earlier race between sampling the backlog tail and starting the cleanup gate. A targeted regression reproduced the lost scheduling entry on '58b7732b9a'. Ten existing focused tests passed, including the new repeated-clear test.
…sor tail Entries published after asyncClearBacklog samples the tail but before the callback starts cleanup were added directly to the live tracker and then removed by the cleanup. The subscription now asks the dispatcher to buffer delayed entries before invoking the cursor clear, and releases the buffer after the cursor and tracker work settles, including on cursor-clear failure. Adds tests for pre-callback buffering and failure release. Assisted-by: Claude Code
clearBacklog() is now fenced per subscription, so a repeated clear fails with SubscriptionBusyException instead of racing the first one. Delayed-entry buffering starts before asyncClearBacklog samples the tail and is released through one idempotent dispatcher method on both success and failure. Adds testRepeatedClearBacklogFailsBusyWhileInProgressThenSucceeds and keeps the pre-callback buffering tests. Assisted-by: Claude Code
…ispatcher interface startBufferingDelayedMessagesForBacklogClear() and releaseBufferedDelayedMessagesAfterBacklogClear() were no-op defaults on the Dispatcher interface, but only PersistentDispatcherMultipleConsumers tracks delayed messages, so the buffering gate belongs on that class. PersistentSubscription now reaches them through an instanceof check, the same pattern it already uses for the multi-consumers dispatcher family. Also drop the redundant release on the backlog-clear success path: clearDelayedMessagesAfterBacklogClear() already releases the buffer when the delayed-state cleanup settles (including on cleanup failure), before the returned future completes. The subscription-side release remains only for the cursor-clear failure callback, where the dispatcher clear was never invoked. Assisted-by: Claude Code
codelipenghui
left a comment
There was a problem hiding this comment.
The subscription fence fixes the overlapping-clear race by rejecting a second clear before it reaches the cursor. The first-consumer race still reproduces on 'b67ffdaec9'. A separate test showed that disabling delayed delivery during a clear can leave the dispatcher buffering new messages indefinitely after re-enable. Twelve existing focused cases passed.
lhotari
left a comment
There was a problem hiding this comment.
Thanks for working through this tricky race, and for the clear write-up and the targeted tests.
The buffering gate does close the N+2 interleaving from the earlier question for a dispatcher that was armed before the clear sampled the tail. Some paths still strand delayed messages, or can block threads, so I'd like to see these addressed before merging:
- The delayed-delivery policy is read once when buffering starts and again during cleanup. A policy change between the two either leaves buffering on permanently or lets N+1 reach the live tracker, where the clear erases it (
PersistentDispatcherMultipleConsumers.java:1793). - Buffered entries that are already due when the clear settles go into the replay set, but nothing triggers a read (
PersistentDispatcherMultipleConsumers.java:1824). - The clear-failure callback now takes the dispatcher and subscription monitors while the cursor holds
pendingMarkDeleteOps. That reverses lock orders that already exist (PersistentSubscription.java:923). - The fence and the buffering flag are released only from the cursor callback. A synchronous throw, or a callback the cursor drops, leaves both set forever (
PersistentSubscription.java:877). - One gap is still open: buffering is armed only on the dispatcher that exists when the clear starts, so a dispatcher created or replaced while the mark-delete is in flight can still lose N+1 (
PersistentSubscription.java:884).
There are also smaller points on closed dispatchers, on the error an overlapping clear returns, and on tests that would pass against the pre-PR ordering. Details are inline.
codelipenghui
left a comment
There was a problem hiding this comment.
Request changes remains my recommendation. On unchanged head 'b67ffdaec9', the early gate still fixes the original race for a dispatcher that was already armed, and the subscription fence prevents overlapping clears. None of the three findings from the last review is resolved: late dispatcher attachment, a policy change leaving the gate armed, and expected contention surfacing as HTTP 500. The new review corroborates those points and raises additional concerns; it does not ask you a direct question. I reproduced the missing replay wakeup and confirmed the failure-path lock inversion in source.
…the clear lifecycle Address the review findings on backlog-clear buffering: - The buffering gate is now armed and released independently of the live delayed-delivery policy: startBuffering arms unconditionally, the disabled branch of clearDelayedMessagesAfterBacklogClear still drains and releases, and close() resets the flag. A policy flip during the mark-delete no longer leaves the gate armed forever or lets a fresh entry be erased by the cleanup. - A dispatcher created while a backlog clear is running buffers from the start, so a delayed entry it reads before the clear's cleanup runs is not erased by that cleanup. - The clear callbacks run on the topic's ordered executor instead of the cursor's mark-delete thread, which invokes callbacks while holding pendingMarkDeleteOps: the finalization takes the dispatcher and subscription monitors, and the reverse order exists through replicated-subscription ACK admission. - A synchronous throw from asyncClearBacklog or the delayed-state cleanup becomes a failed future that runs the release paths, so the fence and the gate cannot stay armed on a dropped callback path. - An overlapping clear chains onto the in-flight future instead of failing with SubscriptionBusyException (mapped to HTTP 500), matching the cursor's convergence of overlapping mark-deletes. - Releasing the buffer requests a read when entries were installed or a tracker creation started: due entries moved to the replay set need a read to be dispatched, and the release is not running inside a read loop. A closed dispatcher drops the buffered positions instead of starting a tracker nobody closes. - The pending-position removal guards against a null mark-delete position. Tests: the gated-clear tests assert no addMessage while the clear is pending (the base install-then-clear ordering fails them), the retry waits fold the verify calls in, and the overlap test covers the converge semantics. Assisted-by: Claude Code
Assisted-by: Claude Code
codelipenghui
left a comment
There was a problem hiding this comment.
The new commit removes one unused test import and changes no broker logic. GitHub reports 43 passing checks, and the focused overlap test passed locally on '1ff09f2b77'. My recommendation remains request changes: all three previously reproduced issues are still present in the unchanged implementation.
lhotari
left a comment
There was a problem hiding this comment.
Thanks for the quick turnaround. The new commit addresses most of the earlier points: the gate no longer depends on the live policy, the release triggers a read, the callbacks run on the topic executor, synchronous throws are handled, and the tests now catch the old install-then-clear ordering.
Two things remain, both in PersistentSubscription.clearBacklog():
- A second clear that overlaps an in-flight one now returns the first clear's future. The first clear sampled the tail when it started, so the second caller gets success while entries published between the two calls stay in the backlog (
PersistentSubscription.java:884). - A dispatcher created by
addConsumerInternal()after the callback has already picked the dispatcher to clean up is armed, and no one releases it. All of its delayed messages then stay in the pending map (PersistentSubscription.java:917).
Details are inline.
codelipenghui
left a comment
There was a problem hiding this comment.
My recommendation remains request changes. The head is unchanged, so none of the three findings from my last review is resolved. @lhotari independently confirms two of them: a later clear can report success without covering its newer tail, and a replacement dispatcher can stay armed after cleanup. The callback handoff, policy-toggle handling, and replay wakeup were already fixed on this head. No new comment asks you a direct question.
- An overlapping clear now queues a fresh clear behind the in-flight one instead of returning its future: the cursor samples the backlog tail per invocation, so the in-flight clear can miss entries published after it started, and the later caller's backlog would be reported cleared while those entries remain. - A dispatcher enrolled during the clear (created or replaced after the cleanup started on the previous dispatcher) is released without a second whole-tracker cleanup: its tracker holds post-tail entries only, so draining the buffer is enough. The no-dispatcher-at-start branch releases the enrolled dispatcher the same way. - A synchronous tracker failure inside clearDelayedMessagesAfterBacklogClear is normalized into the failed future the release handler is attached to, so the buffered entries are still released when clear() throws before returning its future. Assisted-by: Claude Code
codelipenghui
left a comment
There was a problem hiding this comment.
Two prior findings are fixed: a queued clear samples a fresh tail after its predecessor succeeds, and a synchronous tracker cleanup failure now releases the buffer. I still recommend changes. A dispatcher that attaches after cleanup starts can remain in buffering mode, and a queued clear is skipped if its predecessor fails. Both cases reproduced on '915530042e'; fourteen focused cases passed.
…og clear A dispatcher enrolled after the cleanup started arms its buffering gate, but the completion had already chosen the cleanup path for the dispatcher the clear started on, so the late dispatcher stayed in buffering mode. Every dispatcher that arms for the clear now registers on it, and the settle - on success, cursor-clear failure, and startup failure - releases every registered dispatcher and clears the fence, isolating per-dispatcher release failures so the clear's future always settles. A queued clear chained with thenCompose, so a predecessor failure skipped it: the queued caller's backlog was not cleared by the predecessor. The queue now chains through handle and always re-invokes clearBacklog as a fresh invocation with its own tail sample, mirroring how addConsumer chains on inProgressResetCursorFuture. Assisted-by: Claude Code
|
Both findings are fixed in 33c7f00: A dispatcher that attaches after cleanup starts can remain in buffering mode. Every dispatcher that arms for the clear now registers on it — the one the clear started on and any dispatcher enrolled while the fence is up, including after the cleanup already started. The settle (success, cursor-clear failure, and startup failure) releases every registered dispatcher and clears the fence through one path ( A queued clear is skipped if its predecessor fails. The queue now chains with Tests in
Both tests fail on 9155300. |
lhotari
left a comment
There was a problem hiding this comment.
Thanks for the update. Registering every armed dispatcher on the clear and releasing them all in settleInProgressBacklogClear() fixes the late-dispatcher case, and the handle(...) chaining makes a queued clear run even when the one ahead of it fails. Both new tests in PersistentSubscriptionTest cover those paths.
Two smaller points are left, both inline:
settleInProgressBacklogClear()drops the fence before it releases the dispatchers. A clear that starts in that gap can have its gate reset by the previous clear's release (PersistentSubscription.java:993).- When the dispatcher was replaced before the callback runs, the delayed-state cleanup is skipped. Snapshots written before the clear are then not removed (
PersistentSubscription.java:925). On master the callback always ran the cleanup on the current dispatcher.
…e drops The settle nulled the fence before releasing the armed dispatchers, so a clear starting in that gap could have its gate reset by the previous clear's release and lose a message that entered the live tracker. The releases now finish while the fence is still up, draining dispatchers that arm during the releases, and only then does the fence drop. A dispatcher replaced during the cursor clear skipped the delayed-state cleanup: the replaced dispatcher's close leaves the cursor's snapshot properties in place, so the pre-clear bucket snapshots were not removed. The completion now runs the cleanup on the dispatcher enrolled at completion time, reading the dispatcher once so the cleanup and the mark-delete bookkeeping use the same instance. Assisted-by: Claude Code
lhotari
left a comment
There was a problem hiding this comment.
LGTM. Thanks for the quick turnaround. The drain loop in settleInProgressBacklogClear() now releases every registered dispatcher while the fence is still up (PersistentSubscription.java:984-1010), so a clear that starts afterwards can't have its gate reset. Running the cleanup on the dispatcher enrolled at completion time restores master's snapshot cleanup when the dispatcher was replaced, and testDispatcherReplacedBeforeCompletionStillRunsDelayedStateCleanup covers it. Thanks also for opening #27709 for the dropped-callback case.
|
@nodece Please fix the PR description. It seems that it got updated to |
Motivation
PersistentSubscription#clearBacklog()captures the last position N when the clear starts. Before its asynchronous mark-delete callback reaches the dispatcher, a newly published delayed message at N+1 can be read and queued for tracker creation. N+1 is not part of the cleared backlog, but it can be dropped from the pending map, so a successful tracker retry never schedules it and delivery can stall until a rewind or reconnect.Two further hazards around the in-flight clear, found in review: the cursor samples the backlog tail per invocation, so an in-flight clear can miss entries published after it started and a repeated clear must not report the caller's backlog as cleared; and a dispatcher that attaches while the clear is settling arms the buffering gate but the completion no longer observes it, which could leave it buffering forever.
Modifications
asyncClearBacklogsamples the cursor tail, so entries published before the callback starts cleanup cannot be added to the live tracker and then removed by the cleanup.clearDelayedMessagesAfterBacklogClear()preserves pending positions above the captured mark-delete position. Positions arriving while the clear is running stay pending, and the initial tracker install is skipped while the clear is in flight.clearBacklog()is fenced per subscription: a repeated clear queues a fresh clear behind the in-flight one, because the cursor samples the backlog tail per invocation. A queued clear runs whether its predecessor succeeds or fails — only the queued caller's own invocation clears its backlog — and each caller's future reports its own clear's outcome.Verifying this change
Added tests:
testBacklogClearPreservesPendingPositionsAboveMarkDeletetestBacklogClearInstallsPendingPositionsAfterCreationSuccesstestBacklogClearKeepsPositionArrivingDuringClearPendingtestRepeatedClearBacklogQueuesFreshClearBehindInFlightOnetestQueuedClearRunsAfterPredecessorFailuretestBacklogClearBuffersBeforeCursorCallbacktestBacklogClearFailureReleasesBufferedPositionstestBacklogClearAlreadyDuePreservedPositionInstalledOncetestBacklogClearInstallsPreservedPositionsWhenClearFailstestTrackerInstallDropsPendingPositionsAtOrBelowMarkDeletePositiontestDispatcherAttachedAfterCleanupStartsIsReleasedWhenClearSettlestestDispatcherReplacedBeforeCompletionStillRunsDelayedStateCleanupDoes this pull request potentially affect one of the following parts:
Check the boxes that apply
Documentation
docYour PR title contains the doc impact labeldoc-requiredYour PR changes the docsdoc-not-neededDocs are not requireddoc-completeDocs have been already added