Repository navigation
fix(cache): non-destructive narinfo purge on root path - #1326
Conversation
The substituter (root) narinfo read path purged a narinfo whenever its backing NAR looked absent. Production shares one Postgres across replicas, so that delete is globally visible instantly: a NAR that is transiently un-stat-able (NFS local backend) or LRU-evicted flips a reference 200->404 mid `nix copy`, aborting the client with "cannot add X because the reference Y does not exist". #1321 made only the /upload path non-destructive; the root path stayed destructive. Make both missing-NAR read paths (getNarInfoFromDatabase and getNarInfoFromStore) non-destructive: return the cache-miss sentinel and let the existing upstream re-fetch heal the record in place. The result is unchanged (200 on upstream hit, 404 on miss, never 500), but the destructive delete window that aborted concurrent uploads is gone. Also make purgeNarInfo refcount-aware: narinfo<->nar_file is M:N, so a purge driven by one narinfo must not delete a nar_file record or its NAR bytes still linked by another narinfo. Delete only when orphaned (zero NarInfoNarFile links), mirroring RunLRU. Drop the now-unused, refcount-unsafe deleteNarFromStore helper. Modifies the narinfo-purge-serving spec accordingly.
|
This change is part of the following stack:
Change managed by git-spice. |
📝 WalkthroughSummary by CodeRabbit
WalkthroughThis PR makes missing‑NAR reads non‑destructive by returning an internal sentinel and triggering upstream re‑fetch/healing rather than deleting records, and refactors purgeNarInfo to delete nar_file and NAR bytes only when a nar_file has zero remaining narinfo links. ChangesNon-Destructive Narinfo Purge with Refcount Safety
🎯 4 (Complex) | ⏱️ ~45 minutes Possibly Related PRs
Suggested Labels
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
Comment |
There was a problem hiding this comment.
Code Review
This pull request makes the substituter (non-upload) missing-NAR read path non-destructive by removing the purgeNarInfo call in getNarInfoFromDatabase and getNarInfoFromStore. Instead of deleting the records, it returns ErrNarInfoPurged so that GetNarInfo can re-fetch from upstream and heal the record in place. Additionally, purgeNarInfo is updated to be refcount-aware, ensuring that a nar_file record and its NAR bytes are only deleted if no other NarInfoNarFile links exist. New tests have been added to verify these behaviors, and existing tests and specifications have been updated accordingly. I have no feedback to provide as there are no review comments to assess.
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.
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 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 4581-4616: The current code re-looks-up a nar_file by
reconstructing keys from narURL (entnarfile.Query with Hash/Compression/Query)
after deleting the narinfo, which can mismatch normalized stored keys; instead,
before deleting the NarInfo row, capture the linked nar_file IDs from the
narinfo<->nar_file join rows (use the NarInfo's QueryNarFiles /
QueryNarInfoNarFiles edge or the join table that represents narinfo_nar_file)
within the same transaction, then for each captured nar_file ID run the orphan
check (tx.NarFile.Query().Where(entnarfile.IDEQ(id)).Exist or similar) and
delete only those exact NarFile rows if they have no remaining links; update the
code paths around tx.NarFile.Query(...).Only(ctx), hasLinks check, and
DeleteOne(nf).Exec(ctx) to operate on the fetched IDs instead of reconstructing
by narURL.
- Around line 4142-4151: The current early return when !hasNarInStore &&
!c.hasUpstreamJob(narURL.Hash) incorrectly treats legacy narinfos backed by
chunked CDC data as purged; before returning ErrNarInfoPurged, call the
chunk-backed checks (e.g., c.HasNarInChunks(narURL.Hash)) and, if your codebase
tracks in-progress CDC conversions, also check that in-progress record (e.g.,
c.isCDCInProgress or equivalent) to allow serving via GetNar; only return
ErrNarInfoPurged if no chunked NAR exists and no CDC in-progress record would
allow local serving.
- Around line 4631-4635: When narFileOrphaned is true the code only deletes the
logical "none" URL via c.narStore.DeleteNar(*narURL) leaving the actual zstd
object orphaned for rows with compression="none"; update the orphan cleanup in
the same block (where narFileOrphaned is checked) to also compute the zstd
variant URL for the same NAR and call c.narStore.DeleteNar on that zstd URL
(handling storage.ErrNotFound the same way) so both the logical none URL and the
physical .nar.zst object are removed; refer to narFileOrphaned, narURL, and
c.narStore.DeleteNar to locate where to add the extra delete.
🪄 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: 738da45c-520f-4aaf-a3d0-0c24c44a7908
📒 Files selected for processing (10)
openspec/changes/archive/2026-06-04-non-destructive-narinfo-purge/.openspec.yamlopenspec/changes/archive/2026-06-04-non-destructive-narinfo-purge/design.mdopenspec/changes/archive/2026-06-04-non-destructive-narinfo-purge/proposal.mdopenspec/changes/archive/2026-06-04-non-destructive-narinfo-purge/specs/narinfo-purge-serving/spec.mdopenspec/changes/archive/2026-06-04-non-destructive-narinfo-purge/tasks.mdopenspec/specs/narinfo-purge-serving/spec.mdpkg/cache/cache.gopkg/cache/nondestructive_narinfo_purge_internal_test.gopkg/cache/purge_serving_internal_test.gopkg/cache/upload_only_purge_internal_test.go
Addresses the CodeRabbit review on #1326: - getNarInfoFromStore now checks chunk storage (HasNarInChunks) before declaring a missing-NAR cache miss, mirroring getNarInfoFromDatabase. A CDC chunk-backed legacy narinfo is still locally servable via GetNar and must not be turned into a 404/cache-miss sentinel. - purgeNarInfo now identifies the nar_file(s) to reclaim via the actual narinfo_nar_files join links instead of reconstructing the key from narURL. storeInDatabase normalizes the URL before writing the nar_file row, so a reconstructed key can fail to match and leave the linked nar_file (and its bytes) un-reclaimed. - Reclaiming an orphaned compression=none nar_file now also deletes the physical .nar.zst object (where none bytes live), via a new deleteNarBytes helper; previously the real object was leaked.
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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 4018-4024: narFileVerified currently queries the DB with the raw
parsed narURL which can differ from the normalized key used by storeInDatabase,
causing misses for prefixed nix-serve URLs; update narFileVerified to normalize
the narURL using the same normalization logic used by storeInDatabase before
calling getNarFileFromDB so the lookup uses the canonical key (i.e., call the
existing normalization helper or inline the same normalization steps and then
pass the normalized URL into getNarFileFromDB).
🪄 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: fa8ce75d-f93f-4758-9c8f-2493372b38f6
📒 Files selected for processing (2)
pkg/cache/cache.gopkg/cache/nondestructive_narinfo_purge_internal_test.go
4c37e1f to
df94c19
Compare
There was a problem hiding this comment.
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)
4689-4700:⚠️ Potential issue | 🟠 Major | ⚡ Quick winCollapse the orphan check and delete into one statement.
This is still a TOCTOU window. Another transaction can link
nf.IDafterExistreturns false but beforeDeleteOneruns, and then this purge can cascade-delete a freshly re-linkednar_filebefore reclaiming its bytes.Suggested fix
- hasLinks, err := tx.NarFile.Query(). - Where(entnarfile.IDEQ(nf.ID), entnarfile.HasNarInfoNarFiles()). - Exist(ctx) - if err != nil { - return fmt.Errorf("error checking nar_file references: %w", err) - } - - if hasLinks { - continue - } - - if err := tx.NarFile.DeleteOne(nf).Exec(ctx); err != nil { + deleted, err := tx.NarFile.Delete(). + Where( + entnarfile.IDEQ(nf.ID), + entnarfile.Not(entnarfile.HasNarInfoNarFiles()), + ). + Exec(ctx) + if err != nil { return fmt.Errorf("error deleting the nar record: %w", err) } + if deleted == 0 { + continue + }🤖 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 4689 - 4700, Collapse the two-step existence check and deletion into a single conditional delete to avoid the TOCTOU race: replace the separate tx.NarFile.Query(...).Exist(...) + tx.NarFile.DeleteOne(nf).Exec(ctx) with a single tx.NarFile.Delete().Where(entnarfile.IDEQ(nf.ID), entnarfile.HasNarInfoNarFiles().Not()).Exec(ctx) (or the equivalent ent predicate negation), then inspect the returned result (rows affected) and error — if rows affected == 0 skip (someone linked it), otherwise treat as deleted; handle errors from Exec(ctx) normally.
♻️ Duplicate comments (1)
pkg/cache/cache.go (1)
4020-4026:⚠️ Potential issue | 🟠 Major | ⚡ Quick winNormalize the NAR URL before checking
bytes_stored_at.
storeInDatabasewritesnar_filerows under the normalized URL key, but this helper queries with the raw parsed narinfo URL. Prefixed nix-serve-style URLs will miss the existing row here, so the new upload-only path can still fall through toErrNarInfoPurged/404 even after a peer has already stored the NAR.Suggested fix
func (c *Cache) narFileBytesStored(ctx context.Context, narURL nar.URL) bool { + normalizedURL, err := narURL.Normalize() + if err == nil { + narURL = normalizedURL + } + nr, err := c.getNarFileFromDB(ctx, c.dbClient.Ent().NarFile, narURL) if err != nil { return false }🤖 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 4020 - 4026, narFileBytesStored is querying the DB with the raw nar.URL which can mismatch the normalized key used by storeInDatabase and miss existing rows; before calling getNarFileFromDB inside narFileBytesStored, normalize the incoming narURL to the same normalized form used when writing nar_file rows (i.e. call the project’s nar normalization helper used by storeInDatabase) and pass that normalized URL/key to getNarFileFromDB so prefixed nix-serve-style URLs correctly find existing records.
🤖 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.
Outside diff comments:
In `@pkg/cache/cache.go`:
- Around line 4689-4700: Collapse the two-step existence check and deletion into
a single conditional delete to avoid the TOCTOU race: replace the separate
tx.NarFile.Query(...).Exist(...) + tx.NarFile.DeleteOne(nf).Exec(ctx) with a
single tx.NarFile.Delete().Where(entnarfile.IDEQ(nf.ID),
entnarfile.HasNarInfoNarFiles().Not()).Exec(ctx) (or the equivalent ent
predicate negation), then inspect the returned result (rows affected) and error
— if rows affected == 0 skip (someone linked it), otherwise treat as deleted;
handle errors from Exec(ctx) normally.
---
Duplicate comments:
In `@pkg/cache/cache.go`:
- Around line 4020-4026: narFileBytesStored is querying the DB with the raw
nar.URL which can mismatch the normalized key used by storeInDatabase and miss
existing rows; before calling getNarFileFromDB inside narFileBytesStored,
normalize the incoming narURL to the same normalized form used when writing
nar_file rows (i.e. call the project’s nar normalization helper used by
storeInDatabase) and pass that normalized URL/key to getNarFileFromDB so
prefixed nix-serve-style URLs correctly find existing records.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 8ffff746-ffbb-4a76-81ff-8d52b889c60e
⛔ Files ignored due to path filters (3)
migrations/mysql/atlas.sumis excluded by!**/*.summigrations/postgres/atlas.sumis excluded by!**/*.summigrations/sqlite/atlas.sumis excluded by!**/*.sum
📒 Files selected for processing (14)
ent/migrate/schema.goent/mutation.goent/narfile.goent/narfile/narfile.goent/narfile/where.goent/narfile_create.goent/narfile_update.goent/runtime.goent/schema/nar_file.gomigrations/mysql/20260605021047_add_bytes_stored_at_to_nar_files.sqlmigrations/postgres/20260605021047_add_bytes_stored_at_to_nar_files.sqlmigrations/sqlite/20260605021047_add_bytes_stored_at_to_nar_files.sqlpkg/cache/cache.gopkg/cache/nondestructive_narinfo_purge_internal_test.go
✅ Files skipped from review due to trivial changes (9)
- migrations/mysql/20260605021047_add_bytes_stored_at_to_nar_files.sql
- migrations/sqlite/20260605021047_add_bytes_stored_at_to_nar_files.sql
- ent/narfile/narfile.go
- migrations/postgres/20260605021047_add_bytes_stored_at_to_nar_files.sql
- ent/migrate/schema.go
- ent/narfile/where.go
- ent/narfile.go
- ent/runtime.go
- ent/narfile_update.go
🚧 Files skipped from review as they are similar to previous changes (1)
- pkg/cache/nondestructive_narinfo_purge_internal_test.go
df94c19 to
fabde4f
Compare
## Summary Stacked on #1326. Fixes `nix copy --to .../upload` aborting with `cannot add X because the reference Y does not exist` against a production cache carrying CDC-era residue. Two parts: 1. **`bytes_stored_at` marker** — a dedicated `nar_file` column (distinct from fsck's `verified_at`) that `PutNar` sets once a NAR's bytes are durably written. On the `/upload` path the narinfo presence check trusts this shared-DB marker over the local filesystem stat, so a reference check on one replica no longer 404s a NAR a peer replica just uploaded but whose write this replica's NFS mount hasn't observed yet. A byte-less placeholder row (created by a narinfo PUT) is **not** trusted, so phantoms stay excluded. 2. **Compression-agnostic presence lookup** — the marker is matched by NAR hash (+query) regardless of compression. Prod has narinfos that advertise `url=nar/<hash>.nar` (Compression:none) while the NAR is stored only under xz; a compression-keyed lookup missed the xz row and wrongly 404'd. The hash identifies the NAR and the marker proves its bytes exist, so presence no longer depends on which compression the narinfo URL advertises. Why the `/upload` path only: the substituter (root) path must keep self-healing a genuinely missing NAR from upstream; trusting the marker there could mask a real eviction. ## Test plan - [x] `task fmt` / `task lint` / `task test` pass - [x] New internal tests: compression-agnostic presence, marker-trust on upload path, placeholder-not-trusted phantom guard - [ ] Deploy to prod and confirm `nix copy --to .../upload` of the previously-failing closures succeeds --------- Co-authored-by: Claude Opus 4.8 <[email protected]>
* 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
Summary
Fixes the persistent
nix copy --to .../uploadabort:cannot add 'X' because the reference 'Y' does not exist. Root cause confirmed live (2 non-sticky replicas, whole-file local backend on shared NFS, shared Postgres): the substituter/root narinfo read path still calledpurgeNarInfowhen a backing NAR looked absent. Because the DB is shared across replicas, that delete is globally visible instantly, flipping a verified reference200 -> 404mid-copy. #1321 made only the/uploadpath non-destructive.getNarInfoFromDatabaseandgetNarInfoFromStorenow return the cache-miss sentinel on a missing NAR instead of purging; the existing upstream re-fetch heals the record in place. Client-visible HTTP is unchanged (200 upstream-hit, 404 miss, never 500); the destructive cross-replica delete window is gone.narinfo↔nar_fileis M:N (many narinfos → one NAR).purgeNarInfonow deletes anar_filerecord and its NAR bytes only when no other narinfo still links it (orphan-only, mirroringRunLRU). Previously a false-positive purge could delete a present, still-shared NAR and break sibling narinfos.deleteNarFromStorehelper.narinfo-purge-servingspec (non-destructive substituter re-fetch + refcount-safe deletion).Not addressed here (tracked separately): the topology itself (whole-file local backend on shared NFS + non-sticky replicas). This change makes phantoms non-destructive and self-healing rather than copy-aborting; the durable fix is an object-store NAR backend.
Test plan
task fmt,task lint(0 issues),task test(full suite,pkg/cacheunder-race) all passNonUploadOnlyStillPurgestest to assert the new non-destructive behavior