Repository navigation
[fix][txn] Restore metadata transaction visibility and durable ACK state on recovery - #27380
codelipenghui wants to merge 9 commits into
Conversation
…ate on recovery Restore the OPEN visibility boundary and persisted ACK positions before admitting recovered segment traffic. Apply committed ACK recovery sequentially and retain partial-batch records until the durable cursor covers their whole entry. Persist optional batch size and ACK mask fields while retaining legacy non-batched and single-message records; reject ambiguous legacy partial batches without inferring ACKs. Tests-only execution reproduces six unsafe recovery outcomes on unpatched master. All 79 scoped cases and quickCheck pass, with retries disabled. Assisted-by: OpenAI Codex
…very Committed ACK records stay in the metadata store until the durable whole-entry prefix covers them. A seek back to an earlier position clears the cursor state and leaves those records uncovered, so after an owner restart recovery reapplied the pre-seek ACKs and silently skipped messages the seek had made available again. Add a beforeCursorReset hook to PendingAckHandle and PendingAckStore (default no-op). The subscription runs it before persisting a reset and fails the reset if it fails. MetadataPendingAckStore waits for recovery, then drops the ACK records of terminal transactions with versioned deletes; OPEN transactions keep theirs, so their ACKs still apply when they commit after the reset. Closing the store releases a reset waiting on a recovery that never started. Seek-to-earliest followed by a restart now redelivers committed partial-batch and out-of-order ACKed messages, and keeps an OPEN transaction's ACK. Assisted-by: Claude Code (Claude Opus 5.5)
…sisted beforeCursorReset deletes the retained ACK records of terminal transactions before the reset is persisted. If the reset then failed, or the deletion itself failed part way, the cursor kept the committed ACKs only in memory while their recovery records were gone, so a crash before a durable checkpoint redelivered those messages. Capture the contents of every record before deleting any, and add afterCursorReset(persisted) to PendingAckHandle and PendingAckStore (default no-op). When the reset is not persisted, MetadataPendingAckStore recreates the dropped records at their original paths with the indexes appendOp gives them, and tracks their transactions again so reconcile cleans up those the cursor covers meanwhile. The subscription restores the records before it unfences and fails the reset, so a retried reset cannot race the restore. Add fault-injected regressions: a reset whose cursor persistence fails, followed by a restart with volatile cursor state lost, and store-level partial-deletion and unpersisted-reset cases followed by recovery. Assisted-by: Claude Code (Claude Opus 5.5)
Deleting the retained ACK records of terminal transactions before a cursor reset left a window in which a terminal transaction had no op records. A TC GC sweep in that window deleted its COMMITTED header, so even records restored after a failed reset were read as ABORTED: their ACKs were never recovered and the records were deleted. Mark the records resetPending in place instead, with versioned rewrites that keep their indexes, so the TC keeps the header while the outcome of the reset is unknown. A persisted reset deletes the marked records; a reset that is not persisted clears the mark. A delete or unmark that fails is retried on reconcile, which the TC keeps triggering while the records exist. Recovery never reapplies a marked record and deletes it. Recovery now also checks the segment and subscription of each scanned ACK record: a store with a native index does not apply the scan's filter, and its lookup also matches subscriptions whose name extends this one's. Add a regression with a GC sweep between marking and a failed reset, followed by recovery; a TC test showing the real sweep keeps the header of a transaction whose ACK record is marked; and tests for interrupted resets and retried unmarks. Assisted-by: Claude Code (Claude Opus 5.5)
…a-txn-recovery-20261105
A reset that is not persisted leaves its marked ACK records to be unmarked asynchronously. The next reset cleared that bookkeeping and read the records while such an unmark could still be in flight. If the unmark landed between the read and the marking, the marking's version conflict was silently accepted: the reset reported success with the record left unmarked, and recovery after a restart reapplied the ACK, undoing the seek. Run the deletes and unmarks of marked records one after another, and make a reset read the records only once those issued before it have landed; none is issued while it is in progress. Keep the records left to unmark until a later reset's mark takes them over, and treat them as discarded once a reset is persisted. A version conflict while marking now fails the reset preparation instead of counting the record as marked; unmarks still tolerate conflicts, which can only come from their own earlier write. Add a latch-controlled regression holding the unmark in flight while the next reset starts, and a regression rewriting a record between the read and the marking, each followed by recovery. Assisted-by: Claude Code (Claude Opus 5.5)
…a-txn-recovery-20261105 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…transactional ACKs persistedOpenTransactionalAcksRecoverBeforeCommit failed whenever the commit landed while the dispatcher's first read after the restart was in flight. The read was issued while the recovered ACKs were still pending and completed after the commit moved the mark-delete position past those entries. A completed read filters only individually deleted entries, and the pending-ack filter no longer held the positions, so the read delivered the committed messages anyway. Check the durable cursor from a fresh load after the ACK records are removed: a sentinel published after a second restart must be the only message delivered. Co-Authored-By: Claude Opus 5.5 <[email protected]>
lhotari
left a comment
There was a problem hiding this comment.
Thanks for taking on the hard recovery and seek windows here, and for the detailed description of each one.
I found three problems I think should be fixed before merging:
- An ambiguous legacy ACK record (written by 5.0.0/5.0.1 for a batched entry) leaves pending-ack recovery retrying forever, so the subscription never becomes ready (
MetadataPendingAckStore.java:330-333). - A failed
MetadataTransactionBufferrecovery now leavesmaxReadPositionatEARLIESTwith no retry or close, so the segment stops dispatching everything (MetadataTransactionBuffer.java:325-333). - Committed transactions whose ACKs are not yet covered by the durable cursor stay in
openTxnswith no bound, and each reconcile re-reads and re-commits all of them (MetadataPendingAckStore.java:561).
There are also two recovery-ordering cases where a message can be skipped or redelivered (a commit applied during a reset, and hydration order of conflicting OPEN ACKs), and some smaller points inline.
There is one related issue outside this diff: ManagedCursorImpl.internalResetCursor writes the reset's cursor-ledger entry while individualDeletedMessages and batchDeletedIndexes still hold the pre-reset ACKs. They are cleared only after the write (ManagedCursorImpl.java:1826-1873; serializePositionInfo at ManagedCursorImpl.java:4169-4205). A broker crash right after a successful seek can therefore restore ACKs above the new mark-delete, for non-transactional ACKs too. The new restart tests close the broker gracefully, which writes the cleared state, so they don't hit it. This sits in the same cursor batch-ACK code that #26765 and #26998 changed, and there is already a list of follow-up gaps there (#26998 comment), so it could be handled together with those.
That list matters here as well, because this PR's recovery replays committed ACKs through those cursor paths. A recovered cumulative ACK goes through commitRecoveredTxn and acknowledgeMessageAsync(..., AckType.Cumulative, ...) (PendingAckHandleImpl.java:482-484) into ackBatchPosition (ManagedCursorImpl.java:2829-2855). It relies on the AND merge from #26998 to avoid restoring individually acked indexes. handleCumulativeAckRecover skips only positions at or below the mark-delete (PendingAckHandleImpl.java:903-910), and ackBatchPosition has no internalIsMessageDeleted check. So replaying a stale committed cumulative ACK for an entry that is already in individualDeletedMessages can put back the orphan bitmap described in finding 1 of that comment. The shared merge helper proposed there would cover this replay too, so I don't think this PR needs its own fix.
| imagesByTxn.forEach((txnIdKey, txnImages) -> reads.add(txnStore.getHeader(txnIdKey) | ||
| .thenAccept(header -> { | ||
| TxnState state = header.map(v -> v.value().getState()).orElse(TxnState.ABORTED); | ||
| if (state.isTerminal()) { |
There was a problem hiding this comment.
[BUG] A transaction that is OPEN when the reset reads its header but commits before the reset lands can still undo the seek after a restart
Only records of terminal transactions are marked here. Reconcile keeps running while a reset is in progress: nothing gates applyTerminal on resetInProgress (MetadataPendingAckStore.java:457-475), so a commit can be applied to the cursor between this header read and asyncResetCursor.
Scenario: T is OPEN when beforeCursorReset reads its header, so its record for M (out of order, or a partial batch) is left unmarked. T commits, and applyTerminal acks M on the cursor before the reset. The reset then clears that ACK (M is redelivered, as expected), but the unmarked record survives above the durable mark-delete. After any restart, recovery sees a COMMITTED header and reapplies the ACK, so M is skipped. The PR description says the remaining windows "can only redeliver a message, never skip one". This one skips. The window grows with the number of retained transactions (previous comment).
Holding terminal applies while resetInProgress is set (and running them after afterCursorReset), or re-checking headers after the cursor write, would close it.
There was a problem hiding this comment.
Fixed in 5f8c3dd. Terminal outcomes that arrive while a reset is in progress are held back, and afterCursorReset applies them. A transaction that was OPEN when the reset read the records can no longer apply its ACK before the reset lands. commitDuringACursorResetIsAppliedAfterTheReset covers it. I've also removed this case from the PR description's list of remaining windows.
There was a problem hiding this comment.
Thanks, this closes the OPEN-at-read case. The hold also catches transactions the reset already read as terminal, though, and those now apply after the seek. Details in the new comment at MetadataPendingAckStore.java:534-539.
- Restore nothing for a legacy ACK record of a batched entry that lacks its batch acknowledgement mask, and keep the record until the durable cursor covers it. Failing recovery with a retryable error failed it again on every retry, so the subscription never became ready. - Close the topic when the transaction buffer's recovery fails, so that it reloads and recovers again. Nothing retained became dispatchable before. The close runs on the broker executor once the topic has published the buffer, which the topic creates in its constructor. - Track applied committed transactions whose ACK records are kept separately, indexed by the highest kept position. A reconcile compares them only with the persisted mark-delete position instead of reading their headers, committing them again and scanning their records on every event. - Hold back terminal outcomes while a cursor reset is in progress and apply them after it. A transaction that was OPEN when the reset read the records could otherwise apply its ACK before the reset discarded it, leaving an unmarked record that recovery reapplied, skipping the message. - Discard the records of an acknowledgement the handle rejects as a conflict. Recovery restores OPEN transactions in no particular order, so such a record could take the reservation of the accepted acknowledgement. - Ask the metadata store to confirm a record rewrite whose reply was lost. - Check deliveries of the OPEN-ACK seek regression on a fresh consumer. Co-Authored-By: Claude Opus 5.5 <[email protected]>
lhotari
left a comment
There was a problem hiding this comment.
Thanks for the quick and thorough round. I checked each fix against the code at this head, and all of them do what the replies describe: the topic now closes after a failed buffer recovery, rewrites use VerifyPublication, ambiguous legacy batched ACKs are skipped instead of failing recovery, applied commits are indexed by their highest kept position, rejected ACKs discard their records, and the seek regression asserts on a fresh consumer. Keeping the live-owner batch mask issue for #27752 is fine with me.
One new case comes from holding outcomes while a reset is in progress. It's inline at MetadataPendingAckStore.java:534-539: a commit that was already decided when the reset read its header is now applied after the reset lands, so a seek issued after the commit returned can still skip that message on the live owner.
| // The reset left the records of the transactions that were OPEN when it read them unmarked. An outcome | ||
| // applied to the cursor before the reset lands would be discarded by it while its record survives, | ||
| // and recovery would reapply it: the message would be skipped. afterCursorReset reconciles again. | ||
| return; |
There was a problem hiding this comment.
[BUG] An outcome held during a reset is applied after the reset even when the reset already found the transaction terminal and discarded its records
The hold covers every transaction, including ones that beforeCursorReset reads as terminal. For those it marks the records (MetadataPendingAckStore.java:739-749), and a persisted reset deletes them. Then afterCursorReset runs applyDecidedOutcomes (MetadataPendingAckStore.java:775-779), which still finds the transaction in openTxns and calls commitTxn. The reset does not clear the handle's pending ACK for it (PersistentSubscription.java:1194-1208), so the commit acknowledges the message on the cursor after the seek.
Scenario: the client commits T, and endTxn returns once the header is COMMITTED. The subscription event is still in flight when the client seeks back. resetInProgress holds the event, the reset reads T as COMMITTED and marks its record, the cursor write lands, and then T's ACK is applied. The message is not redelivered after a seek that was issued after the commit completed. Before this change, that event was applied right away, so its ACK usually landed before the cursor write and the reset discarded it.
The hold is only needed for transactions that were OPEN when the reset read the headers. One fix: record that set in beforeCursorReset, and hold only its members (or anything that arrives before the read finishes). An outcome the reset already covered by marking could then be applied before the cursor write, or its pending ACK dropped from the handle once the reset is persisted. A variant of commitDuringACursorResetIsAppliedAfterTheReset, where the header is COMMITTED before the reset reads it, would cover this.
| imagesByTxn.forEach((txnIdKey, txnImages) -> reads.add(txnStore.getHeader(txnIdKey) | ||
| .thenAccept(header -> { | ||
| TxnState state = header.map(v -> v.value().getState()).orElse(TxnState.ABORTED); | ||
| if (state.isTerminal()) { |
There was a problem hiding this comment.
Thanks, this closes the OPEN-at-read case. The hold also catches transactions the reset already read as terminal, though, and those now apply after the seek. Details in the new comment at MetadataPendingAckStore.java:534-539.
Motivation
After a segment owner restarts, metadata-backed transactions can expose OPEN data before visibility recovery finishes. Pending ACK recovery also needs to restore persisted positions and batch masks before the handle is ready. A committed partial-batch ACK can otherwise be forgotten when its operation record is deleted before the durable whole-entry cursor covers it.
A retained committed ACK record must not outlive a cursor reset either: a seek back to an earlier position clears the cursor state and leaves the record uncovered, so a restart would reapply the ACK and silently skip a message the seek made available again. Conversely, a reset that fails must not lose those records, because the cursor may still hold the committed ACKs only in memory; and the transaction's outcome must stay readable while the reset's outcome is unknown, since the TC deletes a finalized header once no op record of its transaction remains.
Modifications
beforeCursorResetandafterCursorReset(persisted)hooks toPendingAckHandleandPendingAckStore(default no-op). Before persisting a reset,MetadataPendingAckStorewaits for recovery, then marks the ACK records of terminal transactions with an optionalresetPendingfield, rewriting each in place at its collected version with the indexesappendOpgives it. OPEN transactions keep theirs unmarked, so their ACKs still apply when they commit after the reset. Recovery never reapplies a marked record.The optional JSON fields extend the internal persisted ACK record; null fields are omitted when written and unknown fields are ignored when read. Wire commands and public client APIs are unchanged. The new broker-internal interface methods have no-op defaults, so the legacy and pluggable pending ACK stores behave as before.
Verifying this change
Tests-only execution on unpatched Apache master
a72adf733ead20ba4b19a76222b698f315073ecfproduced 6 expected behavior failures: OPEN visibility after restart, the held recovery boundary, restored ACK positions, partial-batch recovery, and a committed ACK lost with volatile cursor state. Production files were unchanged in that baseline.The seek-to-earliest → restart regressions fail without the reset hook (on this PR's first commit
34e46a8): a committed partial-batch ACK and a committed out-of-order ACK are both reapplied, and the ACKed message is missing after the restart.The failed-seek regression fails when the hook deletes records without restoring them (on
9d5fd8e): a reset whose cursor persistence fails (fenced cursor ledger and a failed metadata-store fallback) leaves the committed partial-batch ACK without its record, and a restart with volatile cursor state lost redelivers the message.The GC-window regression fails when the hook deletes and later recreates records (on
27557d2): with a GC sweep between the deletion and a failed reset, the TC deletes the COMMITTED header, the recreated record is read as ABORTED, and recovery never reapplies the ACK. With marking, the header survives and recovery reapplies it. The test's sweep step applies the rule ofTransactionCoordinatorV5.gcOneTxn(delete a finalized header once no op record of its transaction remains); a TC test checks that the realsweepGc()keeps the header of a transaction whose ACK record is marked.The unmark-race regressions fail without this fix (on the merge
b9a691f): with a failed reset's unmark held in flight, the next reset reads the records before it lands; and with a record rewritten between that read and the marking, the preparation reports success with the record unmarked, so once the reset is persisted a restart reapplies the ACK and undoes the seek. With the fix, the next reset waits for the unmark, and the conflict fails the preparation.Store-level regressions also cover marking that fails part way and an unpersisted reset, each followed by recovery; recovery of records left marked by an interrupted reset; and an unmark retried on reconcile.
With the fix, on this branch merged with
apache/master(b6bfce0), 168 cases passed, with no failures/errors/skips, retries and fail-fast disabled, across:MetadataTransactionBufferTestMetadataPendingAckStoreTestV5TransactionCrashWindowRecoveryTestPendingAckHandleImplThreadingTestMLPendingAckStoreTestSubscriptionSeekTestPersistentSubscriptionTestV5SeekSubscriptionTestTxnMetadataStoreTestTxnMetadataStoreShardedOxiaTestTransactionCoordinatorV5TestquickCheckandgit diff --checkpassed. The restart regressions use an isolated real broker lifecycle and retained native cursor/ledger state.Remaining windows, each of which can only redeliver a message, never skip one: a broker crash between marking the records and resolving the reset (recovery skips the marked records, and the client sees no successful seek); an unmark that keeps failing until the broker restarts; and a transaction that commits while a reset is in flight, which can race the reset as individual ACKs already do on the live path.
TxnMetadataStoreShardedOxiaTeststarts an Oxia container and needs Docker.Does this pull request potentially affect one of the following parts:
Schema: optional internal ACK JSON batch metadata and a
resetPendingmarker, with legacy compatibility checks. Threading: recovery admission and sequential work on the existing pinned executor; the reset hooks queue behind the handle's initialization on that executor, a failed reset clears its marks before the subscription is unfenced, and the deletes and unmarks of marked records are serialized with the next reset's preparation; no new thread pool.