Skip to content

fix: resolve memory leaks in several places [backport #1060] - #1062

Merged
kalbasit merged 1 commit into
release-0.9from
backport-1060-to-release-0.9
Mar 11, 2026
Merged

kalbasit merged 1 commit into
release-0.9from
backport-1060-to-release-0.9

Conversation

@kalbasit

Copy link
Copy Markdown
Owner

Bot-based backport to release-0.9, triggered by a label in #1060.

Three resource leak fixes identified from memory profiling:

  1. pkg/zstd/zstd.go: Add runtime.SetFinalizer on pooled zstd.Decoder
    instances. Each decoder spawns background goroutines that hold a
    back-reference to it, preventing GC after sync.Pool clears the entry
    via the victim cache. This causes linear memory growth (~10 GB/hr
    under load). The finalizer calls Close() when the decoder becomes
    unreachable, stopping its goroutines.

  2. pkg/cache/upstream/cache.go: Close non-200 HTTP response bodies after
    draining them. Without Close(), the HTTP transport cannot return
    connections to the pool, causing exhaustion under error conditions.

  3. pkg/cache/cache.go: Close the storage reader when the database
    transaction fails in getNarFromStore. The reader (which may wrap a
    zstd decoder with background goroutines) was being silently dropped,
    leaking file handles.

Three resource leak fixes identified from memory profiling:

1. pkg/zstd/zstd.go: Add runtime.SetFinalizer on pooled zstd.Decoder
   instances. Each decoder spawns background goroutines that hold a
   back-reference to it, preventing GC after sync.Pool clears the entry
   via the victim cache. This causes linear memory growth (~10 GB/hr
   under load). The finalizer calls Close() when the decoder becomes
   unreachable, stopping its goroutines.

2. pkg/cache/upstream/cache.go: Close non-200 HTTP response bodies after
   draining them. Without Close(), the HTTP transport cannot return
   connections to the pool, causing exhaustion under error conditions.

3. pkg/cache/cache.go: Close the storage reader when the database
   transaction fails in getNarFromStore. The reader (which may wrap a
   zstd decoder with background goroutines) was being silently dropped,
   leaking file handles.

---------

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
(cherry picked from commit 3bb7739)
@kalbasit
kalbasit enabled auto-merge (squash) March 11, 2026 04:31
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. bug Something isn't working go Pull requests that update go code labels Mar 11, 2026
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request addresses several critical resource and memory leaks identified through profiling. The changes focus on ensuring proper closure of zstd.Decoder instances, HTTP response bodies, and storage readers, thereby improving the application's stability and preventing resource exhaustion under various operational scenarios.

Highlights

  • Memory Leak Fix for Zstd Decoders: Implemented runtime.SetFinalizer on pooled zstd.Decoder instances to ensure their background goroutines are stopped and decoders are garbage collected, preventing linear memory growth caused by orphaned decoders.
  • HTTP Response Body Closure: Ensured non-200 HTTP response bodies are explicitly closed after draining them, which prevents HTTP connection pool exhaustion under error conditions.
  • Storage Reader Closure on Transaction Failure: Added logic to close the storage reader when a database transaction fails in getNarFromStore, addressing a file handle leak where readers (potentially wrapping zstd decoders) were silently dropped.
Changelog
  • pkg/cache/cache.go
    • Ensured the storage reader is closed when a database transaction fails in getNarFromStore.
  • pkg/cache/upstream/cache.go
    • Added explicit closing of HTTP response bodies for non-200 status codes to prevent connection exhaustion.
    • Replaced the custom zstdBodyCloser with the new generic helper.NewMultiReadCloser for handling multiple closers.
    • Removed the zstdBodyCloser type definition as it is now superseded by helper.MultiReadCloser.
  • pkg/helper/closer.go
    • Introduced a new MultiReadCloser type and NewMultiReadCloser function to allow wrapping an io.Reader with multiple io.Closer instances, ensuring all are closed when the wrapper is closed.
  • pkg/nar/reader.go
    • Imported the new pkg/helper package.
    • Refactored DecompressReader to use helper.NewMultiReadCloser to ensure that if the input reader is an io.ReadCloser, it is also closed when the decompression reader is closed.
  • pkg/nar/reader_test.go
    • Added a trackCloser helper struct to monitor if a reader's Close method is called.
    • Introduced TestDecompressReader_ClosesUnderlyingReader to verify that DecompressReader correctly closes the underlying io.ReadCloser for various compression types.
  • pkg/zstd/zstd.go
    • Imported the runtime package.
    • Added runtime.SetFinalizer to zstd.Decoder instances created in the readerPool to ensure they are properly closed and their background goroutines are stopped when the decoder becomes unreachable, preventing memory leaks.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩

@gemini-code-assist gemini-code-assist Bot 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.

Code Review

This pull request effectively resolves several memory leaks. Key fixes include adding a finalizer to pooled zstd.Decoder instances to prevent goroutine leaks, ensuring HTTP response bodies are closed for non-200 status codes to avoid connection exhaustion, and closing storage readers on transaction failures to prevent file handle leaks. The introduction of a generic helper.MultiReadCloser is a notable improvement, refactoring the code to robustly handle the closing of chained I/O resources in multiple locations. The changes are well-targeted, and the new tests provide good coverage for the fixes.

@codecov

codecov Bot commented Mar 11, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 5.04%. Comparing base (8055f46) to head (88db8d8).
⚠️ Report is 1 commits behind head on release-0.9.

Additional details and impacted files
@@             Coverage Diff             @@
##           release-0.9   #1062   +/-   ##
===========================================
  Coverage         5.04%   5.04%           
===========================================
  Files                6       6           
  Lines              436     436           
===========================================
  Hits                22      22           
  Misses             410     410           
  Partials             4       4           

☔ View full report in Codecov by Sentry.
📢 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.

@kalbasit
kalbasit merged commit 422d695 into release-0.9 Mar 11, 2026
13 checks passed
@kalbasit
kalbasit deleted the backport-1060-to-release-0.9 branch March 11, 2026 04:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working go Pull requests that update go code size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant