Skip to content

Close GZIPInputStream wrapper in JdkHttpSender#toHttpResponse - #9080

Open
TimurRakhmatullin86 wants to merge 1 commit into
open-telemetry:mainfrom
TimurRakhmatullin86:fix/jdk-http-sender-gzip-leak
Open

TimurRakhmatullin86 wants to merge 1 commit into
open-telemetry:mainfrom
TimurRakhmatullin86:fix/jdk-http-sender-gzip-leak

Conversation

@TimurRakhmatullin86

@TimurRakhmatullin86 TimurRakhmatullin86 commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Problem

JdkHttpSender#toHttpResponse wraps the response body in a GZIPInputStream for gzip-encoded responses, drains it into a ByteArrayOutputStream, and never closes the wrapper. Only the underlying rawIs is declared in the try-with-resources (JdkHttpSender.java#L410-L412):

try (InputStream rawIs = response.body()) {
  // The limit is applied to the decompressed bytes.
  InputStream is = decompress ? new GZIPInputStream(rawIs) : rawIs;
  // ...read is...
}

Closing rawIs does not close the wrapper, so Inflater#end() is never called for the Inflater that the GZIPInputStream allocates. This applies to every exit from the block: normal completion, an IOException while reading, and the early exit when the read limit is reached.

Why it matters

This is missing explicit cleanup, not a permanent leak. Once the wrapper is unreachable, its Inflater is unreachable too, and OpenJDK releases the native zlib state through the Inflater's Cleaner (finalize() on JDK 8). Nothing is lost forever.

What the explicit close() changes:

  1. Timing of native memory release. The zlib inflate state lives outside the Java heap and is held until a GC cycle discovers the unreachable Inflater and the cleaner runs. With the fix it is released on the response thread as soon as the body has been read.
  2. Accumulation between GC cycles. The on-heap footprint of a wrapper is small, so it puts little pressure on the collector, while each one pins a larger native allocation. Under sustained export load with gzip responses, unreleased inflaters pile up between collections and show up as RSS growth that heap metrics do not explain.
  3. Resource hygiene. GZIPInputStream is AutoCloseable and was the only resource created in this block that was not managed by the try-with-resources.

Low severity, consistent with the review discussion: a temporary retention that the runtime eventually cleans up, made deterministic by this change.

Fix

Declare the wrapper as a second resource in the existing try-with-resources:

try (InputStream rawIs = response.body();
    InputStream is = decompress ? new GZIPInputStream(rawIs) : rawIs) {
  // ...read is...
}

Close semantics:

  • GZIPInputStream#close() ends its own Inflater and then closes the stream it wraps, so rawIs is closed by the wrapper and then a second time by the outer resource. The second close is a no-op.
  • When decompress is false both declarations reference the same stream, which is likewise closed twice.
  • If the GZIPInputStream constructor throws (malformed gzip header), rawIs is still closed by the first resource. Same behavior as before.

No change to what is read, to the size limit handling, or to the returned response.

Tests

JdkHttpSenderTest#sendInternal_gzipResponse_closesGzipWrapper sends a valid gzip payload through a mocked java.net.http.HttpResponse whose body stream counts close() calls.

  • Without the fix: only the outer try-with-resources closes the body stream, count == 1.
  • With the fix: the wrapper's close() forwards to the body stream and the outer resource closes it again, count >= 2.

The test fails with count == 1 against the previous version of the file.

@TimurRakhmatullin86
TimurRakhmatullin86 requested a review from a team as a code owner November 30, 2026 16:20
The gzip decompression path wraps the response body in a GZIPInputStream
but keeps only the underlying rawIs in the try-with-resources. Closing
rawIs does not close the wrapper, so its native Inflater is never
released. Every gzip response leaks one Inflater — and the same leak
fires on IO errors while reading, which already use this path.

Include the wrapper in the try-with-resources. Closing the gzip stream
also closes rawIs, so the second declaration in the resource list is
harmless when decompression is off.

Added JdkHttpSenderTest#sendInternal_gzipResponse_closesGzipWrapper:
the mocked body stream tracks close() calls. Without the fix the count
is 1 (outer try-with-resources only). With the fix the gzip wrapper
forwards its own close to the body, so the count is >= 2.
@opentelemetry-pr-dashboard

opentelemetry-pr-dashboard Bot commented Nov 30, 2026 •

Copy link
Copy Markdown

Pull request dashboard status

Waiting on maintainers · refreshed 2026-12-04 18:00 UTC

Merge when ready.

Status above doesn't look right?
  • Just replied or pushed? Anything around or after the refresh time above may not be picked up yet — give it a few minutes.
  • Should this be with the author? Comment /dashboard route:author to route it back.
  • Anything wrong — including the routing? Report it with what you expected; it helps us improve the dashboard.

@codecov

codecov Bot commented Nov 30, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.51%. Comparing base (2aec7ba) to head (a17a15e).

Additional details and impacted files
@@             Coverage Diff              @@
##               main    #9080      +/-   ##
============================================
- Coverage     90.52%   90.51%   -0.01%     
  Complexity    11243    11243              
============================================
  Files          1039     1039              
  Lines         30678    30678              
  Branches       4015     4015              
============================================
- Hits          27772    27769       -3     
- Misses         1928     1929       +1     
- Partials        978      980       +2     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@breedx-splk breedx-splk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks. I think this is mostly a reasonable change, but I'm not convinced how necessary it is. The agents say this about this:

On OpenJDK, the existing code delays cleanup of one native Inflater per gzip response. Calling it a permanent leak overstates the issue.

The old code closes the raw HTTP body and leaves the GZIPInputStream unclosed. Reading to EOF leaves the inflater allocated. Once the wrapper and its inflater become unreachable, OpenJDK’s Cleaner can free the native zlib state on the JVM’s schedule. During a burst of gzip responses, that native memory can accumulate before cleanup runs. PR diff, gzip EOF handling, OpenJDK 11 cleanup, OpenJDK 25 cleanup

So I'm slightly worried that this unnecessarily complicates things without fully understanding the performance implications. My instinct on matters like this is to defer to the decisions of the underlying runtime implementers....

Curious what the maintainers think.

@TimurRakhmatullin86

Copy link
Copy Markdown
Contributor Author

Thanks for pushing back. You and the agents are right that "permanent leak" overstates it — the inflater becomes unreachable with the wrapper, and OpenJDK's Inflater uses a Cleaner, so the native state does free eventually. I'll update the PR description to drop "leak."

The change still buys three things on this burst-heavy exporter path:

  1. Deterministic close. Cleaner runs on GC's schedule. Batch exporters flush in bursts, so under steady load this method runs many times in rapid succession and wrapper+inflater pairs accumulate on the heap until the next young-gen collection reclaims the wrappers. Closing in try-with-resources frees the zlib state on the response thread, decoupled from GC.
  2. Consistency with the rest of the block. rawIs is already in the try-with-resources here. The gzip response wrapper is the only resource in that block left to the Cleaner.
  3. No plaintext cost. When decompress is false the two declarations reference the same stream; close() is idempotent, so the extra resource in the block adds no work.

The test asserts the wrapper's close() is forwarded to the body, which is the behavior the fix produces regardless of how we frame the native state — happy to adjust the description if that framing reads better.

@jkwatson

jkwatson commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

This seems like a pretty harmless change to me; I'm not opposed to it if it fixes a potential short-term leak (although when GC runs, it may not matter at all really).

@jack-berg

Copy link
Copy Markdown
Member

I analyzed #9081, which is similar. It also prevents temporary leakage, not permanent leakage. Good to have, and I think we should proceed, but not mission critical (which explains why we haven't heard about it more loudly before this!)

This branch has not been deployed

No deployments
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