Repository navigation
Auto-port 5.0: Implement Adaptive Cumulator - #17033
Merged
Merged
Conversation
**Motivation:** This PR introduces the `AdaptiveCumulator`, a specialized Cumulator implementation for `ByteToMessageDecoder` that dynamically switches between merge (memory copy) and compose (zero-copy) strategies based on the size of incoming data. Standard cumulators in Netty present a trade-off: the `MERGE_CUMULATOR` is safe but can consume up to 10% of CPU time due to excessive copies during high-throughput transfers. Conversely, the `COMPOSITE_CUMULATOR` provides zero-copy benefits but is vulnerable to "Single Byte Attacks," where an attacker sends messages one byte at a time to force the server to allocate excessive object metadata. The `AdaptiveCumulator` applies a heuristic to achieve the best of both worlds: - **Merge (Copy):** If the total size of the tail component and the incoming buffer is below a configurable threshold (default 1024 bytes), the data is copied into a new buffer to minimize object overhead. - **Compose (Zero-Copy):** Once the threshold is reached, the buffer is added as a new component without copying, maximizing throughput. **Modification:** - Added `AdaptiveCumulator.java` to the `io.netty.handler.codec` package. - Added `AdaptiveCumulatorTest.java`, a comprehensive test suite modernized for JUnit 5. This PR is an attempt to upstream what we were trying to do in gRPC grpc/grpc-java#9558, but the behaviour of `duplicate()` method on slices was changed/corrected in #14093 which invalidated previous manual index workarounds and since then it has been a tech debt in grpc-java. This implementation is "PR #14093-aware" and correctly handles the capacity-capping introduced by that change by verifying the state of the tail component before expansion. This implementation is specifically designed to address historical failure modes associated with `CompositeByteBuf` manipulation: - **Modernized Index Synchronization with componentSlice()** Previous attempts to implement this logic relied on fragile internal hacks like `internalComponent().duplicate()` to correct stale indices returned by `CompositeByteBuf.component()`. This PR leverages the `componentSlice()` method (introduced in Netty 4.2.4) to obtain a correctly indexed view through a public, supported API. - **Protection Against "Resurrected" Bytes** To prevent silent data corruption, we have introduced a capacity safety check: `tail.capacity() == componentView.capacity()`. If a mismatch is detected, it indicates the component is a partial slice containing hidden "discarded" bytes. In such cases, the logic correctly falls back to a safe reallocation to "cleanse" the data, preventing discarded bytes from reappearing in the message. This particular problem was caught in the unit test `mergeWithCompositeTail_detectsIndicesInNestedComposite()` while trying to invalidate the use of previous way (`internalComponent.duplicate()`) as in grpc/grpc-java#9558. - **Prevention of "Russian Doll" Nesting** The implementation strictly uses `addFlattenedComponents` to ensure the `CompositeByteBuf` remains a flat, linear structure. This avoids the recursive deallocation crashes (StackOverflow) that occurred in previous versions when buffers were nested thousands of layers deep. - **Single-Owner Lifecycle Management** The lifecycle of the input buffer is managed using a single-owner pattern in the top-level cumulate method. Sub-methods like `mergeWithCompositeTail` no longer release the input buffer in their finally blocks, which we were doing otherwise in grpc/grpc-java#9558. This prevents `IllegalReferenceCountException` (double-release) crashes during error scenarios. **Usage** Downstream projects can enable the `AdaptiveCumulator` by calling the `setCumulator()` method on any handler that extends `ByteToMessageDecoder`. For example, to use the adaptive strategy with a 1KB threshold: `setCumulator(new AdaptiveCumulator(1024));` CC: @ejona86, @sauravzg (cherry picked from commit bc4b983)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Auto-port of #16731 to 5.0
Cherry-picked commit: bc4b983
Motivation:
This PR introduces the
AdaptiveCumulator, a specialized Cumulator implementation forByteToMessageDecoderthat dynamically switches between merge (memory copy) and compose (zero-copy) strategies based on the size of incoming data.Standard cumulators in Netty present a trade-off: the
MERGE_CUMULATORis safe but can consume up to 10% of CPU time due to excessive copies during high-throughput transfers. Conversely, theCOMPOSITE_CUMULATORprovides zero-copy benefits but is vulnerable to "Single Byte Attacks," where an attacker sends messages one byte at a time to force the server to allocate excessive object metadata.The
AdaptiveCumulatorapplies a heuristic to achieve the best of both worlds:Modification:
AdaptiveCumulator.javato theio.netty.handler.codecpackage.AdaptiveCumulatorTest.java, a comprehensive test suite modernized for JUnit 5.This PR is an attempt to upstream what we were trying to do in gRPC grpc/grpc-java#9558, but the behaviour of
duplicate()method on slices was changed/corrected in #14093 which invalidated previous manual index workarounds and since then it has been a tech debt in grpc-java. This implementation is "PR #14093-aware" and correctly handles the capacity-capping introduced by that change by verifying the state of the tail component before expansion.This implementation is specifically designed to address historical failure modes associated with
CompositeByteBufmanipulation:Modernized Index Synchronization with componentSlice() Previous attempts to implement this logic relied on fragile internal hacks like
internalComponent().duplicate()to correct stale indices returned byCompositeByteBuf.component(). This PR leverages thecomponentSlice()method (introduced in Netty 4.2.4) to obtain a correctly indexed view through a public, supported API.Protection Against "Resurrected" Bytes To prevent silent data corruption, we have introduced a capacity safety check:
tail.capacity() == componentView.capacity(). If a mismatch is detected, it indicates the component is a partial slice containing hidden "discarded" bytes. In such cases, the logic correctly falls back to a safe reallocation to "cleanse" the data, preventing discarded bytes from reappearing in the message. This particular problem was caught in the unit testmergeWithCompositeTail_detectsIndicesInNestedComposite()while trying to invalidate the use of previous way (internalComponent.duplicate()) as in netty: create adaptive cumulator grpc/grpc-java#9558.Prevention of "Russian Doll" Nesting The implementation strictly uses
addFlattenedComponentsto ensure theCompositeByteBufremains a flat, linear structure. This avoids the recursive deallocation crashes (StackOverflow) that occurred in previous versions when buffers were nested thousands of layers deep.Single-Owner Lifecycle Management The lifecycle of the input buffer is managed using a single-owner pattern in the top-level cumulate method. Sub-methods like
mergeWithCompositeTailno longer release the input buffer in their finally blocks, which we were doing otherwise in netty: create adaptive cumulator grpc/grpc-java#9558. This preventsIllegalReferenceCountException(double-release) crashes during error scenarios.Usage
Downstream projects can enable the
AdaptiveCumulatorby calling thesetCumulator()method on any handler that extendsByteToMessageDecoder. For example, to use the adaptive strategy with a 1KB threshold:setCumulator(new AdaptiveCumulator(1024));CC: @ejona86, @sauravzg