Skip to content

Close gzip Source/Sink wrappers in OkHttp senders - #9081

Open
TimurRakhmatullin86 wants to merge 4 commits into
open-telemetry:mainfrom
TimurRakhmatullin86:fix/okhttp-sender-gzip-leak
Open

TimurRakhmatullin86 wants to merge 4 commits into
open-telemetry:mainfrom
TimurRakhmatullin86:fix/okhttp-sender-gzip-leak

Conversation

@TimurRakhmatullin86

@TimurRakhmatullin86 TimurRakhmatullin86 commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Problem

The OkHttp senders create gzip wrappers that are not closed on every exit path:

  • OkHttpHttpSender#handleResponse wraps the response body in a GzipSource and does not close the wrapper; only the ResponseBody is in the try-with-resources (before, L216).
  • OkHttpGrpcSender#handleResponse creates a GzipSource over the buffered message and does not close it on success, on a failed read, or on the early return for an oversized decompressed message (before, L379).
  • OkHttpHttpSender.RequestBodyImpl#writeTo closes the compressed sink only on the success path. If MessageWriter#writeMessage throws, compressedSink.close() is skipped (before, L309-L312).

Why it matters

This is missing explicit cleanup, not permanent retention. Once a wrapper is unreachable, its Inflater/Deflater is unreachable too, and OpenJDK releases the native zlib state through the Cleaner (finalize() on JDK 8).

The explicit close() makes that release deterministic: the native state is freed on the calling thread as soon as the body has been handled, instead of being deferred to GC. Under sustained export load with gzip enabled, this avoids native memory accumulating between collections. Low severity, same as #9080.

Fix

Each wrapper is now declared in a try-with-resources, following the pattern from #9080:

  • OkHttpHttpSender#handleResponse (after, L217-L218): GzipSource#close() ends its Inflater and closes the wrapped source; the enclosing ResponseBody resource then closes it again, which is a no-op. Without gzip the body source is likewise closed twice.
  • OkHttpGrpcSender#handleResponse (after, L378): the wrapped source is an in-memory Buffer, so only the Inflater is affected.
  • RequestBodyImpl#writeTo (after, L318-L321): the compressed sink is closed when writeMessage throws.

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

Tests

  • OkHttpHttpSenderTest#requestBody_compressedWriterThrows_closesCompressedSink: a Compressor returns a stream that counts close() calls and the MessageWriter throws. Close count is 1 with the fix, 0 without it.
  • OkHttpGrpcSenderTest#handleResponse_gzipResponse_success: valid gzip message is decompressed, status OK.
  • OkHttpGrpcSenderTest#handleResponse_gzipResponse_oversized: decompressed size above the limit yields RESOURCE_EXHAUSTED.
  • OkHttpGrpcSenderTest#handleResponse_gzipResponse_corrupt: corrupt gzip payload yields an empty body with the status from the trailers.

The response-side changes are covered by behavior tests on each exit path. The Inflater is created inside the methods, so its release is not asserted directly.

@TimurRakhmatullin86
TimurRakhmatullin86 requested a review from a team as a code owner November 30, 2026 16:25
@opentelemetry-pr-dashboard

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

Copy link
Copy Markdown

Pull request dashboard status

Waiting on reviewers · refreshed 2026-12-05 05:18 UTC

Review the latest changes.

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.

Two related leaks of native compressor resources:

* handleResponse wrapped the response body in a GzipSource but only
  closed the underlying body stream; the wrapper's native Inflater was
  never released. Every gzip response leaked one Inflater, and the
  same leak fires on IO errors while reading (same path).
* RequestBodyImpl.writeTo buffered the compressor's output stream and
  called compressedSink.close() at the end, but a throw from
  requestBodyWriter.writeMessage skipped the close() call, leaking the
  underlying GZIPOutputStream's native Deflater on every failed send
  under compression.

Fix: close the GzipSource in a finally block (it owns the wrapped
stream, which belongs to the outer ResponseBody try-with-resources,
so only close the wrapper when we actually created it); and move the
buffered sink into a try-with-resources so writeMessage throwing
still releases it.

Added OkHttpHttpSenderTest#requestBody_compressedWriterThrows_closesCompressedSink:
a tracking Compressor returns an OutputStream that counts close(),
a MessageWriter throws from writeMessage, writeTo is called via
reflection on the private RequestBodyImpl, and the test asserts that
close() fires exactly once (was zero before the fix).
@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.53%. Comparing base (ddaf381) to head (d1d4fb6).

Additional details and impacted files
@@             Coverage Diff              @@
##               main    #9081      +/-   ##
============================================
+ Coverage     90.50%   90.53%   +0.03%     
- Complexity    11273    11275       +2     
============================================
  Files          1040     1040              
  Lines         30762    30760       -2     
  Branches       4035     4035              
============================================
+ Hits          27840    27849       +9     
+ Misses         1938     1930       -8     
+ Partials        984      981       -3     

☔ 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.

logger.log(Level.WARNING, "Failed to read response body", e);
} finally {
if (decompress && source != null) {
try {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Could you also close the GzipSource in OkHttpGrpcSender.handleResponse (OkHttpGrpcSender.java:379), either here or in a linked follow-up PR? It has the same missing wrapper cleanup on success, read failure, and oversized decompressed responses. #9080 covers the JDK sender, but I couldn't find a tracked PR covering this gRPC path.

Comment on lines +215 to +217
// The GzipSource wrapper owns a native Inflater that must be released. The underlying
// body.source() is owned by `body` (already in the outer try-with-resources), so only
// close it when we created the wrapper.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Could you clarify the PR descriptions here and in #9080 to distinguish missing explicit cleanup from permanent leakage? #9080 still says the native inflater is "never released". As you noted in that discussion, OpenJDK provides GC-triggered cleanup for unreachable inflater/deflater state. These changes make release deterministic, avoiding retention until that cleanup runs, rather than establishing unbounded memory growth.

…p-leak

# Conflicts:
#	exporters/sender/okhttp/src/main/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpHttpSender.java
…with-resources

- OkHttpHttpSender#handleResponse: declare the response source in a
  try-with-resources instead of closing the GzipSource in a finally block.
  Removes the nullable local, the nested try/catch and the separate close
  warning; the read failure handling from main is unchanged.
- OkHttpGrpcSender#handleResponse: declare the GzipSource in a
  try-with-resources so it is closed on success, on a failed decompression
  and on the early return for an oversized decompressed message.
- OkHttpGrpcSenderTest: add gzip response tests for the success, oversized
  and corrupt payload paths.
- OkHttpHttpSenderTest: reword the comment and failure message. Closing the
  wrappers makes the release of native zlib state deterministic; without it
  the release is deferred to GC.
@TimurRakhmatullin86 TimurRakhmatullin86 changed the title Close gzip Source/Sink wrappers in OkHttpHttpSender Close gzip Source/Sink wrappers in OkHttp senders Dec 5, 2026
@TimurRakhmatullin86

Copy link
Copy Markdown
Contributor Author

@jack-berg — addressing both of your review points:

On the OkHttpGrpcSender suggestion: done in d1d4fb6. GzipSource in OkHttpGrpcSender.handleResponse is now in a try-with-resources, covering the success, read-failure, and oversized paths. Added three tests in OkHttpGrpcSenderTest: handleResponse_gzipResponse_success, handleResponse_gzipResponse_oversized, handleResponse_gzipResponse_corrupt.

On the descriptions: updated both #9080 and #9081 to frame this as missing explicit cleanup rather than permanent retention. OpenJDK's Cleaner releases the native zlib state once the wrapper is unreachable; the explicit close makes the release deterministic on the calling thread.

#9080 has no code changes since your approval, only the description, so it should be good to go from my side.

Also rebased onto current main to resolve a conflict with #9063 — the catch now uses the throttlingLogger pattern from that PR.

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.

2 participants