Skip to content

fix: resolve memory leaks in several places - #1060

Merged
kalbasit merged 3 commits into
mainfrom
fix-resolve-memory-leaks-in-zstd
Mar 11, 2026
Merged

kalbasit merged 3 commits into
mainfrom
fix-resolve-memory-leaks-in-zstd

Conversation

@kalbasit

@kalbasit kalbasit commented Mar 11, 2026 •

Copy link
Copy Markdown
Owner

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.

…ions, and storage reader

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.
@kalbasit

kalbasit commented Mar 11, 2026 •

Copy link
Copy Markdown
Owner Author

@dosubot dosubot Bot added size:S This PR changes 10-29 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 implements crucial fixes to prevent several resource leaks identified through memory profiling. The changes ensure proper cleanup of zstd decoder instances, efficient management of HTTP connections by closing response bodies, and correct handling of storage readers during database transaction failures. These improvements are vital for maintaining application stability and preventing gradual memory and file descriptor exhaustion under load.

Highlights

  • Zstd Decoder Memory Leak: Addressed a memory leak in the zstd decoder pool by setting a runtime finalizer on pooled zstd.Decoder instances. This ensures background goroutines are stopped and decoders are garbage collected, preventing linear memory growth.
  • HTTP Connection Exhaustion: Resolved an issue where HTTP connections were not returned to the pool for non-200 HTTP responses. Non-OK response bodies are now explicitly closed after draining, preventing connection exhaustion under error conditions.
  • Storage Reader Leak: Fixed a resource leak where the storage reader was not closed when a database transaction failed in getNarFromStore, leading to leaked file handles.
Changelog
  • pkg/cache/cache.go
    • Closed the storage reader when the database transaction fails in getNarFromStore to prevent file handle leaks.
  • pkg/cache/upstream/cache.go
    • Ensured HTTP response bodies are closed for non-200 status codes after draining them, allowing connections to be returned to the pool.
  • pkg/zstd/zstd.go
    • Imported the runtime package.
    • Implemented runtime.SetFinalizer for zstd.Decoder instances in the readerPool to ensure their background goroutines are stopped and they are garbage collected when 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. ↩

@kalbasit kalbasit changed the title fix: resolve memory leaks in zstd decoder pool, upstream HTTP connections, and storage reader fix: resolve memory leaks in several places Mar 11, 2026

@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 aims to resolve three distinct resource leaks by adding a runtime.SetFinalizer to pooled zstd.Decoder instances, properly closing non-200 HTTP response bodies in the upstream cache logic, and ensuring a storage reader is closed in a previously unhandled error path. However, a critical vulnerability remains: the fix in pkg/cache/cache.go is incomplete as it fails to close the underlying reader when transparent decompression is used, still resulting in a resource leak. The other fixes in pkg/zstd/zstd.go and pkg/cache/upstream/cache.go appear correct and follow best practices.

Comment thread pkg/cache/cache.go Resolved
@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 (b396a10) to head (6754d21).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@          Coverage Diff          @@
##            main   #1060   +/-   ##
=====================================
  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.

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:S This PR changes 10-29 lines, ignoring generated files. labels Mar 11, 2026
@kalbasit

Copy link
Copy Markdown
Owner Author

/gemini review

@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 addresses three distinct and important resource leaks, significantly improving application stability. The fixes for zstd.Decoder goroutine leaks, unclosed HTTP response bodies, and unclosed storage readers are all well-implemented. The introduction of a generic MultiReadCloser is a good refactoring that improves code clarity and prevents future leaks. Overall, these are excellent changes.

Comment thread pkg/helper/closer.go Resolved
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
@kalbasit
kalbasit enabled auto-merge (squash) March 11, 2026 04:20
@kalbasit
kalbasit merged commit 3bb7739 into main Mar 11, 2026
16 checks passed
@kalbasit
kalbasit deleted the fix-resolve-memory-leaks-in-zstd branch March 11, 2026 04:31
kalbasit added a commit that referenced this pull request Mar 11, 2026
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

Copy link
Copy Markdown
Owner Author

Successfully created backport PR for release-0.9:

kalbasit added a commit that referenced this pull request Mar 11, 2026
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.

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backport release-0.9 Backport PR automatically 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