Repository navigation
[improve][ml] Add updateCursorProperties as an atomic read-modify-write closure - #27703
Conversation
011785c to
5b86230
Compare
30c3c7f to
3cfd39a
Compare
3cfd39a to
b6ad115
Compare
lhotari
left a comment
There was a problem hiding this comment.
Thanks for digging into these property races. Doing the compare and the removal against a single snapshot in cleanResidualSnapshots is the right fix for the first race in the description.
A few things to sort out before this lands:
- The closure's return value goes straight into the metadata write unvalidated. A
nullresult wipes the stored properties and then fails the future (inline atManagedCursorImpl.java:493). - I can't see how the new
cursorPropertiesLockchanges behaviour for the writer pair it guards. The writer that does install a fresh version next to stale properties, the BadVersion refresh inpersistPositionMetaStore, refreshes only the stat and never the properties (inline atManagedCursorImpl.java:223). Could you share the variant of the race test that fails without the lock? - The new Javadoc promises same-snapshot semantics, but the interface default and the non-durable path don't provide them. The test decorator in
CustomizedManagedLedgerStorageForTestalso doesn't forward the new method. - Smaller suggestions on the cleanup caller and the tests.
191c606 to
db51d0a
Compare
db51d0a to
afc9f5a
Compare
afc9f5a to
1ad9112
Compare
lhotari
left a comment
There was a problem hiding this comment.
Thanks for working through all of these. Every point from the last round is handled: the result is validated with Map.copyOf before anything is written, the version refresh now adopts the stored properties, the non-durable branch runs in one critical section, the default is documented as a best-effort fallback and forwarded by the test decorator, and testCleanResidualSnapshotsKeepsReplacementPublishedDuringDelete covers the broker caller.
The rework adds one ordering problem. updateCursorLedgerStat now publishes the stat before the properties, and persistPositionMetaStore still reads that pair without the lock. That can write stale properties under a fresh version (inline at ManagedCursorImpl.java:457). There's also a small null-handling nit in the interface default.
codelipenghui
left a comment
There was a problem hiding this comment.
I’m changing my recommendation from comment to request changes. Residual cleanup now compares and removes in one cursor update, skips unchanged writes, and retries version conflicts. The ownership refresh now reloads stored properties, and the fallback is explicitly documented as non-atomic. But the new publication order lets a concurrent position write silently revert a successful property update. The fallback also still computes its diff against a live or nullable map. The separate 'ImmutableBucket' cleanup fix remains deferred to #27673. All 13 focused tests passed; none exercises the new publication race.
… closure updateCursorProperties(Function<Map<String, String>, Map<String, String>>) applies a read-modify-write function against one property snapshot: the read the function observes and the write it produces cannot interleave with a concurrent property write, which a broker-side compare-then-remove split across two operations cannot guarantee. Like the sibling property operations it surfaces BadVersionException on concurrent modification - a retry against a snapshot refreshed by a writer on this cursor re-applies the function, so the function receives a defensive copy, must be side-effect free, must not retain the passed map, and may not throw synchronously (a throw fails the returned future with the original exception and leaves the properties untouched). The result must not be null and must not contain null keys or values; a violation fails the future before anything is written, and a result equal to the snapshot skips the write. The interface default is a best-effort, non-atomic fallback that diffs against the snapshot the closure read and treats a null property map as empty. updateCursorLedgerStat rebuilds cursorProperties from the info inside the same critical section and writes the stat last, preserving the volatile ordering a lock-free reader relies on: the version refresh in persistPositionMetaStore previously installed a fresh stat next to stale properties, letting an update computed from the stale properties win the store's version check. persistPositionMetaStore samples the stat and the properties as one pair under the same lock, so a position persist can no longer commit a stale property map under a fresh version. On non-durable cursors the read, the function and the publication run as one critical section, so two concurrent updates cannot both succeed with one edit lost. BucketDelayedDeliveryTrackerFactory.cleanResidualSnapshots wraps its conditional removal with executeWithRetry on BadVersion, so a cleanup racing a concurrent property write settles instead of failing the caller after the snapshot has already been deleted. Assisted-by: Claude Code
1ad9112 to
e5716bc
Compare
lhotari
left a comment
There was a problem hiding this comment.
LGTM. Thanks for the quick follow-up: persistPositionMetaStore now samples the stat and the properties as one pair under cursorPropertiesLock, updateCursorLedgerStat writes the stat last again, and the default updateCursorProperties diffs against a copied baseline that also covers a null snapshot. The new test cases cover both changes.
…nditional update Both guarded removals now go through ManagedCursor#updateCursorProperties from apache#27703: the check that the property still references the deleted ledger and the removal are one cursor update, so a save publishing a replacement for the same bucket key while the delete is in flight cannot lose its only durable reference even when the publication completes between the check and the removal. The factory-side helper is gone entirely - cleanResidualSnapshots already carries the closure from apache#27703 - and ImmutableBucket's helper applies the same closure inside its existing executeWithRetry. Assisted-by: Claude Code
…nditional update Both guarded removals now go through ManagedCursor#updateCursorProperties from apache#27703: the check that the property still references the deleted ledger and the removal are one cursor update, so a save publishing a replacement for the same bucket key while the delete is in flight cannot lose its only durable reference even when the publication completes between the check and the removal. The factory-side helper is gone entirely - cleanResidualSnapshots already carries the closure from apache#27703 - and ImmutableBucket's helper applies the same closure inside its existing executeWithRetry. Assisted-by: Claude Code
Resolve the conflicts in ManagedCursorImpl and adapt the publication path to the cursor changes on master: - apache#27703 rebuilds the cursor properties in updateCursorLedgerStat, so drop adoptStoredCursorInfo and keep only the deletion of retained ledgers there. Sample the version and the properties as one pair in publishCursorLedger as well as in persistPositionMetaStore, and pass them to buildManagedCursorInfo. - apache#27652 assigns a publication ID in MetaStoreImpl during the write. Assign it in publishCursorLedger before taking the attempted bytes, so that reconciliation still recognizes a committed publication. - apache#27671 makes a closing cursor wait for an in-flight ledger switch, so allow that switch to publish while the cursor is Closing. - apache#26817 closes the read-only cursor ledger in asyncDeleteCursorLedger; keep that next to the deletion of retained ledgers. MetaStoreImpl now calls the put overload with options, so the fault-injection stubs in ManagedCursorTest target that overload. Assisted-by: Claude Code (Claude Opus 5.5)
…nditional update Both guarded removals now go through ManagedCursor#updateCursorProperties from apache#27703: the check that the property still references the deleted ledger and the removal are one cursor update, so a save publishing a replacement for the same bucket key while the delete is in flight cannot lose its only durable reference even when the publication completes between the check and the removal. The factory-side helper is gone entirely - cleanResidualSnapshots already carries the closure from apache#27703 - and ImmutableBucket's helper applies the same closure inside its existing executeWithRetry. Assisted-by: Claude Code
…nditional update Both guarded removals now go through ManagedCursor#updateCursorProperties from apache#27703: the check that the property still references the deleted ledger and the removal are one cursor update, so a save publishing a replacement for the same bucket key while the delete is in flight cannot lose its only durable reference even when the publication completes between the check and the removal. The factory-side helper is gone entirely - cleanResidualSnapshots already carries the closure from apache#27703 - and ImmutableBucket's helper applies the same closure inside its existing executeWithRetry. Assisted-by: Claude Code
…nditional update Both guarded removals now go through ManagedCursor#updateCursorProperties from apache#27703: the check that the property still references the deleted ledger and the removal are one cursor update, so a save publishing a replacement for the same bucket key while the delete is in flight cannot lose its only durable reference even when the publication completes between the check and the removal. The factory-side helper is gone entirely - cleanResidualSnapshots already carries the closure from apache#27703 - and ImmutableBucket's helper applies the same closure inside its existing executeWithRetry. Assisted-by: Claude Code
Motivation
Two races in cursor-property updates, found through the bucket-snapshot cleanup reviews (#26420/#27673):
removeCursorPropertyre-reads the property map and metadata version inside its own update. A concurrentputCursorPropertyfor the same key that completes between the two is erased by the unconditional removal — with bucket snapshot keys this drops the replacement ledger's only durable reference, so the ledger becomes undiscoverable after a reload.persistPositionMetaStorecallsupdateCursorLedgerStat(info, stat), which updated only the stat. An update computed from the stale properties could then carry the fresh version, win the store's version check, and overwrite a concurrent property write. (The compute path's own volatile ordering — properties written before the stat — already prevented this pairing on its own writes; the refresh was the writer that broke it.)Modifications
ManagedCursor#updateCursorProperties(Function<Map<String, String>, Map<String, String>>)applies a read-modify-write function against one property snapshot: the read the function observes and the write it produces cannot interleave with a concurrent property write. Like the sibling property operations it surfacesBadVersionExceptionon concurrent modification — a retry against a snapshot refreshed by a writer on this cursor re-applies the function. The function receives a defensive copy, must be side-effect free, must not retain the passed map, and may not throw synchronously (a throw fails the returned future with the original exception and leaves the properties untouched). The result must not benulland must not containnullkeys or values — a violation fails the future before anything is written — and a result equal to the snapshot skips the write instead of bumping the version.computeCursorPropertiesvalidates the function result withMap.copyOf, so a null map, null keys and null values are rejected before anything is written and the published map is an owned snapshot. On non-durable cursors the read, the function and the publication run as one critical section: without a store version to guard the write, two concurrent updates would otherwise both succeed with only one edit surviving.updateCursorLedgerStatrebuildscursorPropertiesfrom theManagedCursorInfoinside the same critical section as the stat andmanagedCursorInfo, and writes the stat last — the volatile ordering a lock-free reader relies on. The BadVersion ownership refresh inpersistPositionMetaStorepreviously installed a fresh stat next to stale properties; that pair wins the store's version check for an update computed from the stale properties.persistPositionMetaStorealso samples the stat and the properties as one pair under the same lock and serializes from the captured snapshot, so a position persist — the cursor-ledger rollover path included — cannot commit a stale property map under a fresh version.BucketDelayedDeliveryTrackerFactory#cleanResidualSnapshotsuses the closure for its residual-property cleanup, wrapped inexecuteWithRetryonBadVersionException(asImmutableBucketdoes): a save for the same bucket key that published a replacement while the delete was in flight no longer loses its durable reference to the cleanup, and a version conflict settles instead of failingunsubscribe/clearDelayedMessagesafter the snapshot has already been deleted.removeCursorPropertyIfStillReferences/removeBucketCursorPropertyIfStillReferences); it can adopt this closure in a follow-up once this PR lands.Verifying this change
Added
ManagedCursorUpdatePropertiesTest:testUpdateCursorPropertiesAppliesTheWholeFunction/testUpdateCursorPropertiesOnEmptyProperties/testUpdateCursorPropertiesCanRemoveEverything: one closure adds, updates and removes keys, from empty and non-empty states.testConditionalRemovalOnlyAppliesWhileValueMatches: a conditional removal applies only while the value matches.testUpdateCursorPropertiesPropagatesFunctionFailureWithoutSideEffects(havingCause().isSameAs) /testUpdateCursorPropertiesRejectsNullReturn: a throwing function and a null return fail the returned future and leave the properties untouched.testUpdateCursorPropertiesSurvivesReopen: the closure's write survives a factory reopen.testConcurrentReplacementSurvivesConditionalRemoval: races aputCursorProperty(k, b)against a conditional removal of(k, a)for 100 iterations; the property always ends atb, and the removal is only allowed to settle on success orBadVersionException.testConcurrentUpdateCursorPropertiesBothSurviveRetry: two closures racing on the metadata version both succeed after retrying version conflicts (throughFutures.executeWithRetry).testConcurrentNonDurableUpdatesKeepBothEdits: two concurrent closures on a non-durable cursor both survive; with the publication outside the critical section the last edit erases the other.testMarkDeleteVersionRefreshAdoptsStoredProperties: after another factory's cursor writes the metadata, the mark-delete BadVersion refresh adopts the stored properties together with the fresh version — leaving the stale properties paired with the fresh version is the second motivation's hole.testDefaultUpdateCursorPropertiesAppliesPerKeyDifferences: the interface default applies the per-key differences and routes a throwing function into the returned future.Added
DelayedDeliveryTrackerFactoryTest#testCleanResidualSnapshotsKeepsReplacementPublishedDuringDelete: the snapshot delete is held open, a replacement is published under the same bucket key, and the cleanup must leave the replacement's reference in place — the broker-side change itself, which fails ifcleanResidualSnapshotsreverts to the unconditional removal.Remaining follow-up (not in this PR)
The retry contract of
MetaStoreImpl#asyncUpdateCursorInfodeserves its own discussion: cursor-info writes carry apublicationfingerprint (VerifyPublication) and the store may retry a write internally with the original bytes; the comment there states that a caller retrying after an error must likewise reuse its publication ID, payload and expected version. Today every property operation re-invoked by a caller (including a retry of this closure) produces a fresh publication UUID, which is a new write rather than the sanctioned retry shape. This PR keeps the documented sibling contract (BadVersion surfaces to the caller) and does not change that behavior, but a follow-up could align caller-side retries with the publication mechanism, or document explicitly that property-operation retries are always new writes.Does 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