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 — [improve][broker] Hand the publish path's parsed message metadata to the entry cache by lhotari · Pull Request #265 · lhotari/pulsar

Conversation

@lhotari

@lhotari lhotari commented Sep 8, 2026

Copy link
Copy Markdown
Owner

Personal CI run for the message metadata hand-off, ahead of proposing it to apache/pulsar.

What is on this branch

  1. [improve][broker] Cache publish metadata and avoid repeated parsing in the broker send path apache/pulsar#25555 (dao-jun) — parse the message metadata once per publish and reuse it across the producer encryption check, the max-delivery-delay check and the deduplication paths.
  2. [fix][ml] Parse the cached entry's message metadata from the buffer the cache keeps apache/pulsar#26495 — parse the cached entry's metadata from the buffer the cache keeps. Already proposed separately; included here because it lives in the same code. Note this branch carries the earlier form of that fix; the branch proposed upstream (lh-fix-cached-metadata-buffer) has two further commits on top.
  3. The new part — hand the metadata the publish path already parsed to the entry cache, so RangeEntryCacheImpl.insert doesn't parse the same bytes a second time.

The new part, in short

ManagedLedgerImpl.asyncAddEntry asks the ctx object for the metadata, on the caller's thread while the buffer is still intact, and only when the entry is actually going to be cached:

if (!(ctx instanceof EntryMessageMetadataSupplier supplier)
        || !entryCache.isEnabled() || !shouldCacheAddedEntry()) {
    return null;
}

ctx already is the Topic.PublishContext on the publish path, so a small EntryMessageMetadataSupplier interface is enough and ManagedLedger keeps its existing signatures. Contexts that don't participate — REST produce, replication markers, the transaction buffer's null ctx, TxnLogBufferedWriter — return null from the interface default and pay nothing.

Producer.MessagePublishContext implements it by calling MessageMetadata#materialize() on the instance it memoized. That detaches the metadata from the buffer it was parsed from, which is what makes the hand-off safe at all: a parsed MessageMetadata keeps an unretained _parsedBuffer and decodes producerName, partitionKey, orderingKey, uuid, the properties and the rest lazily out of it, while the cached entry outlives the publish buffer. It also means those fields are resolved once on the publish thread instead of racily on whichever dispatcher thread reads them first.

Because the instance is detached, no buffer-lifetime guards are needed anywhere: OpAddEntry doesn't have to drop it when an interceptor replaces the buffer, and broker-entry-metadata and copy-entries deployments get the same benefit as the default one rather than falling back to a second parse.

What I want from CI

The publish path and the managed-ledger write path are both touched, so the whole broker and managed-ledger suites are the point. Specifically worth watching:

  • transaction tests (the transaction buffer and the transaction log pass a ctx that does not implement the new interface),
  • shadow topic tests (ShadowManagedLedgerImpl never caches, and requires ctx to stay instanceof Position),
  • broker-entry-metadata tests (Commands.addBrokerEntryMetadata replaces and releases the publish buffer for payloads up to 16 KB),
  • Key_Shared tests (Commands.resolveStickyKey reads exactly the lazily decoded fields).

Run locally and green: quickCheck, ManagedLedgerTest, RangeEntryCacheImplTest, EntryCacheManagerTest, EntryCacheTest, PersistentTopicTest, MessageDuplicationTest, ServerCnxTest, BrokerMessageDeduplicationTest, BrokerEntryMetadataE2ETest, ShadowTopicTest, ManagedLedgerInterceptorImplTest.

Sorry, something went wrong.

Uh oh!

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

All reactions
dao-jun and others added 14 commits April 21, 2026 17:12
@dao-jun
Cache publish metadata and avoid repeated parsing in the broker send …
6f8832a
…path
@dao-jun
fix import order
f9b5f1a
@dao-jun
Address review comments
23ec4e0
@dao-jun
Merge branch 'master' into improve/metadata_parse
31e5d50
# Conflicts:
#	pulsar-broker/src/main/java/org/apache/pulsar/broker/service/ServerCnx.java
@lhotari
Merge remote-tracking branch 'origin/master' into improve/metadata_parse
f19924f
@lhotari
[fix][ml] Parse the cached entry's message metadata from the buffer t…
6d4ce84
…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
[improve][broker] Hand the publish path's parsed message metadata to …
b63fb03
…the entry cache

### Motivation

This PR already parses the message metadata once per publish and reuses it
across the producer, delivery-delay and deduplication checks. When the entry is
then cached for tailing readers, `RangeEntryCacheImpl.insert` parses the very
same bytes a second time (apache#26463). Passing the instance along removes that
second parse, and pays back the per-message `new MessageMetadata()` that this PR
introduces in place of master's thread-local publish-path parse.

A `MessageMetadata` decodes its string and bytes fields lazily out of the buffer
it was parsed from, so it can only be attached to an entry that keeps that same
buffer alive. Three things can break that, and each is handled explicitly rather
than assumed away:

- a `ManagedLedgerInterceptor` can replace the entry buffer — `addBrokerEntryMetadata`
  copies and *releases* the original for payloads up to 16 KB — or rewrite the
  payload in place through the duplicate it gets in `processPayloadBeforeLedgerWrite`;
- a copying entry cache stores the payload in a buffer of its own;
- a `BrokerInterceptor` is handed the mutable `headersAndPayload` after the
  encryption-required check has already parsed it.

### Modifications

managed-ledger:

- `ManagedLedger.asyncAddEntry(ByteBuf, int, MessageMetadata, AddEntryCallback, Object)`:
  a default overload that takes the metadata the caller already parsed from the
  buffer. It is best effort by contract: silently ignored whenever it cannot be
  proven to stay valid, so nothing may assume a cached entry carries metadata.
- `ManagedLedger.canReuseParsedMessageMetadata()`: lets a caller skip a parse
  whose result would only be discarded. `ManagedLedgerImpl` answers true only
  when entries are being cached, no interceptor is configured and the cache does
  not copy — otherwise the eager parse would be added *on top of* the
  insert-time parse rather than replacing it.
- `OpAddEntry` carries the metadata to the entry it inserts into the cache,
  clears it in both recycler paths and in `setData`, and carries it across
  `duplicateAndClose` (same buffer). `run()` drops it whenever an interceptor is
  configured, which also covers in-place payload rewrites that leave no trace.

broker:

- `PersistentTopic.asyncAddEntry` passes the metadata along, gated on
  `canReuseParsedMessageMetadata()`, and falls back to null if the parse throws
  so that an unparseable message still publishes.
- `Producer` re-parses after a `BrokerInterceptor` has run, in a finally block
  that also restores the buffer's reader index: `addBrokerEntryMetadata` copies
  from `readerIndex()` for `readableBytes()`, so an index left advanced would
  truncate the persisted entry. Without the re-parse, a payload-rewriting
  interceptor would turn a stale local check into a poisoned cache entry served
  to every reader.
- `MessagePublishContext` memoizes only after a successful parse, and documents
  that the instance is owned by the entry cache: release it by nulling the
  reference, never by clearing, pooling or sharing it.
- `Topic.PublishContext.getMessageMetadata` documents the same ownership rule,
  which is why the default implementation must keep allocating a fresh instance
  rather than returning `Commands.parseMessageMetadata`'s thread-local one —
  `ReplicatedSubscriptionsController` passes itself as the context for every
  replication marker.

### Verifying this change

Added `ManagedLedgerTest.testCachedEntryReusesTheMessageMetadataPassedToAsyncAddEntry`,
`ManagedLedgerTest.testCachedEntryReparsesMetadataWhenAnInterceptorReplacesTheBuffer`
(real `addBrokerEntryMetadata` interceptor, sentinel metadata that deliberately
disagrees with the buffer) and
`PersistentTopicTest.testMessageMetadataIsReparsedAfterAnInterceptorRewritesThePayload`.
Each was checked to fail when the corresponding guard is removed.

The existing `asyncAddEntry` mocks in `PersistentTopicTest`, `ServerCnxTest` and
`MessageDuplicationTest` follow the call site to the new overload.

### Does this pull request potentially affect one of the following parts:

- [x] The public API: two default methods added to the `ManagedLedger`
      interface; third-party implementations inherit the no-op behaviour.
@lhotari
[fix][ml] Make testInsertParsesMessageMetadata detect the insert-time…
15a0ba2
… 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
[improve][broker] Address review of the message metadata hand-off
3b5babc
- canReuseParsedMessageMetadata() also requires the entry cache to be able to
  store anything. With managedLedgerCacheSizeMB=0 the managed ledger gets an
  EntryCacheDisabled whose insert() always returns false, so the guard used to
  answer true and the broker parsed the metadata on the IO thread for every
  published message only for OpAddEntry.run() to throw it away. Added
  EntryCache#isEnabled() to express that.
- Release the test's own reference to the buffer in
  testCachedEntryReparsesMetadataWhenAnInterceptorReplacesTheBuffer, which the
  interceptor's addBrokerEntryMetadata leaves behind.
- Advance the reader index in the interceptor used by
  testMessageMetadataIsReparsedAfterAnInterceptorRewritesThePayload, so the test
  covers the reader index restore and not just the metadata invalidation.
@lhotari
[improve][broker] Pin the broker side of the message metadata hand-off
06e120d
PersistentTopic passing the parsed metadata to the managed ledger, and skipping
the parse when canReuseParsedMessageMetadata() says it would be discarded, was
covered by no test: every ledger mock returns false for that guard by default,
so the whole branch went unexercised.
@lhotari
[improve][broker] Supply the parsed message metadata through the publ…
1d3a7d3
…ish context

Reworks the hand-off after review feedback, on two suggestions.

First, the managed ledger asks the ctx object rather than taking the metadata as
an extra asyncAddEntry parameter. ctx already is the Topic.PublishContext on the
publish path, so a small EntryMessageMetadataSupplier interface is enough and
ManagedLedger keeps its existing signatures. ManagedLedgerImpl only asks when the
entry is going to be cached, and does it on the caller's thread while the buffer
is intact, so contexts that don't participate pay nothing and the metadata is
never parsed on the managed ledger executor. This also drops the
canReuseParsedMessageMetadata() predicate and leaves the mocks in
PersistentTopicTest, ServerCnxTest and MessageDuplicationTest untouched.

Second, MessageMetadata#materialize() detaches the instance from the buffer it
was parsed from, which is exactly the invariant the hand-off needs. With that,
none of the buffer lifetime guards are necessary: OpAddEntry no longer has to
drop the metadata in setData(), nor skip the hand-off whenever a
ManagedLedgerInterceptor is configured, and the ledger no longer has to exclude
broker-entry-metadata or copy-entries deployments. Those configurations now get
the same benefit as the default one instead of falling back to a second parse.
Resolving the fields on the publish thread also removes the racy lazy decoding
that several dispatcher threads would otherwise do on a shared cached instance.
@lhotari
Merge remote-tracking branch 'origin/master' into lh-publish-metadata…
73b9f5f
…-to-entry-cache
@lhotari
[improve][broker] Don't supply metadata a copying entry cache cannot use
78693ad
Two defects found reviewing the previous commit.

Dropping the copy-entries condition from the reuse gate was wrong. With
managedLedgerCacheCopyEntries=true the cached entry is backed by the cache's own
copy, so RangeEntryCacheImpl.insert discards the supplied instance and parses
from that copy anyway — meaning the publish thread parsed and materialized for
nothing, two parses where master does one. The previous commit message claimed
the opposite. Ask the cache instead of the factory config:
EntryCache#canUseSuppliedMessageMetadata answers what the caller actually wants
to know, and it subsumes the cache-disabled case, so it replaces isEnabled().

A payload processor is handed a duplicate that shares memory with the entry
buffer, so it can rewrite the payload in place. Metadata parsed before it ran
would then describe bytes the entry no longer holds, and unlike a released
buffer that is not something materialize() can fix. OpAddEntry.initiate() drops
the metadata when a processor actually ran, which is narrower than the
interceptor-wide guard the previous commit removed: broker-entry-metadata alone
still gets the benefit.

Also corrects javadoc left describing the superseded design.
@lhotari
[improve][broker] Cover every lazily decoded field in the detachment …
5f2850f
…test

The design's memory safety rests on MessageMetadata#materialize() being total,
and that method is emitted by an external code generator. Pinning it through one
field left a lightproto upgrade free to regress the rest.

Set and assert every field that is decoded lazily out of the parsed buffer,
including the nested ones a shallow implementation would miss: the property
KeyValue, the encryption key, and the KeyValue metadata nested inside it.
@lhotari lhotari closed this Sep 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

No reviews

Uh oh!

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

Assignees

No one assigned

Labels

None yet

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

Uh oh!

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

2 participants

@lhotari @dao-jun
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.