Skip to content

fix(cache): proxy snix-castore opaque nar URLs - #1427

Merged
kalbasit merged 2 commits into
mainfrom
fix-cache-proxy-snix-castore
Jul 1, 2026
Merged

kalbasit merged 2 commits into
mainfrom
fix-cache-proxy-snix-castore

Conversation

@kalbasit

@kalbasit kalbasit commented Jul 1, 2026

Copy link
Copy Markdown
Owner

Summary

Fixes intermittent HTTP 500 "invalid nar URL" when serving <hash>.narinfo
for store paths available on cache.snix.dev.

Root cause (confirmed against production logs): snix serves narinfos whose
URL: field is a snix-castore reference — nar/snix-castore/<blob>?narsize=N,
Compression: none, no .nar extension. ncps's nar.ParseUpstreamURL
required a .nar token, so it rejected these with ErrInvalidURL and the
narinfo request 500'd. It was intermittent because upstream selection races all
healthy upstreams (first responder wins); a retry that landed on
cache.nixos.org served a conventional URL and succeeded.

Fix: follow the Nix HTTP binary-cache protocol, where the narinfo URL: is
an opaque path relative to the cache root. This generalizes the existing opaque
(cachix UUID) handling to .nar-less URLs:

  • ParseUpstreamURL recovers a genuine cache-relative .nar-less path as
    Compression: none, keyed off the narinfo NarHash, preserving the full path
    and query for the upstream GET (snix returns 400 without ?narsize=N).
  • The initial pull now splits the opaque download URL (path + query) from
    ncps's own hash-named storage/serve key, so the upstream query never leaks
    into the nar_file key (which otherwise 404'd the NAR on a later read).
  • New OpaqueUpstreamRef / WithOpaqueUpstreamRef persist and restore the
    opaque path + query so an evicted NAR re-fetches correctly.
  • Strict ParseURL is unchanged — ncps still emits only hash-named URLs to
    clients. Conventional and cachix-style URLs are unaffected.

No config, schema, or migration changes.

Test plan

  • task fmt (0 changed), task lint (0 issues), task test (all green)
  • pkg/nar: parser unit tests (snix parse, query round-trip, strict
    ParseURL still rejects, invalid-fallback rejected)
  • pkg/cache: TestGetNarInfoSnixCastoreOpaqueURL — full pull → store →
    serve → evict → re-fetch; asserts ?narsize reaches the upstream GET and
    never leaks into ncps's storage key; existing cachix opaque test still
    passes

Upstreams such as cache.snix.dev serve narinfos whose URL field is a
content-addressed reference (nar/snix-castore/<blob>?narsize=N,
Compression: none, no .nar extension). ncps's ParseUpstreamURL required
a .nar token, so these were rejected with ErrInvalidURL and the
.narinfo request returned HTTP 500 "invalid nar URL" — intermittently,
because upstream selection races and a retry landing on a conventional
cache (cache.nixos.org) succeeded.

Per the Nix HTTP binary-cache protocol the narinfo URL is an opaque
path relative to the cache root, so generalize the existing opaque-URL
handling (cachix UUID NARs) to tolerate .nar-less URLs: recover a
genuine cache-relative path as Compression: none keyed off NarHash,
preserving the full path and query for the upstream GET (snix returns
400 without ?narsize=N). Split the download URL (opaque, with query)
from ncps's own hash-named storage/serve key so the upstream query
never leaks into the nar_file key. Persist the opaque path + query via
OpaqueUpstreamRef/WithOpaqueUpstreamRef so evicted NARs re-fetch
correctly. The strict ParseURL is unchanged; ncps still emits only
hash-named URLs to clients.
@kalbasit

kalbasit commented Jul 1, 2026

Copy link
Copy Markdown
Owner Author

This change is part of the following stack:

Change managed by git-spice.

@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 Jul 1, 2026
@coderabbitai

coderabbitai Bot commented Jul 1, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: e2271f68-8d1d-4899-aff1-7e14dfd3cbe3

📥 Commits

Reviewing files that changed from the base of the PR and between ec00aec and e7f29f8.

📒 Files selected for processing (3)
  • pkg/cache/cache.go
  • pkg/nar/url.go
  • pkg/nar/url_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • pkg/nar/url.go
  • pkg/nar/url_test.go

📝 Walkthrough

Summary by CodeRabbit

  • Bug Fixes

    • Fixed upstream nar fetches failing with opaque, .nar-less URL paths by proxying them without breaking the flow.
    • Preserved required upstream query parameters during upstream NAR requests.
    • Ensured NARs are still stored and served using ncps hash-based URLs, with compression treated as none for .nar-less opaque URLs.
  • Documentation

    • Documented the new upstream opaque URL handling in the changelog, developer guide, and specification.
  • Tests

    • Added coverage for snix-castore-style opaque upstream URLs, including query round-tripping and re-fetch after eviction.

Walkthrough

Adds .nar-less opaque upstream narinfo URL handling, preserves opaque path and query for refetch, stores by NarHash, serves hash-named NAR URLs with Compression: none, and updates cache behavior, tests, docs, and OpenSpec specs.

Changes

Opaque upstream URL support

Layer / File(s) Summary
Opaque URL parsing and persistence
pkg/nar/url.go, pkg/nar/url_test.go
ParseUpstreamURL recovers .nar-less opaque URLs, sets Compression: none, and stores the opaque path/query; new helpers serialize and restore opaque upstream refs, with tests for parsing, rejection, and round-tripping.
Cache pull, serve, and refetch wiring
pkg/cache/cache.go, pkg/cache/cache_test.go
Cache fetch and refetch paths use preserved opaque upstream refs, keep queries out of persisted client-visible URLs, and verify the full pull→evict→refetch flow.
Changelog and developer guide
CHANGELOG.md, docs/docs/Developer Guide/Architecture/Request Flow.md
Documents the new opaque URL handling behavior.
OpenSpec change and spec updates
openspec/changes/archive/2026-06-30-support-snix-castore-opaque-urls/*, openspec/specs/upstream-fetch-resilience/spec.md
Adds the archived change artifacts and updates the live spec with opaque URL requirements and scenarios.

Estimated code review effort: 3 (Moderate) | ~30 minutes

Possibly related PRs

  • kalbasit/ncps#1331: Shares the same opaque-upstream URL plumbing in pkg/nar/url.go and pkg/cache/cache.go.
  • kalbasit/ncps#1380: Touches the same Compression: none URL normalization path in pkg/cache/cache.go.

Suggested labels: merge-stack

Poem

I hopped through opaque paths so sly,
Kept queries safe as they went by,
NarHash led home, compression stayed none,
Now refetches work when caches are done,
A happy bunny thumps: fetch flow, you’re won! 🐇

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 62.50% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately summarizes the main change: proxying snix-castore opaque NAR URLs.
Description check ✅ Passed The description clearly matches the changeset and explains the bug, fix, and test plan.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

Comment @coderabbitai help to get the list of available commands.

Comment thread pkg/nar/url_test.go Fixed
Comment thread pkg/nar/url_test.go Fixed
Comment thread pkg/nar/url_test.go Fixed
Comment thread pkg/nar/url_test.go Fixed

@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 introduces support for proxying upstream narinfo URLs that lack a ".nar" extension (such as snix-castore opaque URLs), ensuring that their full path and query string are preserved for upstream GET requests while local storage keys off the NarHash. The reviewer highlighted a platform-dependency issue in pkg/nar/url.go where filepath.Base is used on a URL path, which would fail on Windows, and suggested using strings.LastIndex instead.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread pkg/nar/url.go Resolved
@coderabbitai

coderabbitai Bot commented Jul 1, 2026

Copy link
Copy Markdown

Caution

Failed to replace (edit) comment. This is likely due to insufficient permissions or the comment being deleted.

Error details
{"name":"HttpError","status":500,"request":{"method":"PATCH","url":"https://api.github.com/repos/kalbasit/ncps/issues/comments/4850358915","headers":{"accept":"application/vnd.github.v3+json","user-agent":"octokit.js/0.0.0-development octokit-core.js/7.0.6 Node.js/24","content-type":"application/json; charset=utf-8"},"body":{"body":"<!-- This is an auto-generated comment: summarize by coderabbit.ai -->\n<!-- review_stack_entry_start -->\n\n[![Review Change Stack](https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg)](https://app.coderabbit.ai/change-stack/kalbasit/ncps/pull/1427?utm_source=github_walkthrough&utm_medium=github&utm_campaign=change_stack)\n\n<!-- review_stack_entry_end -->\n<!-- This is an auto-generated comment: review in progress by coderabbit.ai -->\n\n> [!NOTE]\n> Currently processing new changes in this PR. This may take a few minutes, please wait...\n> \n> <details>\n> <summary>⚙️ Run configuration</summary>\n> \n> **Configuration used**: Organization UI\n> \n> **Review profile**: CHILL\n> \n> **Plan**: Pro\n> \n> **Run ID**: `9dfeb77b-0866-4345-9d36-27841d4bac4e`\n> \n> </details>\n> \n> <details>\n> <summary>📥 Commits</summary>\n> \n> Reviewing files that changed from the base of the PR and between 2ba897bb8c592654fedca2bf2db074376fefabff and ec00aecb27b290d61eedaace7f5c6133c44a4799.\n> \n> </details>\n> \n> <details>\n> <summary>📒 Files selected for processing (12)</summary>\n> \n> * `CHANGELOG.md`\n> * `docs/docs/Developer Guide/Architecture/Request Flow.md`\n> * `openspec/changes/archive/2026-06-30-support-snix-castore-opaque-urls/.openspec.yaml`\n> * `openspec/changes/archive/2026-06-30-support-snix-castore-opaque-urls/design.md`\n> * `openspec/changes/archive/2026-06-30-support-snix-castore-opaque-urls/proposal.md`\n> * `openspec/changes/archive/2026-06-30-support-snix-castore-opaque-urls/specs/upstream-fetch-resilience/spec.md`\n> * `openspec/changes/archive/2026-06-30-support-snix-castore-opaque-urls/tasks.md`\n> * `openspec/specs/upstream-fetch-resilience/spec.md`\n> * `pkg/cache/cache.go`\n> * `pkg/cache/cache_test.go`\n> * `pkg/nar/url.go`\n> * `pkg/nar/url_test.go`\n> \n> </details>\n> \n> ```ascii\n>  ____________________________________________________________________\n> < Love the minimalism. Unfortunately the feature was also minimized. >\n>  --------------------------------------------------------------------\n>   \\\n>    \\   \\\n>         \\ /\\\n>         ( )\n>       .( o ).\n> ```\n\n<!-- end of auto-generated comment: review in progress by coderabbit.ai -->\n\n<!-- finishing_touch_checkbox_start -->\n\n<details>\n<summary>✨ Finishing Touches</summary>\n\n<details>\n<summary>📝 Generate docstrings</summary>\n\n- [ ] <!-- {\"checkboxId\": \"7962f53c-55bc-4827-bfbf-6a18da830691\"} --> Create stacked PR\n- [ ] <!-- {\"checkboxId\": \"3e1879ae-f29b-4d0d-8e06-d12b7ba33d98\"} --> Commit on current branch\n\n</details>\n\n</details>\n\n<!-- finishing_touch_checkbox_end -->\n<!-- tips_start -->\n\n---\n\n\n\n\n<sub>Comment `@coderabbitai help` to get the list of available commands.</sub>\n\n<!-- tips_end -->"},"request":{"retryCount":3,"signal":{},"retries":3,"retryAfter":16}}}

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
pkg/nar/url_test.go (1)

254-276: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Add a round-trip case for encoded/order-sensitive opaque queries.

The current round-trip only covers ?narsize=N; add one case with escaped characters or multiple ordered params so the persistence contract catches query re-encoding regressions.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/nar/url_test.go` around lines 254 - 276, The existing round-trip test in
nar.ParseUpstreamURL/WithOpaqueUpstreamRef only covers a simple narsize query,
so add another case that uses an opaque upstream ref with escaped characters or
multiple ordered query parameters. Keep the same round-trip assertions on
OpaqueUpstreamRef, ParseURL, and JoinURL, but verify the exact original query
string is preserved without re-encoding or reordering.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@pkg/cache/cache.go`:
- Around line 4343-4346: The URL normalization in the narinfo handling code is
stripping query parameters too broadly for CompressionTypeNone/eager-CDC cases.
Update the logic around the nar.URL construction in the affected branches so
queries are removed only when the upstream URL is opaque, and preserved for
non-opaque hash-named NAR URLs. Make the same adjustment in both matching paths
in the narinfo serialization flow so the advertised URL stays consistent with
the stored/downloadable key.

In `@pkg/nar/url.go`:
- Around line 183-188: The opaque upstream ref parsing currently discards the
original raw query string by only returning parsed url.Values from the URL
helper, which breaks verbatim reconstruction in OpaqueUpstreamRef and
round-tripping in WithOpaqueUpstreamRef. Update the URL parsing/persistence flow
to carry the raw query alongside the decoded values, and make OpaqueUpstreamRef
use that preserved raw form when rebuilding the ref. Ensure
WithOpaqueUpstreamRef stores and reuses the raw query for refetch/persistence,
and add a regression test covering escaped characters and reordered parameters.

---

Nitpick comments:
In `@pkg/nar/url_test.go`:
- Around line 254-276: The existing round-trip test in
nar.ParseUpstreamURL/WithOpaqueUpstreamRef only covers a simple narsize query,
so add another case that uses an opaque upstream ref with escaped characters or
multiple ordered query parameters. Keep the same round-trip assertions on
OpaqueUpstreamRef, ParseURL, and JoinURL, but verify the exact original query
string is preserved without re-encoding or reordering.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 9dfeb77b-0866-4345-9d36-27841d4bac4e

📥 Commits

Reviewing files that changed from the base of the PR and between 2ba897b and ec00aec.

📒 Files selected for processing (12)
  • CHANGELOG.md
  • docs/docs/Developer Guide/Architecture/Request Flow.md
  • openspec/changes/archive/2026-06-30-support-snix-castore-opaque-urls/.openspec.yaml
  • openspec/changes/archive/2026-06-30-support-snix-castore-opaque-urls/design.md
  • openspec/changes/archive/2026-06-30-support-snix-castore-opaque-urls/proposal.md
  • openspec/changes/archive/2026-06-30-support-snix-castore-opaque-urls/specs/upstream-fetch-resilience/spec.md
  • openspec/changes/archive/2026-06-30-support-snix-castore-opaque-urls/tasks.md
  • openspec/specs/upstream-fetch-resilience/spec.md
  • pkg/cache/cache.go
  • pkg/cache/cache_test.go
  • pkg/nar/url.go
  • pkg/nar/url_test.go

Comment thread pkg/cache/cache.go Resolved
Comment thread pkg/nar/url.go Resolved
- url.go: extract the opaque filename with strings.LastIndex instead of
  filepath.Base, which is platform-dependent (treats "\\" as a
  separator on Windows); pathPart is guaranteed to contain "/".
  (PR #1427, gemini thread PRRT_kwDONV6tZs6NeOGy)
- cache.go: strip the upstream query from ncps's own hash-named serve
  URL only for OPAQUE upstream URLs; preserve queries on conventional
  hash-named none/eager-CDC URLs as before, so the advertised URL does
  not diverge from the stored key.
  (PR #1427, coderabbit thread PRRT_kwDONV6tZs6NeRMp)
- url_test.go: use https example URLs in the new tests to avoid DevSkim
  no-TLS findings (code-scanning 381-384).
@kalbasit

kalbasit commented Jul 1, 2026

Copy link
Copy Markdown
Owner Author

Re: preserving the raw opaque query string (thread on pkg/nar/url.go) — resolving as a documented non-change:

  • The only known .nar-less opaque upstream (snix-castore) uses a single ?narsize=<digits> parameter, which round-trips through url.Values.Encode() byte-for-byte (asserted exactly in TestParseUpstreamURL / the opaque-ref round-trip test).
  • ncps already handles all NAR-URL queries via url.Values end-to-end — parseURLParts decodes with url.ParseQuery and JoinURL re-emits with Query.Encode() for conventional URLs too. Adding a raw-query field only for opaque URLs would be inconsistent with that and a non-trivial change to the shared URL type / JoinURL.

So opaque re-fetch is no less faithful than the shipped behavior for every other URL, and correct for the real upstream. If an order-/encoding-sensitive multi-param opaque upstream ever appears, carrying a raw query through the URL type would be the right follow-up.

@kalbasit
kalbasit enabled auto-merge (squash) July 1, 2026 05:18
@github-actions

github-actions Bot commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

@kalbasit
kalbasit merged commit 2880f19 into main Jul 1, 2026
40 checks passed
@kalbasit
kalbasit deleted the fix-cache-proxy-snix-castore branch July 1, 2026 05:47
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.

2 participants