Skip to content

fix(cache): tolerate opaque (non-hash) upstream NAR URLs - #1331

Merged
kalbasit merged 6 commits into
kalbasit:mainfrom
bryandph:fix/opaque-nar-url
Jun 7, 2026
Merged

kalbasit merged 6 commits into
kalbasit:mainfrom
bryandph:fix/opaque-nar-url

Conversation

@bryandph

@bryandph bryandph commented Jun 5, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #1329.

When ncps proxies a narinfo whose URL: field is not hash-named (e.g. cachix now
serves nar/<uuidv4>.nar.zst), ParseURL rejected it as invalid nar hash and the
whole narinfo fetch aborted with HTTP 500. nix treats a 500 as a hard error
(worse than a 404, which would fall through to the next substituter), so this broke
substitution for every affected path once a fleet proxied a cachix-backed cache.

The Nix binary-cache protocol treats the narinfo URL: field as an opaque path
relative to the cache root — hash-naming (nar/<filehash>.nar.xz) is a
nix copy / nix-serve / cache.nixos.org convention, not part of the spec
(NixOS/nix#4464 tried to standardize it and
was merged then reverted). A pull-through proxy must tolerate it. This matches the
NarHash-as-storage-key approach @dosubot independently suggested on the issue.

Fix

  • pkg/nar — add ParseUpstreamURL(u, fallbackHash). Hash-named URLs behave
    exactly like ParseURL (unchanged fast path). Opaque URLs preserve the original
    path for the upstream GET (new unexported opaquePath, consulted only by
    JoinURL) and key local storage off fallbackHash — the narinfo NarHash,
    re-encoded as a bare 52-char nix32 digest (always a valid content hash, already
    available at that point). Adds IsOpaque / OpaquePath / WithOpaquePath.
  • ent + migrations — new nullable narinfos.upstream_url column that persists
    the opaque upstream path so the NAR can be re-fetched from upstream after the local
    copy is evicted (the stored narinfo URL becomes ncps's own hash-named URL and no
    longer encodes the opaque path). Additive / expand-safe; generated for sqlite +
    postgres + mysql.
  • pkg/cache — pullNarInfo parses via ParseUpstreamURL, re-serves the NAR
    under ncps's own hash-named URL (keyed on NarHash, preserving compression,
    FileHash and signatures), and persists the opaque path. lookupOriginalNarURL
    restores it for re-fetch; lookupPreferredUpstreamURL is made opaque-aware for CDC.

The hash-named fast path is byte-identical, so this is purely additive.

Test plan

  • task fmt, task lint (0 issues), task test, and task ent:check (codegen
    invariants + migration drift) all pass

  • TDD, RED → GREEN:

    • pkg/nar/url_test.go: opaque parse, NarHash keying, path preservation, and
      invalid-fallback / structurally-invalid error cases
    • pkg/cache/cache_test.go::TestGetNarInfoOpaqueUpstreamURL: end-to-end
      GetNarInfo with an opaque URL: → 200, re-served under a hash-named URL,
      upstream_url persisted; then evicts the local NAR bytes and re-fetches,
      deterministically exercising the opaque-restore path (the upstream serves the NAR
      only at the opaque path, so the re-fetch fails unless the persisted path is used)
  • Verified live in production against nix-community.cachix.org's opaque NAR
    (the issue's repro hash 9scxyz46ynlawfzm22s6vl603m9syz3w):

    Check Result
    Opaque narinfo through the proxy HTTP 200 (was 500)
    URL rewrite nar/d0c36585-…uuid….nar.zst → nar/13ishym4…narhash….nar.zst (keyed off NarHash)
    NAR fetch via the rewritten URL HTTP 200
    NAR integrity decompressed bytes' NarHash == narinfo NarHash ✅
    Signatures re-signed by the proxy + original nix-community.cachix.org-1 sig retained

AI Transparency

LLMs were used in the development of this PR.

@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. bug Something isn't working go Pull requests that update go code labels Jun 5, 2026
@coderabbitai

coderabbitai Bot commented Jun 5, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@kalbasit, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 22 minutes and 14 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 6d9d4c3a-1b49-4ce8-a9b1-bc4f830c31ec

📥 Commits

Reviewing files that changed from the base of the PR and between 4b863c4 and a19f73f.

📒 Files selected for processing (2)
  • pkg/cache/cache.go
  • pkg/cache/cache_internal_test.go
📝 Walkthrough

Walkthrough

This PR tolerates opaque (non-hash-named) upstream NAR URLs by adding a nullable upstream_url column, refactoring nar URL parsing to preserve opaque upstream paths, updating the cache pull pipeline to capture/persist/restore opaque paths while deriving storage keys from NarHash, and adding tests and migrations.

Changes

Opaque upstream URL support

Layer / File(s) Summary
Database schema and Ent ORM scaffolding
ent/schema/narinfo.go, ent/narinfo.go, ent/narinfo/narinfo.go, ent/narinfo/where.go, ent/narinfo_create.go, ent/narinfo_update.go, ent/mutation.go, ent/migrate/schema.go, ent/runtime.go, migrations/*
Adds upstream_url nullable column to narinfos table and generates full Ent ORM support: entity field, mutation API with setters/getters/clear operations, field predicates for querying, create/update/upsert builders, and database migrations for MySQL/Postgres/SQLite.
URL parsing for opaque upstream paths
pkg/nar/url.go, pkg/nar/url_test.go
Introduces internal opaquePath field and refactors ParseURL/ParseUpstreamURL to share a parseURLParts helper; ParseUpstreamURL validates the fallback hash and preserves non-hash-named upstream paths for later use; exports IsOpaque, OpaquePath, and WithOpaquePath helpers to query or restore opaque paths.
Cache pipeline integration for opaque URLs
pkg/cache/cache.go, pkg/cache/cache_test.go
Captures opaque upstream paths before URL normalization, rewrites narinfo URLs to hash-named form, derives storage keys from narinfo hash via narInfoStorageKey, and persists opaque paths to the database via setNarInfoUpstreamURL after storing narinfo; includes integration test verifying opaque path acceptance, persistence, and re-fetch after cache eviction.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Suggested labels

size:L

🐰 A coder seeks to parse a URL
Where hash-names aren't the start,
With opaque paths now stored,
And cache logic restored,
The rabbit hops through every part! 🌟

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The PR title accurately summarizes the main change: adding support for opaque (non-hash) upstream NAR URLs in the cache, which directly addresses the issue.
Description check ✅ Passed The PR description clearly explains the problem, root cause, and the comprehensive fix across multiple components (pkg/nar, ent, migrations, pkg/cache).
Linked Issues check ✅ Passed All coding objectives from issue #1329 are met: opaque URLs are now tolerated, NarHash is used as storage key, opaque paths are persisted and restored, hash-named fast path is unchanged, and tests validate the behavior.
Out of Scope Changes check ✅ Passed All changes are directly scoped to supporting opaque upstream NAR URLs. Schema migrations, code generation, parsing logic, cache integration, and tests are all necessary for the feature.
Docstring Coverage ✅ Passed Docstring coverage is 82.86% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@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 preserving and using opaque (non-hash-named) upstream NAR URLs (such as Cachix UUID NARs) by adding an upstream_url field to the NarInfo schema and database migrations. It updates URL parsing to fallback to the NarHash for local storage keys while preserving the original path for upstream fetches. Feedback suggests optimizing setNarInfoUpstreamURL by removing the unnecessary transaction block for a single atomic UPDATE statement.

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/cache/cache.go Resolved
@dosubot

dosubot Bot commented Jun 5, 2026

Copy link
Copy Markdown

This is a well-structured and thorough PR. The dual-key approach — using NarHash as the local storage key while persisting the opaque upstream path in a new upstream_url column — is a clean solution that aligns with the NarHash-as-storage-key suggestion from the issue discussion [1].

A few observations and questions:

  1. Graceful degradation on re-fetch: After local eviction, if the stored upstream_url becomes stale (e.g., upstream rotates UUIDs), does the re-fetch path return a clear error or does it fall through to another substituter? It would be good to confirm ncps doesn't return a 500 in that scenario either.

  2. Hash collision / duplicate key: If a hash-named upstream URL and an opaque upstream URL both resolve to the same NarHash (which is theoretically correct — same content), is the upstream_url column simply overwritten, or is there a conflict path?

  3. SQLite migration: The table-recreation approach for SQLite is the standard pattern for additive columns, but worth noting for deployments with large narinfos tables — the migration will briefly lock the table.

The test coverage looks solid, especially TestGetNarInfoOpaqueUpstreamURL exercising the eviction → re-fetch path with a mock upstream that only serves at the opaque path. The live verification against nix-community.cachix.org is a nice touch.

Overall this looks like a correct and well-tested fix for a real production issue. Nice work! 🎉

To reply, just mention @dosu.


Docs are dead. Just use Dosu.

Leave Feedback Ask Dosu about ncps Share Dosu with your team

When an upstream narinfo's URL: field is not hash-named (e.g. cachix
serves nar/<uuidv4>.nar.zst), ParseURL rejected it as an "invalid nar
hash" and the whole narinfo fetch aborted with HTTP 500. Nix treats a
500 as a hard error (worse than a 404), so this broke substitution for
every affected path once a fleet proxied a cachix-backed cache.

The Nix binary-cache protocol treats the narinfo URL: field as an opaque
path relative to the cache root, so a pull-through proxy must tolerate
non hash-named URLs rather than reject them. Decouple ncps's storage key
from the upstream URL string:

- pkg/nar: add ParseUpstreamURL(u, fallbackHash). Hash-named URLs behave
  exactly like ParseURL; opaque URLs preserve the original path for the
  upstream GET (new opaquePath field, used only by JoinURL) and key
  local storage off fallbackHash (the narinfo NarHash). Adds IsOpaque,
  OpaquePath and WithOpaquePath.
- ent: add nullable narinfos.upstream_url, persisting the opaque upstream
  path so the NAR can be re-fetched from upstream after local eviction.
- cache: pullNarInfo parses via ParseUpstreamURL (NarHash-derived key),
  re-serves the NAR under ncps's own hash-named URL, and persists the
  opaque path. lookupOriginalNarURL restores it for re-fetch;
  lookupPreferredUpstreamURL is made opaque-aware for CDC.

The hash-named fast path is unchanged, so this is purely additive.

Fixes bryandph/ncps#1

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@bryandph
bryandph force-pushed the fix/opaque-nar-url branch from 7f70307 to 21ed918 Compare June 5, 2026 04:59

@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: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
pkg/cache/cache.go (1)

3756-3778: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Make upstream_url persistence part of the narinfo write.

storeInDatabase commits the rewritten ncps-local narInfo.URL first, then setNarInfoUpstreamURL runs in a second transaction and its failure is only logged. For opaque upstreams, that leaves a durable narinfo row without the only path needed to re-fetch the NAR after local eviction, so future substitution can fall back to a URL the upstream does not actually serve.

🤖 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/cache/cache.go` around lines 3756 - 3778, The narinfo write currently
calls c.storeInDatabase(ctx, hash, narInfo) and then separately calls
c.setNarInfoUpstreamURL(ctx, hash, upstreamNarPath), so a failure persisting
upstreamNarPath can leave a durable narinfo without the opaque upstream; change
the implementation so persistence of upstreamNarPath is included in the same
database transaction as storeInDatabase (e.g., extend or modify storeInDatabase
to accept the upstreamNarPath or add a transactional helper that calls both
operations together), ensuring that when upstreamNarPath != "" the code writes
narInfo and the upstream URL atomically (use the existing c.storeInDatabase and
c.setNarInfoUpstreamURL symbols or a new helper to perform both in one
transaction and surface errors instead of only logging them).
🤖 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 `@migrations/sqlite/20260605033958_add_narinfo_upstream_url.sql`:
- Around line 31-43: The Down migration is dropping non-existent temporary
tables `new_nar_files` and `new_narinfos`; instead update the rollback to target
the live tables and indexes that were created/renamed in Up — drop or rename the
`nar_files` and `narinfos` tables (not `new_*`) and drop the indexes
`narfile_last_accessed_at`, `narfile_hash_compression_query`,
`narinfo_last_accessed_at`, and `narinfo_hash` against those live tables so the
Down properly reverses the Up operations in
migrations/sqlite/20260605033958_add_narinfo_upstream_url.sql.

---

Outside diff comments:
In `@pkg/cache/cache.go`:
- Around line 3756-3778: The narinfo write currently calls
c.storeInDatabase(ctx, hash, narInfo) and then separately calls
c.setNarInfoUpstreamURL(ctx, hash, upstreamNarPath), so a failure persisting
upstreamNarPath can leave a durable narinfo without the opaque upstream; change
the implementation so persistence of upstreamNarPath is included in the same
database transaction as storeInDatabase (e.g., extend or modify storeInDatabase
to accept the upstreamNarPath or add a transactional helper that calls both
operations together), ensuring that when upstreamNarPath != "" the code writes
narInfo and the upstream URL atomically (use the existing c.storeInDatabase and
c.setNarInfoUpstreamURL symbols or a new helper to perform both in one
transaction and surface errors instead of only logging them).
🪄 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: 24ba05c3-0f21-45a6-b386-e5a7945d29c2

📥 Commits

Reviewing files that changed from the base of the PR and between 5e98e71 and 7f70307.

⛔ Files ignored due to path filters (3)
  • migrations/mysql/atlas.sum is excluded by !**/*.sum
  • migrations/postgres/atlas.sum is excluded by !**/*.sum
  • migrations/sqlite/atlas.sum is excluded by !**/*.sum
📒 Files selected for processing (16)
  • ent/migrate/schema.go
  • ent/mutation.go
  • ent/narinfo.go
  • ent/narinfo/narinfo.go
  • ent/narinfo/where.go
  • ent/narinfo_create.go
  • ent/narinfo_update.go
  • ent/runtime.go
  • ent/schema/narinfo.go
  • migrations/mysql/20260605034000_add_narinfo_upstream_url.sql
  • migrations/postgres/20260605033958_add_narinfo_upstream_url.sql
  • migrations/sqlite/20260605033958_add_narinfo_upstream_url.sql
  • pkg/cache/cache.go
  • pkg/cache/cache_test.go
  • pkg/nar/url.go
  • pkg/nar/url_test.go

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

♻️ Duplicate comments (1)
migrations/sqlite/20260605033958_add_narinfo_upstream_url.sql (1)

31-43: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Fix invalid SQLite Down migration table targets.

The Up migration renames new_narinfos → narinfos (line 11) and new_nar_files → nar_files (line 23). Therefore, Down must drop the live tables (narinfos and nar_files), not the temporary new_* tables that no longer exist after Up completes. As written, the rollback will fail with "table does not exist" errors.

🔧 Suggested fix
 -- +goose Down
 -- reverse: create index "narfile_last_accessed_at" to table: "nar_files"
 DROP INDEX `narfile_last_accessed_at`;
 -- reverse: create index "narfile_hash_compression_query" to table: "nar_files"
 DROP INDEX `narfile_hash_compression_query`;
--- reverse: create "new_nar_files" table
-DROP TABLE `new_nar_files`;
+-- reverse: rename "new_nar_files" to "nar_files"
+DROP TABLE `nar_files`;
 -- reverse: create index "narinfo_last_accessed_at" to table: "narinfos"
 DROP INDEX `narinfo_last_accessed_at`;
 -- reverse: create index "narinfo_hash" to table: "narinfos"
 DROP INDEX `narinfo_hash`;
--- reverse: create "new_narinfos" table
-DROP TABLE `new_narinfos`;
+-- reverse: rename "new_narinfos" to "narinfos"
+DROP TABLE `narinfos`;

Based on learnings: "For goose-style SQL migrations in this repository, ensure every migration includes both a forward (-- +goose Up) section and a rollback (-- +goose Down) section … It does NOT permit omitting Down rollback blocks or removing rollback logic."

🤖 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 `@migrations/sqlite/20260605033958_add_narinfo_upstream_url.sql` around lines
31 - 43, The Down block is dropping the temporary tables
new_narinfos/new_nar_files which no longer exist after the Up rename; update the
rollback to target the live tables and their indexes instead: replace DROP TABLE
`new_narinfos` and DROP TABLE `new_nar_files` with DROP TABLE `narinfos` and
DROP TABLE `nar_files`, and ensure the DROP INDEX calls remove the corresponding
indexes on narinfos (`narinfo_last_accessed_at`, `narinfo_hash`) and nar_files
(`narfile_last_accessed_at`, `narfile_hash_compression_query`) so the Down
reverses the Up rename/creation correctly.
🤖 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.

Duplicate comments:
In `@migrations/sqlite/20260605033958_add_narinfo_upstream_url.sql`:
- Around line 31-43: The Down block is dropping the temporary tables
new_narinfos/new_nar_files which no longer exist after the Up rename; update the
rollback to target the live tables and their indexes instead: replace DROP TABLE
`new_narinfos` and DROP TABLE `new_nar_files` with DROP TABLE `narinfos` and
DROP TABLE `nar_files`, and ensure the DROP INDEX calls remove the corresponding
indexes on narinfos (`narinfo_last_accessed_at`, `narinfo_hash`) and nar_files
(`narfile_last_accessed_at`, `narfile_hash_compression_query`) so the Down
reverses the Up rename/creation correctly.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b14a9479-5d18-4008-b192-955f32668aa5

📥 Commits

Reviewing files that changed from the base of the PR and between 7f70307 and 21ed918.

⛔ Files ignored due to path filters (3)
  • migrations/mysql/atlas.sum is excluded by !**/*.sum
  • migrations/postgres/atlas.sum is excluded by !**/*.sum
  • migrations/sqlite/atlas.sum is excluded by !**/*.sum
📒 Files selected for processing (16)
  • ent/migrate/schema.go
  • ent/mutation.go
  • ent/narinfo.go
  • ent/narinfo/narinfo.go
  • ent/narinfo/where.go
  • ent/narinfo_create.go
  • ent/narinfo_update.go
  • ent/runtime.go
  • ent/schema/narinfo.go
  • migrations/mysql/20260605034000_add_narinfo_upstream_url.sql
  • migrations/postgres/20260605033958_add_narinfo_upstream_url.sql
  • migrations/sqlite/20260605033958_add_narinfo_upstream_url.sql
  • pkg/cache/cache.go
  • pkg/cache/cache_test.go
  • pkg/nar/url.go
  • pkg/nar/url_test.go
✅ Files skipped from review due to trivial changes (6)
  • migrations/mysql/20260605034000_add_narinfo_upstream_url.sql
  • ent/migrate/schema.go
  • ent/narinfo.go
  • ent/narinfo_update.go
  • ent/narinfo_create.go
  • ent/mutation.go
🚧 Files skipped from review as they are similar to previous changes (7)
  • ent/runtime.go
  • ent/schema/narinfo.go
  • ent/narinfo/narinfo.go
  • pkg/nar/url_test.go
  • pkg/nar/url.go
  • ent/narinfo/where.go
  • pkg/cache/cache.go

* origin/main:
  fix(cdc): heal orphaned mid-chunking NAR state via migration-lock liveness (kalbasit#1317)
  chore(deps): update codecov/codecov-action action to v7 (kalbasit#1340)
  feat(fsck): reclaim CDC chunked-NAR residue (grace-period mark-then-purge) (kalbasit#1335)
  fix(ent): stop sqlite phantom narinfos/nar_files rebuild (kalbasit#1339)
  chore: update flake.lock and run go mod tidy (kalbasit#1338)
  fix(deps): update module github.com/mattn/go-sqlite3 to v1.14.45 (kalbasit#1336)
  fix(cache,fsck): self-completing CDC drain (de-chunk never strands NARs) (kalbasit#1334)
  fix(cache,fsck): reconcile narinfo<->nar_file links (drain-mode unblock + prevention) (kalbasit#1333)
  fix(cache): close the CDC url=none/xz-NAR desync (prevention + repair) (kalbasit#1332)
  fix(cache): durable-bytes marker for /upload reference presence (kalbasit#1330)
  fix(cache): non-destructive narinfo purge on root path (kalbasit#1326)

# Conflicts:
#	migrations/mysql/atlas.sum
#	migrations/postgres/atlas.sum
#	migrations/sqlite/atlas.sum
#	pkg/cache/cache.go
Comment thread pkg/nar/url_test.go Dismissed
Comment thread pkg/nar/url_test.go Dismissed
Comment thread pkg/nar/url_test.go Dismissed
Comment thread pkg/nar/url_test.go Dismissed
The opaque-URL helpers (narInfoStorageKey, setNarInfoUpstreamURL) were
inserted between lookupOriginalNarURL's doc comment and its declaration,
orphaning the comment onto narInfoStorageKey and leaving
lookupOriginalNarURL undocumented. Move the doc comment back to its
function.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
pkg/cache/cache.go (2)

3924-3945: ⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Don't make upstream_url persistence best-effort.

By this point the narinfo row already contains ncps's rewritten hash-named URL. If this follow-up update fails, the request still returns success but loses the only path that can re-fetch an evicted opaque NAR later, which recreates the eviction-time failure this change is meant to fix. Persist upstream_url in the same transaction as storeInDatabase, or fail the pull so the row is retried atomically.

🤖 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/cache/cache.go` around lines 3924 - 3945, The follow-up persistence of
upstreamNarPath must not be best-effort: ensure the upstream URL is persisted in
the same atomic operation as storing the narinfo or return an error to trigger
retry. Modify the code path around c.storeInDatabase(ctx, hash, narInfo) so that
either storeInDatabase performs the upstream URL write internally (include
upstreamNarPath) or, if you keep setNarInfoUpstreamURL separate, treat any error
from c.setNarInfoUpstreamURL(ctx, hash, upstreamNarPath) as a hard failure
(propagate the error / call ds.setError and return an error) so the pull does
not succeed without the opaque upstream path; reference c.storeInDatabase,
setNarInfoUpstreamURL, upstreamNarPath and ds.setError when making the change.

1765-1787: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Delete the real .nar.zst object before clearing bytes_stored_at.

DeleteNar still removes only narURL, but Compression:none NARs are physically stored under the .nar.zst variant. Calling this with nar/<hash>.nar can therefore clear bytes_stored_at while the blob is still on disk, which both leaks the object and makes /upload presence checks lie. Reuse deleteNarBytes here before clearing the marker.

Suggested fix
-		if err := c.narStore.DeleteNar(ctx, narURL); err != nil {
+		if err := c.deleteNarBytes(ctx, narURL); err != nil {
 			return err
 		}
🤖 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/cache/cache.go` around lines 1765 - 1787, The code clears bytes_stored_at
after calling c.narStore.DeleteNar, but for Compression:none the on-disk blob
lives as the .nar.zst variant so bytes may be cleared while the blob remains;
call the existing deleteNarBytes helper to remove the actual stored bytes before
clearing the marker. Concretely, replace the current call to
c.narStore.DeleteNar (or add immediately after it and before computing clearURL)
with a call to c.deleteNarBytes(ctx, narURL) (or pass the normalized URL if
deleteNarBytes expects a normalized form), handle and return any error from
deleteNarBytes, then proceed to compute clearURL and update
ent.NarFile.ClearBytesStoredAt().Save(ctx) as before.
🤖 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 4268-4290: The liveness check in the nar_file servability path
(function returning c.cdcChunkerLive(...) at the end) disagrees with the
progressive streaming code: update streamProgressiveChunks to use the same lock
probe (c.cdcChunkerLive) or extract a shared helper used by both so they
evaluate the migration lock consistently; change the checks in
streamProgressiveChunks (the logic around the cdcChunkingLockTTL hard-fail) to
call c.cdcChunkerLive(ctx, hash) (or the new helper) instead of only relying on
chunk age so GetNar, streamProgressiveChunks and any callers (e.g., GetNar ->
getNarFromChunks) all treat a held migration lock as liveness and avoid aborting
long-running but live chunkers.
- Around line 8463-8466: The URL fallback using
entnarinfo.URLHasPrefix("nar/"+narURL.Hash+".") is too strict and misses
unlinked nix-serve-style narinfos like "nar/<narinfoHash>-<hash>.nar.xz"; update
the lookup to perform a hash-aware parse/normalize instead of a raw prefix
match: when scanning in checkAndFixNarInfosForNar (and the similar spots around
the other occurrences) extract/normalize candidate URLs (reusing
NormalizeChunkedNarInfoURL or implementing the same parse logic) to find the
embedded NarHash, then match against narURL.Hash (or use a new predicate that
checks the extracted hash) so MigrateChunksToNar / LinkedNarinfoNarHash will
correctly detect and normalize those unlinked narinfo URLs. Ensure the change
replaces the URLHasPrefix usage (and equivalent checks at the other locations)
with this hash-aware match.

---

Outside diff comments:
In `@pkg/cache/cache.go`:
- Around line 3924-3945: The follow-up persistence of upstreamNarPath must not
be best-effort: ensure the upstream URL is persisted in the same atomic
operation as storing the narinfo or return an error to trigger retry. Modify the
code path around c.storeInDatabase(ctx, hash, narInfo) so that either
storeInDatabase performs the upstream URL write internally (include
upstreamNarPath) or, if you keep setNarInfoUpstreamURL separate, treat any error
from c.setNarInfoUpstreamURL(ctx, hash, upstreamNarPath) as a hard failure
(propagate the error / call ds.setError and return an error) so the pull does
not succeed without the opaque upstream path; reference c.storeInDatabase,
setNarInfoUpstreamURL, upstreamNarPath and ds.setError when making the change.
- Around line 1765-1787: The code clears bytes_stored_at after calling
c.narStore.DeleteNar, but for Compression:none the on-disk blob lives as the
.nar.zst variant so bytes may be cleared while the blob remains; call the
existing deleteNarBytes helper to remove the actual stored bytes before clearing
the marker. Concretely, replace the current call to c.narStore.DeleteNar (or add
immediately after it and before computing clearURL) with a call to
c.deleteNarBytes(ctx, narURL) (or pass the normalized URL if deleteNarBytes
expects a normalized form), handle and return any error from deleteNarBytes,
then proceed to compute clearURL and update
ent.NarFile.ClearBytesStoredAt().Save(ctx) as before.
🪄 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: 053b71df-de0e-4e62-a675-fd8003812495

📥 Commits

Reviewing files that changed from the base of the PR and between 21ed918 and f81fb0b.

⛔ Files ignored due to path filters (3)
  • migrations/mysql/atlas.sum is excluded by !**/*.sum
  • migrations/postgres/atlas.sum is excluded by !**/*.sum
  • migrations/sqlite/atlas.sum is excluded by !**/*.sum
📒 Files selected for processing (8)
  • ent/migrate/schema.go
  • ent/mutation.go
  • ent/runtime.go
  • ent/schema/narinfo.go
  • migrations/mysql/20260607034027_add_narinfo_upstream_url.sql
  • migrations/postgres/20260607034027_add_narinfo_upstream_url.sql
  • migrations/sqlite/20260607034027_add_narinfo_upstream_url.sql
  • pkg/cache/cache.go
💤 Files with no reviewable changes (2)
  • migrations/postgres/20260607034027_add_narinfo_upstream_url.sql
  • migrations/mysql/20260607034027_add_narinfo_upstream_url.sql
✅ Files skipped from review due to trivial changes (3)
  • migrations/sqlite/20260607034027_add_narinfo_upstream_url.sql
  • ent/migrate/schema.go
  • ent/mutation.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • ent/runtime.go
  • ent/schema/narinfo.go

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

Caution

Inline review comments failed to post. This is likely due to GitHub's internal server error or limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
pkg/cache/cache.go (2)

3924-3945: ⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Don't make upstream_url persistence best-effort.

By this point the narinfo row already contains ncps's rewritten hash-named URL. If this follow-up update fails, the request still returns success but loses the only path that can re-fetch an evicted opaque NAR later, which recreates the eviction-time failure this change is meant to fix. Persist upstream_url in the same transaction as storeInDatabase, or fail the pull so the row is retried atomically.

🤖 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/cache/cache.go` around lines 3924 - 3945, The follow-up persistence of
upstreamNarPath must not be best-effort: ensure the upstream URL is persisted in
the same atomic operation as storing the narinfo or return an error to trigger
retry. Modify the code path around c.storeInDatabase(ctx, hash, narInfo) so that
either storeInDatabase performs the upstream URL write internally (include
upstreamNarPath) or, if you keep setNarInfoUpstreamURL separate, treat any error
from c.setNarInfoUpstreamURL(ctx, hash, upstreamNarPath) as a hard failure
(propagate the error / call ds.setError and return an error) so the pull does
not succeed without the opaque upstream path; reference c.storeInDatabase,
setNarInfoUpstreamURL, upstreamNarPath and ds.setError when making the change.

1765-1787: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Delete the real .nar.zst object before clearing bytes_stored_at.

DeleteNar still removes only narURL, but Compression:none NARs are physically stored under the .nar.zst variant. Calling this with nar/<hash>.nar can therefore clear bytes_stored_at while the blob is still on disk, which both leaks the object and makes /upload presence checks lie. Reuse deleteNarBytes here before clearing the marker.

Suggested fix
-		if err := c.narStore.DeleteNar(ctx, narURL); err != nil {
+		if err := c.deleteNarBytes(ctx, narURL); err != nil {
 			return err
 		}
🤖 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/cache/cache.go` around lines 1765 - 1787, The code clears bytes_stored_at
after calling c.narStore.DeleteNar, but for Compression:none the on-disk blob
lives as the .nar.zst variant so bytes may be cleared while the blob remains;
call the existing deleteNarBytes helper to remove the actual stored bytes before
clearing the marker. Concretely, replace the current call to
c.narStore.DeleteNar (or add immediately after it and before computing clearURL)
with a call to c.deleteNarBytes(ctx, narURL) (or pass the normalized URL if
deleteNarBytes expects a normalized form), handle and return any error from
deleteNarBytes, then proceed to compute clearURL and update
ent.NarFile.ClearBytesStoredAt().Save(ctx) as before.
🤖 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 4268-4290: The liveness check in the nar_file servability path
(function returning c.cdcChunkerLive(...) at the end) disagrees with the
progressive streaming code: update streamProgressiveChunks to use the same lock
probe (c.cdcChunkerLive) or extract a shared helper used by both so they
evaluate the migration lock consistently; change the checks in
streamProgressiveChunks (the logic around the cdcChunkingLockTTL hard-fail) to
call c.cdcChunkerLive(ctx, hash) (or the new helper) instead of only relying on
chunk age so GetNar, streamProgressiveChunks and any callers (e.g., GetNar ->
getNarFromChunks) all treat a held migration lock as liveness and avoid aborting
long-running but live chunkers.
- Around line 8463-8466: The URL fallback using
entnarinfo.URLHasPrefix("nar/"+narURL.Hash+".") is too strict and misses
unlinked nix-serve-style narinfos like "nar/<narinfoHash>-<hash>.nar.xz"; update
the lookup to perform a hash-aware parse/normalize instead of a raw prefix
match: when scanning in checkAndFixNarInfosForNar (and the similar spots around
the other occurrences) extract/normalize candidate URLs (reusing
NormalizeChunkedNarInfoURL or implementing the same parse logic) to find the
embedded NarHash, then match against narURL.Hash (or use a new predicate that
checks the extracted hash) so MigrateChunksToNar / LinkedNarinfoNarHash will
correctly detect and normalize those unlinked narinfo URLs. Ensure the change
replaces the URLHasPrefix usage (and equivalent checks at the other locations)
with this hash-aware match.

---

Outside diff comments:
In `@pkg/cache/cache.go`:
- Around line 3924-3945: The follow-up persistence of upstreamNarPath must not
be best-effort: ensure the upstream URL is persisted in the same atomic
operation as storing the narinfo or return an error to trigger retry. Modify the
code path around c.storeInDatabase(ctx, hash, narInfo) so that either
storeInDatabase performs the upstream URL write internally (include
upstreamNarPath) or, if you keep setNarInfoUpstreamURL separate, treat any error
from c.setNarInfoUpstreamURL(ctx, hash, upstreamNarPath) as a hard failure
(propagate the error / call ds.setError and return an error) so the pull does
not succeed without the opaque upstream path; reference c.storeInDatabase,
setNarInfoUpstreamURL, upstreamNarPath and ds.setError when making the change.
- Around line 1765-1787: The code clears bytes_stored_at after calling
c.narStore.DeleteNar, but for Compression:none the on-disk blob lives as the
.nar.zst variant so bytes may be cleared while the blob remains; call the
existing deleteNarBytes helper to remove the actual stored bytes before clearing
the marker. Concretely, replace the current call to c.narStore.DeleteNar (or add
immediately after it and before computing clearURL) with a call to
c.deleteNarBytes(ctx, narURL) (or pass the normalized URL if deleteNarBytes
expects a normalized form), handle and return any error from deleteNarBytes,
then proceed to compute clearURL and update
ent.NarFile.ClearBytesStoredAt().Save(ctx) as before.
🪄 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: 053b71df-de0e-4e62-a675-fd8003812495

📥 Commits

Reviewing files that changed from the base of the PR and between 21ed918 and f81fb0b.

⛔ Files ignored due to path filters (3)
  • migrations/mysql/atlas.sum is excluded by !**/*.sum
  • migrations/postgres/atlas.sum is excluded by !**/*.sum
  • migrations/sqlite/atlas.sum is excluded by !**/*.sum
📒 Files selected for processing (8)
  • ent/migrate/schema.go
  • ent/mutation.go
  • ent/runtime.go
  • ent/schema/narinfo.go
  • migrations/mysql/20260607034027_add_narinfo_upstream_url.sql
  • migrations/postgres/20260607034027_add_narinfo_upstream_url.sql
  • migrations/sqlite/20260607034027_add_narinfo_upstream_url.sql
  • pkg/cache/cache.go
💤 Files with no reviewable changes (2)
  • migrations/postgres/20260607034027_add_narinfo_upstream_url.sql
  • migrations/mysql/20260607034027_add_narinfo_upstream_url.sql
✅ Files skipped from review due to trivial changes (3)
  • migrations/sqlite/20260607034027_add_narinfo_upstream_url.sql
  • ent/migrate/schema.go
  • ent/mutation.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • ent/runtime.go
  • ent/schema/narinfo.go
🛑 Comments failed to post (2)
pkg/cache/cache.go (2)

4268-4290: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

The new lock-based liveness check is now out of sync with progressive streaming.

These lines treat a held migration lock as the source of truth for "the chunker is alive", but streamProgressiveChunks still hard-fails any in-progress chunk older than cdcChunkingLockTTL at Lines 8119-8123 and 8239-8242. A healthy chunk that runs longer than an hour will now be routed as servable here and then be aborted downstream as "stalled". Make the progressive path use the same lock probe (or a shared helper) so both paths agree on liveness.

🤖 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/cache/cache.go` around lines 4268 - 4290, The liveness check in the
nar_file servability path (function returning c.cdcChunkerLive(...) at the end)
disagrees with the progressive streaming code: update streamProgressiveChunks to
use the same lock probe (c.cdcChunkerLive) or extract a shared helper used by
both so they evaluate the migration lock consistently; change the checks in
streamProgressiveChunks (the logic around the cdcChunkingLockTTL hard-fail) to
call c.cdcChunkerLive(ctx, hash) (or the new helper) instead of only relying on
chunk age so GetNar, streamProgressiveChunks and any callers (e.g., GetNar ->
getNarFromChunks) all treat a held migration lock as liveness and avoid aborting
long-running but live chunkers.

8463-8466: ⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

The URL fallback misses unlinked nix-serve-style narinfos.

URLHasPrefix("nar/"+hash+".") only matches canonical nar/<hash>... URLs. An unlinked narinfo with a prefixed URL like nar/<narinfoHash>-<hash>.nar.xz will not match, so MigrateChunksToNar / NormalizeChunkedNarInfoURL can leave it unnormalized and LinkedNarinfoNarHash can wrongly conclude there's no NarHash to verify against. That's reachable here because checkAndFixNarInfosForNar already documents that CDC row replacement can drop the join row. This fallback needs a hash-aware parse/normalize step instead of a raw prefix match.

Also applies to: 8610-8613, 8682-8686

🤖 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/cache/cache.go` around lines 8463 - 8466, The URL fallback using
entnarinfo.URLHasPrefix("nar/"+narURL.Hash+".") is too strict and misses
unlinked nix-serve-style narinfos like "nar/<narinfoHash>-<hash>.nar.xz"; update
the lookup to perform a hash-aware parse/normalize instead of a raw prefix
match: when scanning in checkAndFixNarInfosForNar (and the similar spots around
the other occurrences) extract/normalize candidate URLs (reusing
NormalizeChunkedNarInfoURL or implementing the same parse logic) to find the
embedded NarHash, then match against narURL.Hash (or use a new predicate that
checks the extracted hash) so MigrateChunksToNar / LinkedNarinfoNarHash will
correctly detect and normalize those unlinked narinfo URLs. Ensure the change
replaces the URLHasPrefix usage (and equivalent checks at the other locations)
with this hash-aware match.

kalbasit and others added 2 commits June 6, 2026 20:51
Document the opaque (non-hash) upstream NAR URL support: proposal,
design, delta specs for upstream-fetch-resilience (new requirements) and
data-model (narinfos.upstream_url column), and the implementation task
breakdown.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Sync the delta specs into the main specs (upstream-fetch-resilience gains
the opaque-URL tolerance + eviction-survival requirements; data-model
gains the narinfos.upstream_url column) and archive the completed change
to clear the openspec-guard merge gate.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

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

🧹 Nitpick comments (2)
openspec/changes/archive/2026-06-06-tolerate-opaque-upstream-nar-urls/specs/data-model/spec.md (1)

5-5: ⚡ Quick win

Clarify upstream_url value semantics (full path vs pre-.nar stem).

This sentence is contradictory: it says “path before .nar” but the example includes .nar.zst. Please specify that upstream_url stores the full original opaque upstream path verbatim (including .nar[.<compression>]) to match implementation and avoid test ambiguity.

Suggested wording
- The `upstream_url` column MAY be `NULL` and SHALL hold the original opaque upstream NAR path (the path before `.nar`, e.g. `nar/<uuid>.nar.zst`) when the upstream narinfo URL was not hash-named; it stays `NULL` for conventional hash-named upstreams.
+ The `upstream_url` column MAY be `NULL` and SHALL hold the original opaque upstream NAR path verbatim (including `.nar` and any compression suffix, e.g. `nar/<uuid>.nar.zst`) when the upstream narinfo URL was not hash-named; it stays `NULL` for conventional hash-named upstreams.
🤖 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
`@openspec/changes/archive/2026-06-06-tolerate-opaque-upstream-nar-urls/specs/data-model/spec.md`
at line 5, The spec text for the narinfos table is ambiguous about what
upstream_url holds; update the description for the narinfos table so
upstream_url is explicitly defined as storing the full original opaque upstream
NAR path verbatim (including the .nar extension and any compression suffix like
.zst), not the pre-.nar stem; edit the sentence referencing the upstream_url
column in the narinfos table to state: "The upstream_url column MAY be NULL and,
when present for opaque (non-hash-named) upstreams, SHALL contain the full
original upstream NAR path verbatim (including .nar and any compression suffix,
e.g., nar/<uuid>.nar.zst)." Ensure this replaces the current contradictory
phrasing in the spec for upstream_url.
openspec/specs/data-model/spec.md (1)

77-77: ⚡ Quick win

Use unambiguous contract text for upstream_url in the active spec.

Same ambiguity as the archived spec: “before .nar” conflicts with the .nar.zst example. Tightening this to “full original opaque path verbatim” will keep the active contract precise and consistent with behavior.

Suggested wording
- The `upstream_url` column MAY be `NULL` and SHALL hold the original opaque upstream NAR path (the path before `.nar`, e.g. `nar/<uuid>.nar.zst`) when the upstream narinfo URL was not hash-named; it stays `NULL` for conventional hash-named upstreams.
+ The `upstream_url` column MAY be `NULL` and SHALL hold the original opaque upstream NAR path verbatim (including `.nar` and any compression suffix, e.g. `nar/<uuid>.nar.zst`) when the upstream narinfo URL was not hash-named; it stays `NULL` for conventional hash-named upstreams.
🤖 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 `@openspec/specs/data-model/spec.md` at line 77, Update the narinfos table
contract text to remove the ambiguous “before `.nar`” phrase and explicitly
state that the upstream_url column (in the narinfos table) MAY be NULL and, when
populated for non-hash-named upstreams, SHALL contain the full original opaque
upstream NAR path verbatim (including any extensions such as “.nar.zst” or other
suffixes); keep the rule that upstream_url stays NULL for conventional
hash-named upstreams and preserve the existing NULLability for url/compression
fields.
🤖 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.

Nitpick comments:
In
`@openspec/changes/archive/2026-06-06-tolerate-opaque-upstream-nar-urls/specs/data-model/spec.md`:
- Line 5: The spec text for the narinfos table is ambiguous about what
upstream_url holds; update the description for the narinfos table so
upstream_url is explicitly defined as storing the full original opaque upstream
NAR path verbatim (including the .nar extension and any compression suffix like
.zst), not the pre-.nar stem; edit the sentence referencing the upstream_url
column in the narinfos table to state: "The upstream_url column MAY be NULL and,
when present for opaque (non-hash-named) upstreams, SHALL contain the full
original upstream NAR path verbatim (including .nar and any compression suffix,
e.g., nar/<uuid>.nar.zst)." Ensure this replaces the current contradictory
phrasing in the spec for upstream_url.

In `@openspec/specs/data-model/spec.md`:
- Line 77: Update the narinfos table contract text to remove the ambiguous
“before `.nar`” phrase and explicitly state that the upstream_url column (in the
narinfos table) MAY be NULL and, when populated for non-hash-named upstreams,
SHALL contain the full original opaque upstream NAR path verbatim (including any
extensions such as “.nar.zst” or other suffixes); keep the rule that
upstream_url stays NULL for conventional hash-named upstreams and preserve the
existing NULLability for url/compression fields.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: afd9b033-c1fc-42a0-930f-a22cfedf8b0c

📥 Commits

Reviewing files that changed from the base of the PR and between f81fb0b and 4b863c4.

📒 Files selected for processing (9)
  • openspec/changes/archive/2026-06-06-tolerate-opaque-upstream-nar-urls/.openspec.yaml
  • openspec/changes/archive/2026-06-06-tolerate-opaque-upstream-nar-urls/design.md
  • openspec/changes/archive/2026-06-06-tolerate-opaque-upstream-nar-urls/proposal.md
  • openspec/changes/archive/2026-06-06-tolerate-opaque-upstream-nar-urls/specs/data-model/spec.md
  • openspec/changes/archive/2026-06-06-tolerate-opaque-upstream-nar-urls/specs/upstream-fetch-resilience/spec.md
  • openspec/changes/archive/2026-06-06-tolerate-opaque-upstream-nar-urls/tasks.md
  • openspec/specs/data-model/spec.md
  • openspec/specs/upstream-fetch-resilience/spec.md
  • pkg/cache/cache.go
✅ Files skipped from review due to trivial changes (2)
  • openspec/changes/archive/2026-06-06-tolerate-opaque-upstream-nar-urls/tasks.md
  • openspec/changes/archive/2026-06-06-tolerate-opaque-upstream-nar-urls/.openspec.yaml
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/cache/cache.go

Addresses CodeRabbit review (kalbasit#1331): the opaque upstream path was
persisted as a best-effort UPDATE after storeInDatabase succeeded. If
that follow-up write failed, the pull still returned success but the
narinfo row kept ncps's rewritten hash-named URL with no upstream_url —
losing the only path that can re-fetch an evicted opaque NAR and
recreating the exact eviction failure this change fixes.

Move the upstream_url write inside the storeInDatabase transaction so it
lands atomically with the narinfo row (all-or-nothing; a failure now
fails the pull and is retried). Drop the standalone setNarInfoUpstreamURL
helper. PutNarInfo (client uploads, no upstream) passes "".

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@kalbasit

kalbasit commented Jun 7, 2026

Copy link
Copy Markdown
Owner

Addressed the CodeRabbit "couldn't post inline" / outside-diff-range findings (commit a19f73f):

✅ Fixed — pkg/cache/cache.go "Don't make upstream_url persistence best-effort" (3924-3945).
Valid and load-bearing for this feature. The opaque path is now persisted inside the storeInDatabase transaction (all-or-nothing with the narinfo row) instead of as a best-effort follow-up UPDATE. A failure now fails the pull and is retried atomically, so the row can never end up with the rewritten hash-named URL but no upstream_url (which would lose the only re-fetch path for an evicted opaque NAR). Removed the standalone setNarInfoUpstreamURL helper; PutNarInfo (client uploads, no upstream) passes "". Covered by the existing TestGetNarInfoOpaqueUpstreamURL (persistence + eviction → re-fetch).

⏭️ Out of scope — DeleteNar clears bytes_stored_at without deleting the .nar.zst variant (1765-1787).
Verified the concern is plausible, but this is pre-existing main code, not touched by this PR (it's flagged "outside diff range" for exactly that reason). It concerns the Compression:none storage-variant / bytes_stored_at upload-presence subsystem, unrelated to opaque upstream URLs. Bundling it here would be scope creep across subsystems — better as its own issue/PR.

⏭️ Out of scope — URLHasPrefix("nar/"+hash+".") misses unlinked nix-serve-style narinfos (8463/8610/8682).
Also pre-existing main code (CDC MigrateChunksToNar / checkAndFixNarInfosForNar), not part of this diff. Note the match is already an Or(HasNarInfoNarFilesWith(...), URLHasPrefix(...)), and the inline comment documents the join-link branch as the primary path that "covers nix-serve-style prefixed URLs the URL prefix would miss" — so the gap is only the narrow unlinked-AND-prefixed case. A "Heavy lift" CDC concern that belongs in a separate change, not this opaque-URL fix.

No unresolved inline review threads remain on the PR.

@kalbasit
kalbasit enabled auto-merge (squash) June 7, 2026 04:02
@kalbasit
kalbasit merged commit 04cb40b into kalbasit:main Jun 7, 2026
30 checks passed
kalbasit added a commit that referenced this pull request Jun 7, 2026
## Summary

`Cache.DeleteNar` removed only the exact URL variant via
`narStore.DeleteNar`, but a `Compression:none` NAR's physical object is
stored under the `.nar.zst` variant. Deleting `nar/<H>.nar` therefore
left the real `.nar.zst` blob orphaned on disk while still clearing
`bytes_stored_at` — leaking storage and making the `/upload` presence
check lie (report absent while bytes remain). It also spuriously
errored, since the bare none object never exists.

This deletes the actually-stored variant (the `.nar.zst` variant for
`none`, mirroring `statNarInStore`) and tracks whether any variant was
present, returning `ErrNotFound` only when none was — preserving the
established "deleting an absent NAR errors" contract while no longer
orphaning the blob.

Surfaced by a CodeRabbit "outside diff range" finding on #1331; scoped
out of that PR as pre-existing, now fixed on its own.

Specs: adds a requirement to `upload-reference-presence` (deletion
removes the stored variant before clearing the marker; not-found only
when no variant was present).

## Test plan

- [x] `task fmt`, `task lint`, `task test` pass
- [x] New: `TestDeleteNar_RemovesNoneNarZstdVariant` (none NAR removes
the `.nar.zst` object)
- [x] New: `TestDeleteNar_AbsentNoneNarReturnsNotFound` (contract:
absent → `ErrNotFound`, marker kept)
- [x] Existing xz `DeleteNar` "absent → ErrNotFound" backend test still
passes

Co-authored-by: Claude Opus 4.8 <[email protected]>
kalbasit added a commit that referenced this pull request Jun 7, 2026
The de-chunk path located narinfos referencing a NAR with a raw
URLHasPrefix("nar/"+hash+".") fallback. That only matches canonical
nar/<hash>... URLs, so a nix-serve-style prefixed URL
(nar/<narinfoHash>-<hash>.nar.xz) on an unlinked narinfo (a known race
drops the join row) matched neither the join link nor the prefix. Such
narinfos were left unnormalized after de-chunk (later serve 404s) and
their NarHash could not be resolved (NAR purged / drain stuck).

Match hash-aware instead: narrow candidates in SQL via
URLContains(hash), then confirm in Go with ParseURL+Normalize so the
embedded hash (prefix stripped) equals the target. A shared
normalizedURLHash helper backs all three sites (LinkedNarinfoNarHash,
MigrateChunksToNar, NormalizeChunkedNarInfoURL); the join link stays the
primary match. Surfaced by CodeRabbit review on PR #1331.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
kalbasit added a commit that referenced this pull request Jun 7, 2026
## Summary

The de-chunk path located narinfos referencing a NAR with a raw
`URLHasPrefix("nar/"+hash+".")` fallback. That only matches canonical
`nar/<hash>...` URLs, so a nix-serve-style prefixed URL
(`nar/<narinfoHash>-<hash>.nar.xz`) on an **unlinked** narinfo (a known
race drops the `narinfo_nar_files` join row) matched neither the join
link nor the prefix. Such narinfos were left unnormalized after de-chunk
(a later serve 404s) and their verification `NarHash` could not be
resolved (NAR purged / drain stuck).

This matches **hash-aware** instead: narrow candidates in SQL via
`URLContains(hash)`, then confirm in Go with `ParseURL`+`Normalize` so
the embedded hash (narinfo-hash prefix stripped) equals the target. A
shared `normalizedURLHash` helper backs all three sites —
`LinkedNarinfoNarHash`, `MigrateChunksToNar`,
`NormalizeChunkedNarInfoURL` — and the join link stays the primary
match.

Surfaced by a CodeRabbit "outside diff range" finding on #1331; scoped
out of that PR as pre-existing, now fixed on its own.

Specs: updates two `chunks-to-nar-migration` requirements (URL-based
narinfo lookup is hash-aware, covering unlinked nix-serve-style prefixed
URLs).

## Test plan

- [x] `task fmt`, `task lint`, `task test` pass
- [x] New: `TestMigrateChunksToNar_DeChunksUnlinkedPrefixedNarinfoURL`
(de-chunk + normalize via hash-aware match)
- [x] New: `TestNormalizeChunkedNarInfoURL_MatchesUnlinkedPrefixedURL`
(first direct test of that entry point)
- [x] Existing canonical/unlinked/different-compression de-chunk tests
still pass (join-link path unchanged)

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
@bryandph
bryandph deleted the fix/opaque-nar-url branch June 7, 2026 19:31
kalbasit added a commit that referenced this pull request Jun 8, 2026
## Summary

The `[Unreleased]` section was populated in #1309 but skewed toward the
recent CDC-drain, in-flight-staging, and Ent-migration work, omitting
several user-facing features and fixes that also landed since v0.9.4.
This backfills the missing notable changes, each cross-referenced by PR.

**Added**
- `ncps fsck` command + Helm fsck CronJob (#975, #996, #998, #999,
#1000, #1004, #1006, #1176)
- Closure pinning HTTP endpoints `POST`/`DELETE /pin/{hash}.narinfo`,
`GET /pins` (#1108)
- pprof server via `--pprof-addr` (#1063)
- CDC lazy chunking as a feature + `--cache-cdc-lazy-cleanup-schedule` +
recovery cron (#1082, #1083, #1089, #1096)
- Helm: auto `GOMEMLIMIT` (#1061), configurable temp volume /
`volumeClaimTemplate` (#1074, #1077), SQLite `Recreate` strategy (#1012)
- Startup storage reporting + deprecated-narinfo warning (#959, #961)
- `docker-dev` image (#1097)

**Fixed**
- `store/tmp` no longer wiped on startup (#1313)
- `nix-hash` NAR verification (#1101)
- Prometheus counters primed at startup (#1337, #1343)
- 404 on un-reassemblable chunked NARs (#1319), purged narinfo no longer
500 (#1318), fail-fast tmp validation (#1086)
- Further CDC/cache reliability fixes (#1317, #1346, #1341, #1342,
#1331, #1347)

**Changed**
- CDC config now persisted in the DB config table (#971)

Dependency bumps, CI/test-only changes, and the internal Ent-conversion
PRs are intentionally excluded; the existing Ent-migration entry already
covers that work.

## Test plan

- [x] `nix fmt` reports no changes (docs-only edit)
- [x] CHANGELOG section structure intact
(Added/Fixed/Changed/Removed/Migration/CI)
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.

HTTP 500 "invalid nar hash" when an upstream serves an opaque (non-hash) NAR URL — e.g. cachix UUID-named NARs

3 participants