Skip to content

[fix][ml] Retry a failed read on the bookies a cached read handle's ledger was re-replicated to - #27147

Merged
codelipenghui merged 3 commits into
apache:masterfrom
KannarFr:fix/ml-read-handle-keep-update-metadata
Nov 3, 2026
Merged

codelipenghui merged 3 commits into
apache:masterfrom
KannarFr:fix/ml-read-handle-keep-update-metadata

Conversation

@KannarFr

@KannarFr KannarFr commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

ManagedLedgerImpl.getLedgerHandle caches the read handles of the ledgers it opens, possibly for a long time. A cached handle keeps the ensembles the ledger had when it was opened, and doesn't see the bookies auto-recovery re-replicates the ledger to.

While a bookie of the original ensemble is still up, the reads succeed: with bookkeeperClientReorderReadSequenceEnabled (enabled by default), the bookies that left the cluster are read last. But once no bookie of the original ensemble is left, e.g. when the bookies of a cluster are decommissioned one after the other, a read on the cached handle fails. The handle is then invalidated and reopened with the current metadata by the next read, but the dispatcher waits dispatcherReadFailureBackoffInitialTimeInMs (15 seconds by default) before reading again, for every subscription reading such a ledger. #22559 reports a related symptom.

Opening these handles with withKeepUpdateMetadata(true), as #25199 did on other paths, would avoid the failed read, but at the cost of one ledger metadata watch per cached handle. With the ZooKeeper driver of BookKeeper, that is one ZooKeeper watch per ledger read and still retained, as the cache has no size limit or TTL. The same concern led apache/bookkeeper#4613 to keep this behavior opt-in. So this change retries the failed read instead, which costs nothing until a read fails.

While looking at this, some paths turned out not to release the cached handles, see below.

Modifications

  • When a read from storage fails in RangeEntryCacheImpl, except with TooManyRequestsException, the new ManagedLedgerImpl.reopenLedgerHandleIfReplicated releases the handle as before and opens the ledger again with its current metadata. If the ensembles changed, the read is retried once on the new handle; otherwise it fails as before. Reads failing on the same handle share the new open through the handle cache, which the next read would have opened anyway.
  • Release the cached read handles on every exit of asyncClose: when the managed ledger is fenced, when it has no current ledger, and when closing the current ledger fails. They were only released when the current ledger closed successfully.
  • Once the close has released the handles, getLedgerHandle fails with ManagedLedgerAlreadyClosedException instead of opening and caching a handle that nothing would release. An open that was already running when the handles were released closes its handle when it completes.
  • In invalidateLedgerHandle, only remove the cached handle if it is the one that failed. When several reads failed on the same handle and another read had already opened a new one, the later calls removed the new handle from the cache without closing it. The handle is now also removed when the managed ledger has no current ledger, e.g. a terminated managed ledger whose last ledger was offloaded and deleted from BookKeeper.

The retry doesn't avoid the first failed read, nor its timeout when the bookies don't answer. It isn't added to EntryCacheDisabled, used when the entry cache is disabled, where reads still fail and reopen the handle on the next read as before.

Verifying this change

  • Make sure that the change passes the CI checks.

This change added tests and can be verified as follows:

  • ManagedLedgerReadHandleMetadataTest runs on real bookies. It caches a read handle, stops the bookies of its ledger and reads through the managed ledger:
    • testReadRetriedOnReReplicatedBookies first re-replicates the ledger with BookKeeperAdmin.recoverBookieData through another client: the read succeeds, through a handle opened again with the new ensemble.
    • testReadNotRetriedWithoutReReplication doesn't: the read fails.
  • ManagedLedgerReadHandlePulsarMetadataDriverTest runs the same tests with the managed ledger reading through PulsarMetadataClientDriver, which caches the ledger metadata, as apache/pulsar-helm-chart can enable it; both check which driver they use.
  • ManagedLedgerTest.testReadHandlesReleasedWhenCloseFails closes a fenced managed ledger, and one whose current ledger fails to close (failNow), and checks that no read handle is left in the cache.
  • ManagedLedgerTest.testReadHandleOpenedAfterCloseIsNotCached asks for a read handle after the close. The release of a handle whose open started before the close but was cached after it is not covered: that race cannot be reproduced deterministically.
  • ManagedLedgerTest.testFailedReadHandleDoesNotEvictItsReplacement reports the same failed handle twice, with a new handle opened in between.
  • OffloadPrefixReadTest.testReadTerminatedFinalLedgerDeletedFromBookkeeper now also checks a read error and the close of a managed ledger without a current ledger.

All these tests, except testReadNotRetriedWithoutReReplication, fail without the change in the main code.

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

🤖 Generated with Claude Code

…replication

ManagedLedgerImpl.getLedgerHandle caches read handles opened without
withKeepUpdateMetadata, so they keep the ensembles the ledger had when
opened. Once no bookie of that ensemble is left, a read on the cached
handle fails and the dispatcher backs off before reading again.

Open these handles with withKeepUpdateMetadata(true), and release them on
every path where the managed ledger stops using them, since each one now
holds a ledger metadata listener: on every exit of asyncClose, for an open
that completes after the close, and in invalidateLedgerHandle only when the
cached handle is the one that failed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@void-ptr974

Copy link
Copy Markdown
Contributor

Thanks for investigating this and adding the cleanup fixes. I’d prefer keeping metadata watching disabled for this backlog path.

For example, 1,000 topic partitions × 100 cached historical ledgers could mean roughly 100,000 additional watches with the native ZooKeeper driver when a slow subscription prevents cleanup. The handle cache has no explicit size limit or TTL. Watches add memory and session-recovery load. With PulsarMetadataClientDriver, the watch is shared, so the additional cost is local listeners instead.

This concern was raised in BookKeeper #4613, which subsequently retained opt-in behavior.

This path already recovers through invalidate/reopen. Could we instead evaluate one asynchronous reopen with fresh metadata and retry before dispatcher backoff, sharing the refresh across concurrent failures? That could avoid the additional ~15-second delay, though not the initial failed read or timeout.

The cleanup fixes remain useful independently. I wouldn’t replace all existing watches together: compaction and delayed-snapshot paths need safe handle/context replacement first; schema already opens and closes per read; current-ledger and recovery paths need separate lifecycle checks.

… watching metadata

Keeping the metadata of every cached read handle updated costs one ledger
metadata watch per handle, and the cache has no size limit or TTL. Drop
withKeepUpdateMetadata from getLedgerHandle, and instead, when a read from
storage fails, open the ledger again with its current metadata and retry the
read once if its ensembles changed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@KannarFr KannarFr changed the title [fix][ml] Keep cached read handles' ledger metadata updated after re-replication [fix][ml] Retry a failed read on the bookies a cached read handle's ledger was re-replicated to Oct 28, 2026
@KannarFr

Copy link
Copy Markdown
Contributor Author

Thanks, done: I dropped withKeepUpdateMetadata and retry the failed read once, sharing the reopen, if the ensembles changed. I kept the cleanup fixes.

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

Thanks, this looks good. I traced the retry: it's bounded to one (allowRetry=false), nothing blocks, and with the compare-and-remove in invalidateLedgerHandle the reopen is really shared across reads that failed on the same handle. Reopening is also the right hook here: a BK ReadHandle can't refresh its metadata without withKeepUpdateMetadata. The close-path fixes look correct, including the open that races the close.

One heads-up: #26816 adds the same kind of closing flag and cache drain to ReadOnlyManagedLedgerImpl. With this PR, the base asyncClose already releases a read-only ledger's handles through the lh == null branch, so it would be good to align the two so we don't end up with two flags.

A few small suggestions inline.

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

Reviewed commit 88864ff. No actionable findings identified within the reviewed scope. All 28 focused test cases passed across two validation runs.

The bounded retry approach looks sound. Additional deterministic coverage for close/open races and concurrent failures sharing a reopen would be useful but is non-blocking.

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

The bounded retry and read-handle cache cleanup look sound to me. I didn't find any additional blocking issues in the current diff. The existing inline suggestions are worth addressing, particularly the offloaded-handle and metadata-cache cases.

…dgers, await metadata in test

- Don't reopen an OffloadedLedgerHandle, whose data re-replication never moves, nor a ledger that is no longer in
  the managed ledger.
- Read currentLedger once, and check the cached handle with getNow.
- Wait for the reader's metadata to show the new ensemble before stopping the bookies, so that the test can't flake
  with a metadata driver that caches it.
- Fix a test comment left over from withKeepUpdateMetadata.

Assisted-by: Claude Code (Opus 5.5)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
@KannarFr

KannarFr commented Nov 1, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review, I pushed the suggestions. About aligning with #26816: I couldn't find that PR in apache/pulsar. Could you point me to the one adding the closing flag to ReadOnlyManagedLedgerImpl? I didn't change anything for it here; whichever lands second can drop its own flag and rely on the base asyncClose, which already releases a read-only ledger's handles through the lh == null branch.

@KannarFr

KannarFr commented Nov 1, 2026

Copy link
Copy Markdown
Contributor Author

@merlimat could you approve the CI workflows? They have been waiting for approval since 2026-10-28, and none of the commits on this PR has run CI yet.

@codelipenghui
codelipenghui merged commit 0065fdc into apache:master Nov 3, 2026
43 checks passed
lhotari pushed a commit that referenced this pull request Nov 4, 2026
…edger was re-replicated to (#27147)

Co-authored-by: Claude Opus 5.5 <[email protected]>
(cherry picked from commit 0065fdc)
poorbarcode pushed a commit to poorbarcode/pulsar that referenced this pull request Nov 26, 2026
…edger was re-replicated to (apache#27147)

Co-authored-by: Claude Opus 5.5 <[email protected]>
(cherry picked from commit 0065fdc)
poorbarcode pushed a commit to poorbarcode/pulsar that referenced this pull request Nov 26, 2026
…edger was re-replicated to (apache#27147)

Co-authored-by: Claude Opus 5.5 <[email protected]>
(cherry picked from commit 0065fdc)
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