Skip to content

fix: resolve concurrent NAR streaming failures in distributed setup - #742

Merged
kalbasit merged 2 commits into
mainfrom
02-04-refactor_improve_test_code_quality_in_distributed_cache_tests
Feb 5, 2026
Merged

kalbasit merged 2 commits into
mainfrom
02-04-refactor_improve_test_code_quality_in_distributed_cache_tests

Conversation

@kalbasit

@kalbasit kalbasit commented Feb 5, 2026

Copy link
Copy Markdown
Owner

This commit fixes issue #660 where multiple ncps instances fail to serve
the same NAR file concurrently when one instance is still downloading it
from upstream.

Problem:
When running multiple ncps servers in HA mode with shared storage (S3)
and database (PostgreSQL), concurrent requests for the same NAR would
fail with "failed to acquire download lock" errors. Only the first
instance that acquired the lock could serve the NAR, while other
instances would return errors instead of waiting for the download to
complete and serving from shared storage.

This was a regression between release-0.8 and HEAD, breaking the ability
to horizontally scale ncps servers.

Solution:
Modified the download coordination logic to allow instances that fail to
acquire the download lock to poll the shared storage and serve the NAR
once another instance completes the download. This ensures all instances
can successfully serve concurrent requests even during initial download.

Testing:
Added testDistributedLargeNARConcurrentDownload test that simulates the
exact failure scenario: 3 cache instances requesting the same 12MB NAR
concurrently while one is downloading. The test verifies all instances
successfully serve the NAR without lock acquisition errors.

Also includes minor code quality improvements:

  • Switched to crypto/rand for secure test data generation
  • Improved error messages with wrapped static errors
  • Added testdata.GenerateEntry() helper for custom NAR generation

Part of #322

This commit fixes issue #660 where multiple ncps instances fail to serve
the same NAR file concurrently when one instance is still downloading it
from upstream.

Problem:
When running multiple ncps servers in HA mode with shared storage (S3)
and database (PostgreSQL), concurrent requests for the same NAR would
fail with "failed to acquire download lock" errors. Only the first
instance that acquired the lock could serve the NAR, while other
instances would return errors instead of waiting for the download to
complete and serving from shared storage.

This was a regression between release-0.8 and HEAD, breaking the ability
to horizontally scale ncps servers.

Solution:
Modified the download coordination logic to allow instances that fail to
acquire the download lock to poll the shared storage and serve the NAR
once another instance completes the download. This ensures all instances
can successfully serve concurrent requests even during initial download.

Testing:
Added testDistributedLargeNARConcurrentDownload test that simulates the
exact failure scenario: 3 cache instances requesting the same 12MB NAR
concurrently while one is downloading. The test verifies all instances
successfully serve the NAR without lock acquisition errors.

Also includes minor code quality improvements:
- Switched to crypto/rand for secure test data generation
- Improved error messages with wrapped static errors
- Added testdata.GenerateEntry() helper for custom NAR generation

Part of #322
@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 Feb 5, 2026

kalbasit commented Feb 5, 2026 •

Copy link
Copy Markdown
Owner Author

This stack of pull requests is managed by Graphite. Learn more about stacking.

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello @kalbasit, 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 a critical regression in distributed cache setups where concurrent requests for the same NAR file would fail if multiple instances attempted to download it simultaneously. The core change introduces a robust coordination mechanism, allowing instances that initially fail to acquire a download lock to intelligently wait and serve the NAR once another instance completes the download. This restores the ability to horizontally scale cache servers effectively, ensuring high availability and consistent service delivery even under heavy concurrent load.

Highlights

  • Concurrent NAR Streaming Fix: Resolved an issue where multiple cache instances in a distributed setup would fail to serve the same NAR file concurrently if one instance was still downloading it, by implementing a polling mechanism for instances that fail to acquire the download lock.
  • Decoupled Storage Reading: Introduced a new function, serveNarFromStorageViaPipe, which uses a pipe pattern and a detached context to decouple storage reading from the HTTP request lifecycle, preventing partial transfers upon client cancellation.
  • Enhanced Download Coordination: Modified the coordinateDownload logic to allow instances that cannot immediately acquire a download lock to poll shared storage, waiting for another instance to complete the download, thus ensuring all concurrent requests are eventually served.
  • New Distributed Test Case: Added testDistributedLargeNARConcurrentDownload to simulate and verify the fix for concurrent large NAR downloads across multiple cache instances.
  • Code Quality Improvements: Switched to crypto/rand for secure test data generation, improved error messages with wrapped static errors, and added a testdata.GenerateEntry() helper for custom NAR generation in tests.
Changelog
  • pkg/cache/cache.go
    • Refactored GetNar to utilize the new serveNarFromStorageViaPipe function for consistent NAR serving.
    • Added serveNarFromStorageViaPipe function to read NARs from storage using a detached context and io.Pipe to prevent premature cancellation of storage reads.
    • Updated prePullNar to check for NAR presence in both the main store and chunk store, improving detection of partially downloaded NARs.
    • Implemented a polling loop in coordinateDownload for instances that fail to acquire a download lock, allowing them to wait for other instances to complete the download.
  • pkg/cache/cache_distributed_test.go
    • Replaced math/rand/v2 with crypto/rand for generating cryptographically secure random data in tests.
    • Added testDistributedLargeNARConcurrentDownload to validate the fix for concurrent NAR streaming failures in a distributed environment.
    • Modified keyPrefix generation to use time.Now().UnixNano() for better test isolation.
    • Introduced testLargeNARConcurrentDownloadScenario to encapsulate the logic for testing concurrent large NAR downloads under various conditions.
  • testdata/generator.go
    • Added a new file generator.go to provide helper functions for generating custom test data.
    • Implemented GenerateEntry function to create testdata.Entry objects from raw NAR data, facilitating the creation of large or specific NARs for testing.
Activity
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 provides a solid fix for the concurrent NAR streaming failures in a distributed setup. The introduction of a polling mechanism in coordinateDownload for instances that fail to acquire a download lock is a robust solution. The new test case, testDistributedLargeNARConcurrentDownload, is comprehensive and effectively validates the fix. I also appreciate the refactoring to use serveNarFromStorageViaPipe, which improves the resilience of NAR serving. The code is well-written and the changes are clear. I have one suggestion to enhance configurability.

Comment thread pkg/cache/cache.go Resolved
@codecov

codecov Bot commented Feb 5, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 85.41%. Comparing base (3d6b873) to head (caf967c).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main     #742   +/-   ##
=======================================
  Coverage   85.41%   85.41%           
=======================================
  Files           2        2           
  Lines         480      480           
=======================================
  Hits          410      410           
  Misses         65       65           
  Partials        5        5           

☔ 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:XL This PR changes 500-999 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Feb 5, 2026
@kalbasit
kalbasit merged commit 178d094 into main Feb 5, 2026
15 checks passed
@kalbasit
kalbasit deleted the 02-04-refactor_improve_test_code_quality_in_distributed_cache_tests branch February 5, 2026 09:05
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:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant