Skip to content

[improve][ml] Add updateCursorProperties as an atomic read-modify-write closure - #27703

Merged
nodece merged 1 commit into
apache:masterfrom
nodece:atomic-cursor-property-removal
Nov 24, 2026
Merged

nodece merged 1 commit into
apache:masterfrom
nodece:atomic-cursor-property-removal

Conversation

@nodece

@nodece nodece commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

Motivation

Two races in cursor-property updates, found through the bucket-snapshot cleanup reviews (#26420/#27673):

  1. Broker-side compare-then-remove is two operations. The comparison reads the property from one snapshot; removeCursorProperty re-reads the property map and metadata version inside its own update. A concurrent putCursorProperty for 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.
  2. A version refresh can pair a fresh stat with stale properties. The BadVersion ownership refresh in persistPositionMetaStore calls updateCursorLedgerStat(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 surfaces BadVersionException on 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 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 instead of bumping the version.
  • computeCursorProperties validates the function result with Map.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.
  • updateCursorLedgerStat rebuilds cursorProperties from the ManagedCursorInfo inside the same critical section as the stat and managedCursorInfo, and writes the stat last — the volatile ordering a lock-free reader relies on. The BadVersion ownership refresh in persistPositionMetaStore previously installed a fresh stat next to stale properties; that pair wins the store's version check for an update computed from the stale properties. persistPositionMetaStore also 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#cleanResidualSnapshots uses the closure for its residual-property cleanup, wrapped in executeWithRetry on BadVersionException (as ImmutableBucket does): 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 failing unsubscribe/clearDelayedMessages after the snapshot has already been deleted.
  • The interface default is a best-effort, non-atomic fallback for implementations without an atomic variant: it applies the per-key differences through the individual property operations, diffing against the snapshot handed to the closure (a null property map behaves as empty), so an implementation returning a live map cannot turn another writer's concurrent change into a stale overwrite when the closure itself changed nothing.
  • Follow-up in flight: [fix][broker] Harden bucket snapshot delete and trim cleanup on failed creation #27673 currently guards these removals with a two-step check (removeCursorPropertyIfStillReferences / removeBucketCursorPropertyIfStillReferences); it can adopt this closure in a follow-up once this PR lands.

Verifying this change

  • Make sure that the change passes the CI checks.

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 a putCursorProperty(k, b) against a conditional removal of (k, a) for 100 iterations; the property always ends at b, and the removal is only allowed to settle on success or BadVersionException.
  • testConcurrentUpdateCursorPropertiesBothSurviveRetry: two closures racing on the metadata version both succeed after retrying version conflicts (through Futures.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 if cleanResidualSnapshots reverts to the unconditional removal.

Remaining follow-up (not in this PR)

The retry contract of MetaStoreImpl#asyncUpdateCursorInfo deserves its own discussion: cursor-info writes carry a publication fingerprint (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

  • Dependencies (add or upgrade a dependency)
  • The public API
  • The threading model
  • The schema
  • The default values of configurations
  • The binary protocol
  • The REST endpoints
  • The admin CLI options
  • The metrics
  • Anything that affects deployment

Documentation

@nodece
nodece marked this pull request as draft November 23, 2026 03:14
@nodece
nodece force-pushed the atomic-cursor-property-removal branch from 011785c to 5b86230 Compare November 23, 2026 04:48
@nodece nodece changed the title [improve][ml] Add conditional cursor-property removal applied in one update [improve][ml] Add updateCursorProperties, an atomic read-modify-write closure Nov 23, 2026
@nodece
nodece force-pushed the atomic-cursor-property-removal branch 2 times, most recently from 30c3c7f to 3cfd39a Compare November 23, 2026 05:46
@nodece
nodece marked this pull request as ready for review November 23, 2026 07:56
@nodece
nodece force-pushed the atomic-cursor-property-removal branch from 3cfd39a to b6ad115 Compare November 23, 2026 08:15
@nodece nodece changed the title [improve][ml] Add updateCursorProperties, an atomic read-modify-write closure [improve][ml] Add updateCursorProperties as an atomic read-modify-write closure Nov 23, 2026

@lhotari lhotari left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 null result wipes the stored properties and then fails the future (inline at ManagedCursorImpl.java:493).
  • I can't see how the new cursorPropertiesLock changes behaviour for the writer pair it guards. The writer that does install a fresh version next to stale properties, the BadVersion refresh in persistPositionMetaStore, refreshes only the stat and never the properties (inline at ManagedCursorImpl.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 CustomizedManagedLedgerStorageForTest also doesn't forward the new method.
  • Smaller suggestions on the cleanup caller and the tests.

@nodece
nodece force-pushed the atomic-cursor-property-removal branch 2 times, most recently from 191c606 to db51d0a Compare November 23, 2026 13:10
@nodece
nodece marked this pull request as draft November 23, 2026 13:12
@nodece
nodece force-pushed the atomic-cursor-property-removal branch from db51d0a to afc9f5a Compare November 23, 2026 13:13
@nodece
nodece marked this pull request as ready for review November 23, 2026 13:15
@nodece
nodece requested a review from lhotari November 23, 2026 13:15
@nodece
nodece force-pushed the atomic-cursor-property-removal branch from afc9f5a to 1ad9112 Compare November 23, 2026 14:08

@lhotari lhotari left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

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
@nodece
nodece force-pushed the atomic-cursor-property-removal branch from 1ad9112 to e5716bc Compare November 24, 2026 02:03

@lhotari lhotari left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@nodece
nodece merged commit 9bafa1b into apache:master Nov 24, 2026
44 checks passed
nodece added a commit to nodece/pulsar that referenced this pull request Nov 24, 2026
…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
nodece added a commit to nodece/pulsar that referenced this pull request Nov 24, 2026
…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
codelipenghui added a commit to codelipenghui/incubator-pulsar that referenced this pull request Nov 24, 2026
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)
lhotari pushed a commit that referenced this pull request Nov 24, 2026
nodece added a commit to nodece/pulsar that referenced this pull request Nov 25, 2026
…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
nodece added a commit to nodece/pulsar that referenced this pull request Nov 25, 2026
…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
nodece added a commit to nodece/pulsar that referenced this pull request Nov 25, 2026
…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
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.

3 participants