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
commented
Sep 8, 2026
•
edited
Loading
Uh oh!
There was an error while loading. Please reload this page.
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:
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.
…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.
… 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.
Uh oh!
There was an error while loading. Please reload this page.
… 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.
|
@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
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
…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.
|
@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.
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
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.
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
…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.
Uh oh!
There was an error while loading. Please reload this page.
nodece
pushed a commit
to ascentstream/pulsar
that referenced
this pull request
Oct 13, 2026
This was referenced Oct 22, 2026
Uh oh!
There was an error while loading. Please reload this page.
Assignees
No one assigned
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.
|