GeezerVison is showing github.com — [fix][broker] Revalidate ownership before loading fenced topics by codelipenghui · Pull Request #27285 · apache/pulsar
Conversation
Motivation
A broker can retain cached namespace ownership while metadata notifications are delayed. If another broker takes over and fences its BookKeeper ledger, the old topic closes, but a retry can reload it using the stale cached ownership and recover the new owner's ledger.
Modifications
- Mark a fenced loaded topic before removing its cache entry, then require authoritative namespace-lock validation before readmission. Healthy cached topics continue using the existing ownership checks.
- Bind every pending persistent-topic load to its original ownership generation, including queued loads and the check before opening the managed ledger. Successful validation requires a fresh retry rather than authorizing an older pending load.
- Evict the exact failed topic future when a queued load is rejected by its captured ownership checker, while continuing the queue. A split without unload can then recover on the same broker through a fresh load.
- Forward
DualMetadataStore.sync() to the current read backend, including the default ZooKeeper wrapper. Validation waits for the underlying synchronization barrier and propagates its failures.
- Add asynchronous
ResourceLock.validate() and order validation, value updates, revalidation, and release through the existing lock sequencer. Share an unfinished validation across caller timeouts to bound retry work, and clear readmission markers with their ownership generation.
- Add real ZooKeeper/BookKeeper fencing coverage and controls for lease restoration, foreign ownership, stale generations, store failures, sync ordering, and retry coalescing.
- Align ExtensibleLoadManagerCloseTest shutdown timeout with its existing five-second close target. Preserve the less-than-five-second duration assertions; the old 100 ms deadline could race normal executor termination.
ResourceLock.validate() has a default implementation that returns a failed future, preserving existing implementations without trusting cached ownership. Custom implementations must implement authoritative validation to permit fenced-topic readmission. Validation may restore a missing lease using the existing lock rules. This orders future lock operations; it does not revoke metadata requests already in flight or provide global writer fencing.
Verifying this change
- Make sure that the change passes the CI checks.
Coverage includes independent real ZooKeeper sessions and real BookKeeper fencing, captured ownership generations, queue recovery after a bundle split, and the synchronization barrier beneath the production DualMetadataStore wrapper.
Prior review head 11abb2918f4 was validated against its parent 7bcba5f4113, with retries disabled:
- 70 metadata cases passed:
ResourceLockValidationTest (6), DualMetadataStoreSyncTest (5 migration phases), existing DualMetadataStoreTest (14), and LockManagerTest (45).
- 38 broker cases passed:
OwnershipCacheTest (28), targeted BrokerServiceTest (8, including the new real split-without-unload queue regression), NamespaceReadmissionAfterFencingTest (1, real ZooKeeper/BookKeeper), and TopicTransactionBufferTest.testCheckDeduplicationFailedWhenCreatePersistentTopic (1).
- All 108 cases had zero failures/errors/skips. The real BookKeeper regression reached and passed its fencing/readmission assertions.
quickCheck and git diff --check passed.
- Negative control on the prior head: all seven selected cases failed for their expected reasons: the queued load retained its failed cache entry, the underlying ZooKeeper validation sync was bypassed, and all five phase rows returned success before the backend barrier completed. Metadata production sources were unchanged; the old broker received only the read-only queue-count testing accessor so the identical test could observe the queue. It retained the old ownership/load/cache behavior.
Tests used Corretto 21.0.11, -PtestRetryCount=0, one test fork, and scoped --tests filters. The wrapper barrier test gates real ZooKeeper synchronization beneath a real Dual wrapper; the phase test initializes migration state from a persisted flag and supplies its controlled target through the provider SPI. Neither test substitutes the wrapper sync itself.
CI follow-up: the original Broker Group 1 failure at 11abb2918f4 was ExtensibleLoadManagerCloseTest.cleanupBrokers timing out on the test's 100 ms shutdown budget. Its log showed normal executor termination one millisecond after the deadline. Coordination/lock release precedes installation of that final timeout. The unchanged head passed all 22 class cases locally; the current budget-only head 03d0e8f733a also passed all 22 cases and quickCheck, with retries disabled and zero failures/errors/skips. These local runs used Corretto 21; the original CI used Corretto 25. The old-head failed-job rerun is tracked separately and is not evidence for the new budget change.
Remote CI is still required.
No new long-duration soak or performance comparison is claimed for this revision. Earlier shared runs describe previous implementations.
Does this pull request potentially affect one of the following parts:
- 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
The metadata coordination API gains the default ResourceLock.validate() method described above. Lock release now waits for preceding operations in the existing asynchronous sequencer; no new executor is introduced.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Require an authoritative, sequenced namespace-lock check before reloading a
topic whose managed ledger was fenced. Bind pending loads to their original
ownership generation and retain one validation through caller timeouts.
Add real BookKeeper and ZooKeeper fencing coverage and controls for lease
restoration, foreign owners, cached serving, generation races and retry bounds.
Assisted-by: Codex
Delegate the new ownership checker to the existing mock ownership path so topic loading and ownership failure tests keep their original behavior.
Assisted-by: Codex
Evict the exact topic future when a queued persistent load fails its captured ownership check, retaining queue advancement. Forward DualMetadataStore sync to the current read backend so authoritative lock validation reaches the underlying synchronization barrier.
Add real split-without-unload queue recovery, underlying ZooKeeper validation barrier, and five-phase sync routing regressions.
Assisted-by: Codex
Use the existing five-second close target for the broker shutdown deadline. The previous 100ms timeout could expire immediately before normal executor termination, leaving cleanupBrokers failed. Keep the less-than-five-second assertions intact.
Assisted-by: Codex
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks for tackling the stale-ownership readmission hole; pinning it down with a real ZooKeeper/BookKeeper fencing test is a good way to do it. The core idea (mark the fenced topic, require an authoritative ResourceLock.validate() before it can load again) looks sound, and reverting the requireFreshOwnershipBeforeTopicReadmission call in PersistentTopic.addFailed makes NamespaceReadmissionAfterFencingTest fail on its readmission assertion, so that test does pin the fix.
I have two requests about how the per-load ownership checker picks its bundle, which can regress ordinary (unfenced) loads, and one coverage gap:
- The checker resolves the bundle with
NamespaceBundle.includes() rather than the configured bundle-assignment strategy (inline comment on OwnershipCache.java).
- It can capture an inactive split parent that is still cached next to its children (inline comment).
- Only the publish-failure path installs the readmission gate; two subscription paths in
PersistentTopic that also close on ManagedLedgerFencedException do not (inline comment).
There is also a smaller lock-ordering risk, described in the last inline comment on BrokerService.java. I did not reproduce it.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Resolve bundles through the configured assignment strategy while preserving captured ownership generations, cover subscription fencing paths, and start ownership validation after publishing the topic future. Preserve upstream partition-property refresh ordering and adapt queued-load cleanup coverage.
Assisted-by: Codex
Resolve the conflict in BrokerServiceTopicDeletionTest with apache#27426. Keep
this branch's NamespaceService#newTopicOwnershipChecker stub for the
queued topic, and adopt master's trigger load. The trigger now passes its
ownership check through TopicLoadingContext#setOwnershipChecker, because
the loading path here no longer calls BrokerService#checkTopicNsOwnership.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Approved with a non-blocking follow-up for the pre-existing initialization case described inline.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
LGTM. Thanks for the thorough rework: resolving the bundle through the configured strategy (NamespaceService.getBundleIfPresent with an async getBundleAsync fallback), starting the load after the topics-map insertion, and gating the subscribe and cursor-open fence paths address all four of my earlier points, and each has a test that names the scenario.
Three optional hardening points, none blocking:
BrokerService.java:3032-3040 runs requireFreshOwnershipBeforeReadmission without a catch, and it now calls the configured TopicBundleAssignmentStrategy synchronously (OwnershipCache.java:307-309). If a custom strategy throws there, addFailed skips close(), the callback completion and the pending-write decrement, and openCursorFailed skips subscriptionFuture.completeExceptionally and close(). The takeover report right below the marker call in addFailed is already wrapped in a try/catch for the same reason; the same treatment (log and continue) would keep marker installation from breaking fenced cleanup.
- A cold marker (
OwnershipCache.java:294-321) is only cleared by the removal listener or a later check. If its last captured ownership future fails, Caffeine removes it without invoking the listener, so the marker can linger until the topic is next checked. I believe the consequence is bounded (at most one extra rejected attempt after reacquisition), so this is a note rather than a request.
- A subscribe check that resolved the old split parent before the fence can remove a cold marker via the generation-mismatch branch at
OwnershipCache.java:345. The resolved-marker path already behaved this way, so this is not a regression; it only matters if the child's cached ownership is stale at that moment.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
…gate fails
Installing the readmission gate resolves the topic's bundle through the
configured TopicBundleAssignmentStrategy. If that throws, addFailed,
openCursorFailed and the subscribe failure handler skipped closing the
fenced topic and completing their callbacks. Log the failure and
continue; without the gate, the next load uses the cached ownership
checks, as before this change.
Assisted-by: Claude Code (Opus 5.5)
…uencer
Merging master brought apache#27530, which queues the delete in release() behind
the update or revalidation in flight. This branch also queued the whole
release() through the sequencer, so the merged release queued its delete
behind itself and never completed while another lock operation was in
flight.
Keep master's release(), which marks the handle as releasing at once and
queues only the delete. So that a validation in flight still expires the
handle when it finds another session's lock, report that owner before the
releasing-state check in revalidate(); the queued delete then skips the
other owner's lock.
Assisted-by: Claude Code (Opus 5.5)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
LGTM. Thanks for the two follow-up commits. Wrapping the readmission gate in BrokerService.requireFreshOwnershipBeforeTopicReadmission (BrokerService.java:3058-3074) keeps fenced cleanup running when the bundle assignment strategy throws, which covers the first optional point from my last review, and the two new PersistentTopicTest cases check that the publish callback and the subscription future still complete and the topic leaves the cache. Going back to master's release() and moving the foreign-owner LockBusyException check ahead of the state check in revalidate() (ResourceLockImpl.java:332-338) removes the self-queued release, and ResourceLockValidationTest.foreignValidationExpiresBeforeQueuedUpdateAndRelease still shows that a validation whose read is in flight expires the handle before the queued delete runs.
I left one optional inline note about the store.sync() window in validateOnce(). It is not blocking.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
…starts
A release() that started while validate() waited for store.sync() made
revalidate() fail its state check before reading the lock, so the handle
was not expired and the queued delete still used the old version. A
validation still queued behind another operation when release() started
failed the same way. If another session had re-created the lock with that
version, the delete removed its lease.
When the handle is already releasing, validateOnce() now still syncs and
reads the lock, only to fail with LockBusyException for another session's
lease. That expires the handle, so the queued delete skips the lease. A
lock that is being released is never re-acquired.
Assisted-by: Claude Code (Opus 5.5)
Uh oh!
There was an error while loading. Please reload this page.
Reviewers
lhotari
lhotari approved these changes
dao-jun
dao-jun approved these changes
Uh oh!
There was an error while loading. Please reload this page.
Development
Successfully merging this pull request may close these issues.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
|