GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
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
Owner
Personal CI run for the message metadata hand-off, ahead of proposing it to What is on this branch
The new part, in short
if (!(ctx instanceof EntryMessageMetadataSupplier supplier) || !entryCache.isEnabled() || !shouldCacheAddedEntry()) { return null; }
Because the instance is detached, no buffer-lifetime guards are needed anywhere: What I want from CIThe 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:
Run locally and green:
Sorry, something went wrong. Uh oh!
There was an error while loading. Please reload this page. All reactions# Conflicts: # pulsar-broker/src/main/java/org/apache/pulsar/broker/service/ServerCnx.java …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. …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. … 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. - 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. 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. …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. 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. …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.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ReviewersNo reviewsUh oh!
There was an error while loading. Please reload this page. AssigneesNo one assignedLabels
None yet
ProjectsMilestoneNo milestoneDevelopmentSuccessfully merging this pull request may close these issues. Uh oh!
There was an error while loading. Please reload this page. 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. |