Skip to content

Auto-port 5.0: Implement Adaptive Cumulator - #17033

Merged
chrisvest merged 2 commits into
5.0from
auto-port-pr-16731-to-5.0
Jul 2, 2026
Merged

chrisvest merged 2 commits into
5.0from
auto-port-pr-16731-to-5.0

Conversation

@netty-project-bot

Copy link
Copy Markdown
Contributor

Auto-port of #16731 to 5.0
Cherry-picked commit: bc4b983


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 netty: create adaptive cumulator 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 netty: create adaptive cumulator 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

**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)
@chrisvest chrisvest added this to the 5.0.0.Final milestone Jul 1, 2026
@chrisvest
chrisvest enabled auto-merge (squash) July 1, 2026 23:29
@chrisvest
chrisvest merged commit 8eaa813 into 5.0 Jul 2, 2026
13 checks passed
@chrisvest
chrisvest deleted the auto-port-pr-16731-to-5.0 branch July 2, 2026 10:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants