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 — Duplicate of slice should have the same capacity as the original slice so that it's not writable by lhotari · Pull Request #14093 · netty/netty

Conversation

@lhotari

@lhotari lhotari commented Jun 3, 2024

Copy link
Copy Markdown
Contributor

Motivation:

The issue #12919 is titled "ByteBuf slice duplicates are not slices". This behavior is very surprising. It explains why the SslHandler has been causing issues in Apache Pulsar. The incoming messages come from the network and use the LengthFieldBasedFrameDecoder, which slices the buffer into frame buffers. Pulsar later calls retainedDuplicate. This removes the effect of slicing (as described in issue #12919) and makes the buffer writable. The impact of this is that the original buffer used by the LengthFieldBasedFrameDecoder gets mutated by the SslHandler later when the sliced frame buffer (which is made writable with .retainedDuplicate) is passed to the Apache Bookkeeper client, which also uses Netty and contains an SslHandler. The SslHandler's cumulation in the attemptCopyToCumulation method thinks that it's fine to mutate the input buffer since it's writable and that's what causes data corruption.

Issue #12919 references the vert.x issue eclipse-vertx/vert.x#4509. It seems vert.x applied a workaround in eclipse-vertx/vert.x#4517.

I also found a workaround for a data corruption issue within Netty's http codecs, #11802. That was to address #11792.

Such workarounds won't be needed when we eliminate the surprising behaviour. The PR will address it for Sslhandler and also optimise the cumulation. I think #12919 should also be addressed so that a duplicating a slice doesn't provide write access to the parent buffer outside of the slice.

Modification:

For sliced buffers, make the duplicate() method duplicate the slice and not the underlying buffer.
When I was working on the changes, I noticed that io.netty.buffer.AdaptivePoolingAllocator.PooledNonRetainedSlicedByteBuf had already implemented duplicate so that it duplicates the slice and not the underlying buffer:

netty/buffer/src/main/java/io/netty/buffer/AdaptivePoolingAllocator.java

Lines 1238 to 1242 in ecebe1c

public ByteBuf duplicate() {
ensureAccessible();
return new PooledNonRetainedSlicedByteBuf(referenceCountDelegate, unwrap(), idx(0), capacity())
.setIndex(readerIndex(), writerIndex());
}

Result:

Fixes #12919.

If there is no issue then describe the changes introduced by this PR.

Sorry, something went wrong.

Uh oh!

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

franz1981 reacted with thumbs up emoji merlimat reacted with hooray emoji
All reactions
  • 👍 1 reaction
  • 🎉 1 reaction
lhotari added 2 commits June 3, 2024 07:56
@lhotari
A duplicate of a slice should be a slice
8426ec1
@lhotari
Add tests
5d45595
This was referenced Jun 3, 2024
ByteBuf slice duplicates are not slices #12919
Closed
Optimize wrap buffer cumulation in SslHandler and don't mutate input buffers #14086
Merged
normanmaurer
normanmaurer approved these changes Jun 3, 2024
View reviewed changes

@normanmaurer normanmaurer left a comment

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great catch!

Sorry, something went wrong.

Uh oh!

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

franz1981 reacted with rocket emoji
All reactions
  • 🚀 1 reaction
@lhotari

lhotari commented Jun 3, 2024

Copy link
Copy Markdown
Contributor Author

Reported a flaky test #14097 for the current build failure. It took some time to find out that finding the error or failure can be achieved by downloading the zip file, extracting it and then running find -name "*.xml" |xargs egrep '<error|<failure'.

All reactions

Sorry, something went wrong.

Uh oh!

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

@franz1981

franz1981 commented Jun 3, 2024

Copy link
Copy Markdown
Contributor

@vietj wdyt? it looks good to me

All reactions

Sorry, something went wrong.

Uh oh!

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

franz1981
franz1981 approved these changes Jun 3, 2024
View reviewed changes

@franz1981 franz1981 left a comment

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changes look good to me

Sorry, something went wrong.

Uh oh!

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

All reactions
chrisvest
chrisvest approved these changes Jun 3, 2024
View reviewed changes
@chrisvest chrisvest added this to the 4.1.111.Final milestone Jun 3, 2024
@chrisvest
chrisvest merged commit e9caa97 into netty:4.1 Jun 3, 2024
chrisvest pushed a commit that referenced this pull request Jun 3, 2024
@lhotari @chrisvest
Duplicate of slice should have the same capacity as the original slic…
21e5411
…e so that it's not writable (#14093)

Motivation:

The issue #12919 is titled "ByteBuf
slice duplicates are not slices". This behavior is very surprising. It
explains why the SslHandler has been causing issues in Apache Pulsar.
The incoming messages come from the network and use the
LengthFieldBasedFrameDecoder, which slices the buffer into frame
buffers. Pulsar later calls retainedDuplicate. This removes the effect
of slicing (as described in issue
#12919) and makes the buffer
writable. The impact of this is that the original buffer used by the
LengthFieldBasedFrameDecoder gets mutated by the SslHandler later when
the sliced frame buffer (which is made writable with .retainedDuplicate)
is passed to the Apache Bookkeeper client, which also uses Netty and
contains an SslHandler. The SslHandler's cumulation in the
attemptCopyToCumulation method thinks that it's fine to mutate the input
buffer since it's writable and that's what causes data corruption.

Issue #12919 references the vert.x
issue eclipse-vertx/vert.x#4509. It seems
vert.x applied a workaround in
eclipse-vertx/vert.x#4517.

I also found a workaround for a data corruption issue within Netty's
http codecs, #11802. That was to
address #11792.

Such workarounds won't be needed when we eliminate the surprising
behaviour. The PR will address it for Sslhandler and also optimise the
cumulation. I think #12919 should
also be addressed so that a duplicating a slice doesn't provide write
access to the parent buffer outside of the slice.

Modification:

For sliced buffers, make the `duplicate()` method duplicate the slice
and not the underlying buffer.
When I was working on the changes, I noticed that
`io.netty.buffer.AdaptivePoolingAllocator.PooledNonRetainedSlicedByteBuf`
had already implemented `duplicate` so that it duplicates the slice and
not the underlying buffer:

https://github.com/netty/netty/blob/ecebe1c102cf9a9e2faaccbfc12f594963af7326/buffer/src/main/java/io/netty/buffer/AdaptivePoolingAllocator.java#L1238-L1242

Result:

Fixes  #12919.

If there is no issue then describe the changes introduced by this PR.
This was referenced Jun 11, 2024
[improve][misc] Upgrade to Netty 4.1.111.Final and switch to use grpc-netty-shaded apache/pulsar#22892
Merged
Upgrade to Netty 4.1.111.Final and switch to use grpc-netty-shaded apache/bookkeeper#4426
Merged
hezhangjian pushed a commit to apache/bookkeeper that referenced this pull request Jun 13, 2024
@lhotari
Upgrade to Netty 4.1.111.Final and switch to use grpc-netty-shaded (#…
a95f698
…4426)

### Motivation

[Netty 4.1.111.Final](https://netty.io/news/2024/06/11/4-1-111-Final.html) contains important fixes:
- netty/netty#14086
- netty/netty#14093

On the Pulsar side these address Broker stability when TLS with Bookkeeper V2 protocol is used between Broker and Bookies. The Bookkeeper client didn't contain a workaround for the Netty SslHandler "feature" like Pulsar did. That's why Bookkeeper client was impacted. Netty 4.1.111.Final will address those stability issues with the Bookkeeper client when using V2 protocol over TLS.

### Changes

- Upgrade Netty to 4.1.111.Final
- Switch to use grpc-netty-shaded instead of grpc-netty
  - grpc-java is not compatible with Netty 4.1.111.Final. [grpc-java supports only specific Netty versions](https://github.com/grpc/grpc-java/blob/master/SECURITY.md#netty). The solution is to use grpc-netty-shaded instead of grpc-netty dependency.
- Add module to shade jetcd-core partially so that it can work with grpc-netty-shaded. 
  - jetcd-core library and it's transient dependency vertx-grpc has a direct dependency on grpc-netty and it doesn't work with grpc-netty-shaded without this solution.
  - this solution avoids the need to shade grpc libraries completely which would cause a lot of duplication and increase build times.
lhotari added a commit to apache/bookkeeper that referenced this pull request Jun 13, 2024
@lhotari
Upgrade to Netty 4.1.111.Final and switch to use grpc-netty-shaded (#…
7efcbd2
…4426)

[Netty 4.1.111.Final](https://netty.io/news/2024/06/11/4-1-111-Final.html) contains important fixes:
- netty/netty#14086
- netty/netty#14093

On the Pulsar side these address Broker stability when TLS with Bookkeeper V2 protocol is used between Broker and Bookies. The Bookkeeper client didn't contain a workaround for the Netty SslHandler "feature" like Pulsar did. That's why Bookkeeper client was impacted. Netty 4.1.111.Final will address those stability issues with the Bookkeeper client when using V2 protocol over TLS.

- Upgrade Netty to 4.1.111.Final
- Switch to use grpc-netty-shaded instead of grpc-netty
  - grpc-java is not compatible with Netty 4.1.111.Final. [grpc-java supports only specific Netty versions](https://github.com/grpc/grpc-java/blob/master/SECURITY.md#netty). The solution is to use grpc-netty-shaded instead of grpc-netty dependency.
- Add module to shade jetcd-core partially so that it can work with grpc-netty-shaded.
  - jetcd-core library and it's transient dependency vertx-grpc has a direct dependency on grpc-netty and it doesn't work with grpc-netty-shaded without this solution.
  - this solution avoids the need to shade grpc libraries completely which would cause a lot of duplication and increase build times.

(cherry picked from commit a95f698)
lhotari added a commit to apache/bookkeeper that referenced this pull request Jun 13, 2024
@lhotari
Upgrade to Netty 4.1.111.Final and switch to use grpc-netty-shaded (#…
f5dfd89
…4426)

[Netty 4.1.111.Final](https://netty.io/news/2024/06/11/4-1-111-Final.html) contains important fixes:
- netty/netty#14086
- netty/netty#14093

On the Pulsar side these address Broker stability when TLS with Bookkeeper V2 protocol is used between Broker and Bookies. The Bookkeeper client didn't contain a workaround for the Netty SslHandler "feature" like Pulsar did. That's why Bookkeeper client was impacted. Netty 4.1.111.Final will address those stability issues with the Bookkeeper client when using V2 protocol over TLS.

- Upgrade Netty to 4.1.111.Final
- Switch to use grpc-netty-shaded instead of grpc-netty
  - grpc-java is not compatible with Netty 4.1.111.Final. [grpc-java supports only specific Netty versions](https://github.com/grpc/grpc-java/blob/master/SECURITY.md#netty). The solution is to use grpc-netty-shaded instead of grpc-netty dependency.
- Add module to shade jetcd-core partially so that it can work with grpc-netty-shaded.
  - jetcd-core library and it's transient dependency vertx-grpc has a direct dependency on grpc-netty and it doesn't work with grpc-netty-shaded without this solution.
  - this solution avoids the need to shade grpc libraries completely which would cause a lot of duplication and increase build times.

(cherry picked from commit a95f698)
@sergiitk sergiitk mentioned this pull request Jun 14, 2024
grpc-netty breaks with Netty 4.1.111.Final grpc/grpc-java#11284
Closed
@lhotari lhotari mentioned this pull request Jun 17, 2024
Apparent corruption with gRPC and Netty 4.1.111 #14126
Closed
Ghatage pushed a commit to sijie/bookkeeper that referenced this pull request Jul 12, 2024
@lhotari Anup Ghatage
Upgrade to Netty 4.1.111.Final and switch to use grpc-netty-shaded (a…
67c870f
…pache#4426)

### Motivation

[Netty 4.1.111.Final](https://netty.io/news/2024/06/11/4-1-111-Final.html) contains important fixes:
- netty/netty#14086
- netty/netty#14093

On the Pulsar side these address Broker stability when TLS with Bookkeeper V2 protocol is used between Broker and Bookies. The Bookkeeper client didn't contain a workaround for the Netty SslHandler "feature" like Pulsar did. That's why Bookkeeper client was impacted. Netty 4.1.111.Final will address those stability issues with the Bookkeeper client when using V2 protocol over TLS.

### Changes

- Upgrade Netty to 4.1.111.Final
- Switch to use grpc-netty-shaded instead of grpc-netty
  - grpc-java is not compatible with Netty 4.1.111.Final. [grpc-java supports only specific Netty versions](https://github.com/grpc/grpc-java/blob/master/SECURITY.md#netty). The solution is to use grpc-netty-shaded instead of grpc-netty dependency.
- Add module to shade jetcd-core partially so that it can work with grpc-netty-shaded. 
  - jetcd-core library and it's transient dependency vertx-grpc has a direct dependency on grpc-netty and it doesn't work with grpc-netty-shaded without this solution.
  - this solution avoids the need to shade grpc libraries completely which would cause a lot of duplication and increase build times.
@j1wonpark j1wonpark mentioned this pull request Mar 29, 2026
[SPARK-52965][BUILD] Upgrade gRPC to 1.76.0 on branch-4.0 apache/spark#55081
Closed
@shivaspeaks shivaspeaks mentioned this pull request Apr 30, 2026
Implement Adaptive Cumulator #16731
Merged
chrisvest pushed a commit that referenced this pull request Jul 1, 2026
@shivaspeaks
Implement Adaptive Cumulator (#16731)
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 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
@netty-project-bot netty-project-bot mentioned this pull request Jul 1, 2026
Auto-port 5.0: Implement Adaptive Cumulator #17033
Merged
chrisvest pushed a commit that referenced this pull request Jul 2, 2026
@netty-project-bot @shivaspeaks
Auto-port 5.0: Implement Adaptive Cumulator (#17033)
8eaa813
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 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

Co-authored-by: MV Shiva <[email protected]>
This was referenced Sep 14, 2026
Http2: Reserve promised stream for PUSH_PROMISE after local RST_STREAM #17471
Closed
cache failure 1233e4a5 #17565
Closed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

@chrisvest chrisvest chrisvest approved these changes
@normanmaurer normanmaurer normanmaurer approved these changes
@franz1981 franz1981 franz1981 approved these changes

Uh oh!

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

Assignees

No one assigned

Labels

None yet

Projects

None yet

Milestone

4.1.111.Final

Development

Successfully merging this pull request may close these issues.

ByteBuf slice duplicates are not slices

Uh oh!

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

4 participants

@lhotari @franz1981 @chrisvest @normanmaurer
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.