GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — [fix][ml] Parse the cached entry's message metadata from the buffer the cache keeps by lhotari · Pull Request #26495 · apache/pulsar

Conversation

@lhotari

@lhotari lhotari commented Sep 8, 2026 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Member

Fixes #26493

This PR carries two related changes to how the managed ledger entry cache handles message metadata. The first is the fix for #26493; the second removes a per-entry metadata parse that can never succeed on the transaction log and the transaction pending ack store.

1. Parse the cached entry's metadata from the buffer the cache keeps

Motivation

RangeEntryCacheImpl.insert stores on the cached entry a MessageMetadata instance that was parsed from the incoming entry's buffer. That is only sound when the two share a buffer, and with managedLedgerCacheCopyEntries=true they don't: the cached entry is backed by a fresh copy from copyEntry(entry) while the incoming entry is released right after the insert returns.

It matters because a MessageMetadata keeps a reference to the buffer it was parsed from and decodes part of itself out of it lazily. lightproto's generated parseFrom ends with

_parsedBuffer = _buffer;   // no retain, no copy

and producerName, replicatedFrom, partitionKey, replicateTo, encryptionAlgo, encryptionParam, schemaVersion, orderingKey, uuid, schemaId and every properties key/value are decoded from _parsedBuffer on first access. Scalars such as sequenceId and publishTime are decoded eagerly by parseFrom, which is what makes the failure selective rather than obvious.

So for as long as the entry stays cached, those fields are read out of a released, pool-recycled buffer. They are read on hot paths — Commands.resolveStickyKey via AbstractBaseDispatcher.peekStickyKey, the metadata handed to entry filters in filterEntriesForConsumer, and PersistentTopicsBase's peek/examine — so the symptoms are wrong Key_Shared routing or wrong filter decisions rather than anything that points at a buffer lifetime problem.

Two paths reach it:

  • Read path — readFromStorage parses the metadata on each entry it creates and then inserts that entry into the cache, while the entries it returns are released once dispatch completes. Present since [improve][broker] Reduce unnecessary MessageMetadata parsing by caching the parsed instance in the broker cache #24682 + [fix][ml] PIP-430: Fix concurrency issue in MessageMetadata caching and improve caching #24836, so branch-4.2 is affected too.
  • Write path — since [improve][ml] Parse message metadata at entry cache insert time instead of under the wrapper write lock #26463 insert also parses the metadata on the incoming entry, and OpAddEntry.run releases that entry, and then its buffer in completeAdd, right after inserting. master only.

managedLedgerCacheCopyEntries defaults to false, so a default broker is not affected.

Modifications

  • Parse the metadata on the cache entry rather than on the incoming one, and only inherit the incoming entry's instance when the cache retains that same buffer (copyEntries == false).
  • Nothing depended on insert parsing the source entry: readFromStorage already parses the entries it returns, and the write path releases the incoming entry immediately. With managedLedgerCacheCopyEntries=true the read path now parses twice, once for the entry it returns and once for the cache's own copy. That is unavoidable, since a MessageMetadata cannot be rebound to another buffer, and the default copyEntries=false path is unchanged: the cached entry keeps the same buffer and inherits the instance.
  • Added a package-private @VisibleForTesting RangeEntryCacheImpl#getEntries() so tests can assert on what the cache actually holds rather than on the entry that was handed to it.

MessageMetadata#materialize() was considered as an alternative (thanks @merlimat for the pointer) and rejected: on the read path the instance insert receives still belongs to the entry being handed to the dispatcher, so it can't be mutated in place, and re-parsing from the buffer the cache already owns is a cheaper copy than materialize()/copyFrom since it leaves the string and bytes fields lazy. See the discussion below.

The invariant this establishes, and which is worth keeping in mind when touching EntryImpl.messageMetadata, is that an entry's message metadata must always have been parsed from that entry's own data buffer.

2. Skip metadata parsing for managed ledgers that don't hold Pulsar messages

Motivation

MLTransactionLogImpl and MLPendingAckStore open their own managed ledgers and store bare lightproto TransactionMetadataEntry / PendingAckMetadataEntry records rather than Pulsar messages. Since #24682 the entry cache parses every entry as a MessageMetadata at insert and read time, which for these ledgers can never succeed: Commands.parseMessageMetadata reads a 4-byte big-endian metadata length off the front of the payload, and the first byte of one of these records is a protobuf tag, so the length always decodes to at least 128 MiB and the lightproto parse walks off the end of the buffer.

EntryImpl.initializeMessageMetadataIfNeeded catches the resulting exception and leaves messageMetadata null, so no wrong metadata is ever produced, but it logs a warning with a stack trace for every entry. A broker with transactions enabled therefore warns once per transaction log and pending ack entry it writes, and once per entry it replays during recovery.

Modifications

  • Added ManagedLedgerConfig.pulsarMessageEntries, defaulting to true. The transaction log and the pending ack store set it to false on the config they already build before asyncOpen, so the value is fixed before the managed ledger and its entry cache exist. The field is additive and defaults to the existing behaviour.
  • RangeEntryCacheImpl.insert, RangeEntryCacheImpl.readFromStorage and EntryCacheDisabled skip initializeMessageMetadataIfNeeded when the flag is false. These are the only three places that parse an entry's metadata; every other reader falls back to peeking the buffer when Entry#getMessageMetadata() is null, which is already a normal condition (CompactedTopicImpl, NonPersistentTopic and ManagedLedgerImpl all hand out entries with null metadata today).
  • Dropped the lazy metadata initialization from RangeCacheEntryWrapper. With the parse skipped for these ledgers it would have re-introduced it on the first cache read, and for the ledgers that do hold messages insert has parsed the metadata eagerly since [improve][ml] Parse message metadata at entry cache insert time instead of under the wrapper write lock #26463. Removing it also makes the managedLedgerName that was threaded through RangeCache and RangeCacheEntryWrapper for its warning message dead, so that goes too, along with the two-argument RangeCache constructor which never had a caller.

Verifying this change

For the buffer lifetime fix. RangeEntryCacheImplTest.testCachedEntryMetadataStaysReadableWhenEntriesAreCopied inserts into a copyEntries=true cache, releases the source entry exactly as OpAddEntry does on the write path, and then reads a lazily decoded field off the cached entry. Against the pre-fix insert it fails with:

io.netty.util.IllegalReferenceCountException: refCnt: 0
	at org.apache.bookkeeper.mledger.impl.cache.RangeEntryCacheImplTest
	        .testCachedEntryMetadataStaysReadableWhenEntriesAreCopied(RangeEntryCacheImplTest.java:190)

An exception is the lucky outcome — the cached metadata holds an unretained duplicate that shares its parent's reference count, so once the pooled parent has been released and reused the duplicate sees a healthy refCnt again and simply decodes whatever now occupies that memory.

testReadFromStorageDoesNotShareSourceMetadataWithTheCopiedCacheEntry covers the read path shape, where insert receives an entry whose metadata was already parsed from the source buffer (thanks @void-ptr974 for catching that the original test didn't reach it: it hands insert an entry whose metadata is still null, so both arms of the copyEntries ? null : guard evaluate to null and the guard itself was unpinned). It drives the real readFromStorage path, asserts the cached entry's MessageMetadata is a different instance from the source entry's, and reads a lazily decoded string field back off the cached entry after the source has been released; the source payload is overwritten while it is still referenced, so a leftover dependency on it shows up as a wrong value rather than depending on when the pooled buffer happens to be reused.

testInsertReusesTheMessageMetadataTheEntryAlreadyCarries supplies a sentinel instance whose producerName deliberately disagrees with the serialized buffer, so that a silent re-parse cannot pass it.

For the parse skipping. A test per guarded site asserts that the metadata isn't parsed when the entries aren't Pulsar messages, each carrying an in-test control that pushes the same bytes through the same path with the flag on, so the assertion can't pass merely because the payload is unparseable. testInsertDoesNotParseMessageMetadataWhenTheEntriesArentPulsarMessages also reads the entry back through the cache, which is what pins the removal of the wrapper's lazy initialization. MLTransactionLogImplTest and TransactionTest assert that the two stores mark their managed ledgers and that a plain one keeps the default.

Every guard and both setters were mutation-tested: removing any one of them fails exactly the test that covers it, and restoring the wrapper's lazy initialization fails only the insert test.

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

Documentation

  • doc
  • doc-required
  • doc-not-needed
  • doc-complete

Matching PR in forked repository

PR in forked repository: N/A — the change is covered by the unit tests above.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
lhotari added 2 commits September 8, 2026 15:29
@lhotari
[fix][ml] Parse the cached entry's message metadata from the buffer t…
9d7f334
…he cache keeps

### Motivation

`RangeEntryCacheImpl.insert` parses the message metadata from the *incoming*
entry's buffer and stores that instance on the *cached* entry. A
`MessageMetadata` keeps a reference to the buffer it was parsed from
(`_parsedBuffer`) and decodes its string and bytes fields out of it lazily, so
the two must share a buffer.

They don't when `managedLedgerCacheCopyEntries=true`: the cache copies the
payload into a buffer of its own, while the incoming entry is released right
after the insert returns (`OpAddEntry.run` on the write path, and the caller on
the read path). From then on the cached metadata views a released, recycled
buffer, and every read of `producerName`, `partitionKey`, `orderingKey`, `uuid`,
the properties or the encryption keys returns another message's bytes or throws
`IllegalReferenceCountException`. `Commands.resolveStickyKey` reads exactly
those fields on the dispatch path, via `AbstractBaseDispatcher.peekStickyKey`.

Scalar fields such as `sequenceId` and `publishTime` are decoded eagerly and
keep working, which is what makes the failure silent and selective.

### Modifications

- Parse the metadata on the cached entry rather than on the incoming one, and
  only inherit the incoming entry's instance when the cache retains that same
  buffer (`copyEntries == false`). The parse stays ahead of `entries.put`, since
  `RangeCacheEntryWrapper.withNewInstance` reads `getMessageMetadata() != null`
  to decide whether anything still has to be initialized lazily.
- The read path already parses the metadata on the entries it returns
  (`RangeEntryCacheImpl.readFromStorage`), and the write path releases the
  incoming entry immediately, so nothing depended on `insert` parsing it there.

### Verifying this change

`RangeEntryCacheImplTest.testCachedEntryMetadataStaysReadableWhenEntriesAreCopied`
fails with `IllegalReferenceCountException: refCnt: 0` without the fix.
@lhotari
[fix][ml] Make testInsertParsesMessageMetadata detect the insert-time…
4c83cce
… parse again

Asserting on the entry read back out of the cache does not distinguish a parse
done by insert() from one done lazily by RangeCacheEntryWrapper.getValueInternal
on that very read, so the test passed even with the insert-time parse removed.

Assert RangeCacheEntryWrapper.messageMetadataInitialized before reading the entry
back, through a new package-private RangeCache#isMessageMetadataInitialized which
does not trigger the lazy path.
@lhotari lhotari added this to the 5.0.0-M2 milestone Sep 8, 2026
@lhotari lhotari added release/4.2.5 release/4.0.14 labels Sep 8, 2026
@lhotari
lhotari requested review from dao-jun, merlimat and nodece September 8, 2026 13:03
void-ptr974
void-ptr974 reviewed Sep 8, 2026
View reviewed changes
Comment thread ...d-ledger/src/test/java/org/apache/bookkeeper/mledger/impl/cache/RangeEntryCacheImplTest.java Resolved

Uh oh!

There was an error while loading. Please reload this page.

@lhotari
[fix][ml] Cover the read path shape in the cached metadata regression…
38f82c2
… test

The existing copyEntries=true test hands insert an entry whose message
metadata is still null, so both arms of `copyEntries ? null :
entry.getMessageMetadata()` evaluate to null and no test pins that guard.
readFromStorage parses the metadata of the entry it returns before inserting
it, which is the shape where sharing that instance with the cached copy leaves
it decoding lazily out of the released source buffer.
@merlimat

merlimat commented Sep 8, 2026

Copy link
Copy Markdown
Contributor

@lhotari Not sure if it helps here, though there's also a materialize() method in the lightproto objects, that will force the parsing of all fields, so that it doesn't depend anymore on the original buffer.

lhotari reacted with thumbs up emoji
All reactions
  • 👍 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@lhotari
lhotari marked this pull request as draft September 8, 2026 16:40
@lhotari
[improve][ml] Drop the vacuous instanceof around the insert time meta…
f943113
…data parse

The check tested the incoming `Entry` before the parse moved onto the cache
entry, and `EntryImpl.createWithRetainedDuplicate` is declared to return
`EntryImpl`, so the pattern match is statically always true.
@lhotari

lhotari commented Sep 8, 2026

Copy link
Copy Markdown
Member Author

@merlimat Thanks, I looked into it. materialize() does remove the buffer dependency, but it can't be applied to entry.getMessageMetadata() at this call site: on the read path that instance belongs to the entry readFromStorage is about to hand to the dispatcher — it is parsed at entry.initializeMessageMetadataIfNeeded(ml.getName()) and the same entry is passed to insert() four lines later — and materialize() mutates it: _parsedBuffer goes null and every *BufferIdx is reset to -1, which also flips _writeTo from the byte-exact _parsedBuffer.getBytes(...) passthrough to re-encoding from the decoded String. So the cache needs its own copy either way.

copyFrom would be a correct copy — it does come out fully buffer-independent, since the bytes fields go through getSchemaVersion()'s byte[] copy and every setter clears its *BufferIdx. The cost is that it eagerly decodes everything: a String per string field, a String per property key and value, a byte[] + Unpooled copy per bytes field, and it memoizes into the source instance on the way through the getters. Re-parsing from the buffer the cache already owns yields the same independent instance while leaving the string and bytes fields lazy, so nothing is decoded that no consumer reads. The allocation profile also differs in a way that matters for a cache: the second parse's temporaries die with the read callback, whereas everything materialize() or copyFrom decodes stays live for the entry's whole cache residency.

Where materialize() would be the right tool is if the cached metadata had to outlive the cache's own buffer — here it doesn't, since the cache entry retains that buffer for as long as it is cached and reader copies retainedDuplicate() it. So I've kept the re-parse, but happy to switch if you read the tradeoff differently.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@lhotari
lhotari marked this pull request as ready for review September 8, 2026 19:47
@lhotari
lhotari requested a review from void-ptr974 September 8, 2026 20:59
@lhotari lhotari mentioned this pull request Sep 8, 2026
[improve][broker] Hand the publish path's parsed message metadata to the entry cache lhotari/pulsar#265
Closed
merlimat
merlimat approved these changes Sep 8, 2026
View reviewed changes
@lhotari
lhotari marked this pull request as draft September 8, 2026 21:23
@lhotari

lhotari commented Sep 8, 2026

Copy link
Copy Markdown
Member Author

There's one more issue: when the entry doesn't contain a message, parsing the metadata will throw an exception (which is caught, however that will cause an overhead). This happens for MLTransactionLogImpl and MLPendingAckStore which store BatchedTransactionMetadataEntry and PendingAckMetadataEntry bytes directly to the managed ledger. There's no "magic bytes" as a header to differentiate these entries from ordinary message entries in a managed ledger.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@lhotari
[improve][ml] Skip message metadata parsing for ledgers that don't ho…
f57acac
…ld messages

### Motivation

`MLTransactionLogImpl` and `MLPendingAckStore` open their own managed ledgers and store bare
lightproto `TransactionMetadataEntry` / `PendingAckMetadataEntry` records rather than Pulsar
messages. Since apache#24682 the entry cache parses every entry as a `MessageMetadata` at insert and
read time, which for these ledgers can never succeed: `Commands.parseMessageMetadata` reads a
4-byte big-endian metadata length off the front of the payload, and the first byte of one of
these records is a protobuf tag, so the length always decodes to at least 128 MiB and the
lightproto parse walks off the end of the buffer.

`EntryImpl.initializeMessageMetadataIfNeeded` catches the resulting exception and leaves
`messageMetadata` null, so no wrong metadata is ever produced, but it logs a warning with a
stack trace for every entry. A broker with transactions enabled therefore warns once per
transaction log and pending ack entry it writes, and once per entry it replays during recovery.

### Modifications

- Added `ManagedLedgerConfig.pulsarMessageEntries`, defaulting to true. The transaction log and
  the pending ack store set it to false on the config they already build before `asyncOpen`, so
  the value is fixed before the managed ledger and its entry cache exist.
- `RangeEntryCacheImpl.insert`, `RangeEntryCacheImpl.readFromStorage` and `EntryCacheDisabled`
  skip `initializeMessageMetadataIfNeeded` when the flag is false. These are the only three
  places that parse an entry's metadata; every other reader falls back to peeking the buffer
  when `Entry#getMessageMetadata()` is null, which is already a normal condition.
- Dropped the lazy metadata initialization from `RangeCacheEntryWrapper`. With the parse skipped
  for these ledgers it would have re-introduced it on the first cache read, and for the ledgers
  that do hold messages `insert` has parsed the metadata eagerly since apache#26463. Removing it also
  makes the `managedLedgerName` that was threaded through `RangeCache` and
  `RangeCacheEntryWrapper` for its warning message dead, so that goes too, along with the
  two-argument `RangeCache` constructor which never had a caller.

### Verifying this change

Added a test per guarded site asserting that the metadata isn't parsed when the entries aren't
Pulsar messages, each carrying an in-test control that pushes the same bytes through the same
path with the flag on, so the assertion can't pass merely because the payload is unparseable.
`RangeEntryCacheImplTest.testInsertDoesNotParseMessageMetadataWhenTheEntriesArentPulsarMessages`
also reads the entry back through the cache, which is what pins the removal of the wrapper's
lazy initialization. `MLTransactionLogImplTest` and `TransactionTest` assert that the two stores
mark their managed ledgers, and that a plain one keeps the default.
@lhotari
lhotari marked this pull request as ready for review September 8, 2026 23:46
@nodece
nodece merged commit 9e0f694 into apache:master Sep 9, 2026
82 of 84 checks passed

Uh oh!

There was an error while loading. Please reload this page.

lhotari added a commit that referenced this pull request Sep 9, 2026
@lhotari
[fix][ml] Parse the cached entry's message metadata from the buffer t…
65ca2a6
…he cache keeps (#26495)

(cherry picked from commit 9e0f694)
@lhotari lhotari added cherry-picked/branch-4.2 and removed release/4.0.14 labels Sep 9, 2026
@lhotari lhotari mentioned this pull request Sep 16, 2026
[fix][test] Disable Pulsar message parsing for raw ledger test entries #26604
Merged
11 tasks
dao-jun pushed a commit to ascentstream/pulsar that referenced this pull request Sep 20, 2026
@lhotari @dao-jun
[fix][ml] Parse the cached entry's message metadata from the buffer t…
0796516
…he cache keeps (apache#26495)

(cherry picked from commit 9e0f694)
@dao-jun dao-jun mentioned this pull request Oct 4, 2026
[feat][ml] Port batch read and managed-ledger cache improvements (PIP-430) on BK 4.17.4.1 ascentstream/pulsar#105
Closed
Radiancebobo pushed a commit to Radiancebobo/pulsar that referenced this pull request Oct 8, 2026
@lhotari hechengbo
[fix][ml] Parse the cached entry's message metadata from the buffer t…
87a9558
…he cache keeps (apache#26495)
@nodece nodece mentioned this pull request Oct 13, 2026
[feat][ml] Port batch read and managed-ledger cache improvements (PIP-430) on BK 4.17.4.1 (ml-only subset) ascentstream/pulsar#106
Closed
nodece pushed a commit to ascentstream/pulsar that referenced this pull request Oct 13, 2026
@lhotari @nodece
[fix][ml] Parse the cached entry's message metadata from the buffer t…
3197cb7
…he cache keeps (apache#26495)

(cherry picked from commit 9e0f694)
(cherry picked from commit 0796516)
This was referenced Oct 22, 2026
[Bug] Topic can't be loaded once a cursor with properties is stored compressed (IllegalReferenceCountException: refCnt: 0) #27049
Closed
[fix][ml] Materialize compressed ManagedCursorInfo before releasing the decompressed buffer #27050
Merged
@namest504 namest504 mentioned this pull request Nov 27, 2026
[Bug] Transaction log and pending-ack store entries are parsed as MessageMetadata on every cache insert and always fail #26494
Open
2 of 3 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

@merlimat merlimat merlimat approved these changes
@nodece nodece Awaiting requested review from nodece
@dao-jun dao-jun Awaiting requested review from dao-jun
@void-ptr974 void-ptr974 Awaiting requested review from void-ptr974

Uh oh!

There was an error while loading. Please reload this page.

Assignees

No one assigned

Labels

cherry-picked/branch-4.2 release/4.2.5

Projects

None yet

Milestone

5.0.0-M2

Development

Successfully merging this pull request may close these issues.

[Bug] Cached MessageMetadata can outlive the buffer it was parsed from when managedLedgerCacheCopyEntries=true

Uh oh!

There was an error while loading. Please reload this page.

4 participants

@lhotari @merlimat @void-ptr974 @nodece
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.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.