Repository navigation
[fix][ml] Fix cached read handle leaks when closing read-only managed ledgers - #26816
Conversation
Release the read-only handle cache on close, including fenced closes and handles whose opens are pending, without changing writable managed-ledger shutdown. Main Issue: apache#26815 Assisted-by: OpenAI Codex
Guard cache insertion against concurrent close and cover reads after normal or fenced close, repeated close, and independent cleanup failures. Assisted-by: OpenAI Codex
lhotari
left a comment
There was a problem hiding this comment.
Thanks for tracking down this leak and for the thorough tests of the close path.
The close logic in ReadOnlyManagedLedgerImpl looks right to me. The flag is set before the cache is drained. The recheck after insertion covers the late-open race. Invalidation is async, so nothing blocks. A second close finds an empty cache and does nothing.
My main concern is the one @Denovo1998 raised: nothing in production calls the new asyncClose. ManagedLedgerFactoryImpl.asyncOpenReadOnlyManagedLedger returns ReadOnlyManagedLedgerImplWrapper. Neither the wrapper nor the ReadOnlyManagedLedger interface has a close method. ReadOnlyCursorImpl.asyncClose only closes the cursor. Factory shutdown does not help either, because read-only ledgers are never added to its ledgers map. SnapshotSegmentAbortedTxnProcessorImpl.readSegmentEntries is the only production caller, and it drops the ledger without closing it. The new tests build ReadOnlyManagedLedgerImpl directly, so they cannot show this. As it stands, the leak in the description still happens. Please add a close path to the interface and wrapper, call it from that caller, and add a test through the factory API. If you want to keep this PR as groundwork only, please say so in the description.
I also agree with the second open thread. No test reaches the recheck in getLedgerHandle. Deleting it leaves every test green. A deterministic option is to call readOnly.close() from inside the stubbed newOpenLedgerOp() execution, before super.getLedgerHandle returns. Then assert the returned future fails with ManagedLedgerAlreadyClosedException and the handle gets closed. Separately, testCloseReleasesHandleWhoseOpenIsPending assumes initialize() opens exactly one handle (openedHandles.size() == 2, get(1)). Recording the size before the call would be less brittle, especially next to #26817, which also touches ReadOnlyManagedLedgerImpl.
Expose an asynchronous close on the factory-facing read-only ledger API, delegate it through the wrapper, and close snapshot recovery ledgers after use. Add deterministic coverage for the close/open race, factory delegation, and the broker caller lifecycle. Assisted-by: OpenAI Codex
|
Thanks @Denovo1998 and @lhotari for the detailed reviews. I've pushed
The focused managed-ledger and broker tests pass locally, as does Could you please take another look when convenient? |
codelipenghui
left a comment
There was a problem hiding this comment.
Reviewed head 401ff9c. No actionable findings identified within the reviewed scope.
Focused validation passed: 18 managed-ledger tests and 1 snapshot-recovery lifecycle test. The scoped cleanup and factory/caller close wiring look sound.
Preserve the expectedReadCount read overload alongside read-only ledger handle cleanup, and add a regression for count propagation. Assisted-by: Codex
Register handle promises before IO, invalidate failed handles by identity, and release cached and temporary resources across close, initialization, and executor failures. Track read-only opens through shutdown, give factory cursors ownership, and dispose isolated entry caches and unreturned entries. Assisted-by: Codex
Release late read-only ledgers and entries after a snapshot recovery wait times out or is interrupted. Preserve the recovery result when cleanup fails, and cover delayed resources and close failures. Assisted-by: Codex
Detach the source watcher immediately after the close gate is claimed, independently of pending BookKeeper or cursor close callbacks. Run the cleanup without holding the managed-ledger monitor and cover a delayed current-handle close. Assisted-by: Codex
codelipenghui
left a comment
There was a problem hiding this comment.
Reviewed head f31fa58. No actionable findings identified within the reviewed scope.
The merge preserves expectedReadCount forwarding and the previously reviewed cleanup behavior. All 23 focused tests passed. The new regression test also failed when forwarding was deliberately removed and passed after restoration.
lhotari
left a comment
There was a problem hiding this comment.
LGTM. Thanks for working through the earlier points; each one is addressed.
ReadOnlyManagedLedger.asyncClose() now exists with a no-op default, ReadOnlyManagedLedgerImplWrapper.asyncClose() delegates to the implementation, and SnapshotSegmentAbortedTxnProcessorImpl.readSegmentEntries closes the ledger in a finally, so the production path now releases the cached handles. testFactoryWrapperCloseReleasesCachedHandle goes through the factory API, and SnapshotSegmentAbortedTxnProcessorCloseTest verifies the close call. The race test is deterministic, and the handle-count baseline is now taken after initialize().
Two small, non-blocking notes.
First, testCloseRejectsHandleInsertedAfterCloseStarts pins the failed-future return of the recheck in getLedgerHandle, but not its invalidateReadHandle call. The test pauses inside newOpenLedgerOp(), which runs under the map's write lock, so close's scan waits for the insertion and releases the handle itself. Deleting only the invalidateReadHandle in the recheck keeps all tests green. The window it covers (close finishing its scan before the insertion) needs a pause between the first flag check and the parent lookup. I would not block on it.
Second, a closed read-only ledger can stay the owner of the entry cache that RangeEntryCacheManagerImpl.getEntryCache registers by ledger name. ManagedLedgerFactoryImpl.close(ManagedLedger) returns early for a ledger that is not in its map, so the cache mapping is not removed. A later writable ledger with the same name reuses that cache, and RangeEntryCacheImpl.readFromStorage retries OffloadReadHandleClosedException through ml.reopenReadHandle, which now fails with ManagedLedgerAlreadyClosedException. This needs a read-only ledger to be the first opener, followed by an offloaded-ledger retry, so I consider it low risk. Removing the cache mapping in ReadOnlyManagedLedgerImpl.asyncClose would close it, if you want to.
For #26817: it also changes ReadOnlyManagedLedgerImpl and fixes the handle initialize() opens to read the last add confirmed, which bypasses ledgerCache and is not released by this PR's close. The two touch different methods, so I expect a clean merge, but whichever lands second should rebase and re-run ReadOnlyManagedLedgerHandleCloseTest.
codelipenghui
left a comment
There was a problem hiding this comment.
I recommend fixing cache ownership before merge. On '8d448806bc', a focused test reproduced the earlier P2: a writable ledger’s offload retry failed because it used a closed read-only ledger. Moving only the reader’s close until after the retry made the same test pass. All 25 selected checked-in tests passed; none exercises that ownership order. The master merge also made the subclass’s close-time cache scan redundant.
Keep the shared entry cache and scope pending reads and handle retries to the managed ledger that issued the read. Preserve confirmation bounds and cover both cache allocation orders. Delegate read-handle cleanup to the parent close path and release a snapshot recovery ledger when its open finishes after the wait times out. Assisted-by: Codex
Verify that a writable ledger can reopen an offloaded handle after the same-name cache creator closes. Cover requester-specific pending read invalidation and clean up resources in the related ledger and broker tests. Assisted-by: Codex
lhotari
left a comment
There was a problem hiding this comment.
LGTM. Thanks for the quick turnaround on the cache-ownership follow-up.
The retry in RangeEntryCacheImpl.java:770-796 now goes through the ledger that issued the read (reader.reopenReadHandle, reader.invalidateLedgerHandle, reader.reopenLedgerHandleIfReplicated) instead of the ledger that happened to register the shared cache, so a closed read-only owner can no longer fail a writable ledger's offload retry. All production callers in ManagedLedgerImpl pass this, and pending reads are keyed by reader identity and completed on that reader's executor. OffloadPrefixReadTest.testAsyncReadEntryRetriesOffloadAfterSharedCacheOwnerCloses covers the read-only-first order through the public read API, and RangeEntryCacheOwnershipTest covers the retry, coalescing and read-boundary combinations.
ReadOnlyManagedLedgerImpl.asyncClose now only sets the flag and delegates, so the cache is drained once. Every branch of the parent's asyncClose drains (fenced, no current ledger, and the write-handle close callback even on failure), and a handle whose open finishes after the drain is closed by the parent's readHandlesReleased handling. testCloseReleasesHandleInsertedAfterCacheDrain closes the ledger inside openLedgerHandleOnCacheMiss and verifies the late handle's closeAsync, which also settles my earlier note about the recheck: it now only rejects the lookup, and the release is pinned. The snapshot recovery path also releases a ledger whose open completes after the wait timed out.
Two small, non-blocking notes.
First, the shared RangeEntryCacheImpl still keeps the first opener as ml for things other than retries: cache-miss stats go to ml.getMbean() (RangeEntryCacheImpl.java:754), and the interceptor (RangeEntryCacheImpl.java:103) and the message-metadata setting (RangeEntryCacheImpl.java:470) come from its configuration. When the first opener was a read-only ledger, a later writable ledger's cache misses are therefore counted on the closed ledger's MBean. This is not new and not a correctness problem for the snapshot case, whose read-only ledger uses the topic's own configuration, so I would leave it unless you want to follow up.
Second, the cross-reader tests in PendingReadsManagerTest and RangeEntryCacheOwnershipTest use equal or contained ranges. I did not find a test with two readers whose pending ranges only partially overlap, so dropping the reader == other.reader check in PendingReadKey.overlaps (PendingReadsManager.java:148) would likely stay green. A small test would pin it.
The PR has no CI checks reported on this head yet, so the new tests have not run in CI.
…o codex/pr26816-private-read-cache
Give independent read-only ledgers their own entry cache to retain storage retries and read limiting. Clear pending reads on close and keep the existing read signatures for writable ledgers. Assisted-by: Codex
|
Thanks @lhotari for pointing out the first-opener metrics and partial-overlap cases in In Snapshot recovery closes the reader when it finishes. The reader clears its private The regression opens the read-only ledger first and the writer second, closes the reader, and verifies that the writer can retry an expired offload handle through the public read API. Temporarily registering the read-only cache by name again reproduced |
lhotari
left a comment
There was a problem hiding this comment.
LGTM. Thanks for reworking this. Opening each read-only ledger with its own unregistered entry cache is simpler than routing the requesting ledger through the shared cache. It also removes the ownership questions from the previous round. ManagedLedgerFactoryImpl.close still removes a named cache only when the closing ledger is the registered instance, so a reader closing can no longer affect a same-name writer. OffloadPrefixReadTest.testAsyncReadEntryRetriesOffloadWithPrivateReadOnlyCache covers the reader-first, writer-second order that failed before.
The remaining CI failure (BrokerServiceTopicDeletionTest.setup, a Mockito WrongTypeOfReturnValue while stubbing getTopicPoliciesService) is in code this PR doesn't touch. A rerun should clear it.
… branch # Conflicts: # managed-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/OffloadPrefixReadTest.java
|
The only test failure in the CI - Unit - Other job on This also reproduces on |
lhotari
left a comment
There was a problem hiding this comment.
LGTM. Thanks for tracking down the CI failure. Since the approval at a00f5bb the only new commits are two merges of master (b675316 and 50e2d64). The PR's own changes are the same as the ones I approved: against the approved diff only hunk offsets and context lines moved (ManagedLedgerImpl.java, RangeEntryCacheImpl.java, and the imports in OffloadPrefixReadTest.java, where master now has the mock import).
The second merge brings in #27763. It removes the State.Closed fail-fast from asyncTerminate in ManagedLedgerImpl.java. This PR doesn't touch that code, so it doesn't interact with the read-handle cleanup in openLedgerHandleOnCacheMiss (ManagedLedgerImpl.java:3170). #27763 also fixes the ManagedLedgerTerminationTest.duplicateTerminateAfterCloseSharesExistingAttempt failure you pointed out in the CI - Unit - Other job. All 43 checks pass on 50e2d64.
A factory-opened ReadOnlyCursor closes its read-only managed ledger, but before apache#26816 the same-name writable ledger could reuse the reader's name-keyed entry cache. A retry after OffloadReadHandleClosedException then reopened the offload read handle through the closed reader and failed with ManagedLedgerAlreadyClosedException. Add a regression test that opens the factory cursor first, reads the offloaded entry, opens the writer, closes the cursor and makes the writer read the entry again. The test asserts the writer reopens the offload read handle and returns the original data. On 456c3f9 it fails with ManagedLedgerAlreadyClosedException. Signed-off-by: Drifter-yh <[email protected]>
Transaction buffer snapshot recovery closes the temporary read-only managed ledger it opens. Each independent reader owns its read state for its lifetime. A same-name writable ledger can therefore retry storage reads after that reader closes.
Main Issue: #26815
Motivation
Snapshot recovery opens a read-only managed ledger to read indexed snapshot segments. The factory wrapper previously gave the caller no way to close it, leaving its cached read handles open.
The factory keys its writable-ledger and entry-cache registries by managed-ledger name. When it removes the matching writable ledger, it removes that name's entry cache in the same operation. A read-only open creates a separate, caller-owned instance outside the writable-ledger registry. It could still create the shared entry cache first, which bound storage retries to that instance. If the reader closed after a same-name writer acquired the cache, an expired offload handle could cause the writer to retry through the closed reader.
Modifications
ReadOnlyManagedLedger.asyncClose()and delegate through the factory wrapper. Recovery starts close infinallyand closes a successful open that arrives after a timeout or interruption. Cursors created from a read-only ledger borrow it from the caller who owns it.RangeEntryCacheImplwhen it opens. It tracks in-flight reads outside the name registry and leaves entry payloads uncached. It uses the reader's handle-retry operations, the existing factory read limiter, and the reader's cache-miss metrics. Point reads follow the independent read-only position rules ([fix][ml] Read published positions through stale read-only caches #27223). A factory cache size of zero selectsEntryCacheDisabled.entryCache's pending-read index, and the parent drainsledgerCache, which holds this instance's storage handles. Previously issued reads can complete through their callbacks, and the parent releases handles whose opens finish after the drain, even after the close future completes ([fix][ml] Retry a failed read on the bookies a cached read handle's ledger was re-replicated to #27147).Snapshot recovery performs point reads whose storage results are uncached by default. The private path gives up shared entry hits, cross-instance read coalescing, and read-ahead for independently opened read-only ledgers.
Verifying this change
Local testing at
522f93cd50awith upstreammaster893259f491dpassed 145 managed-ledger tests and 3 broker tests with test retries disabled.ManagedLedgerAlreadyClosedException.quickCheckrun encountered existingSummaryJavadocerrors. The baseline and candidate had the same 89 managed-ledger main Checkstyle findings.Does this pull request potentially affect one of the following parts: