Repository navigation
fix(cache): no purge on upload-only narinfo reads - #1321
Conversation
A narinfo whose backing NAR is absent (a phantom) was destructively purged on every read, including on the /upload route. During a `nix copy --to .../upload`, that made the cache's path-validity answer non-monotonic: a path was present at the client's queryValidPaths phase, then purged before its reference was verified, so Lix's BinaryCacheStore::addToStore aborted with "the reference does not exist". Each retry re-seeded the phantom, causing purge churn. getNarInfoFromDatabase now skips purgeNarInfo when the request is upload-only (cache.IsUploadOnly), returning the existing ErrNarInfoPurged sentinel that GetNarInfo already maps to storage.ErrNotFound (HTTP 404) on that path. The client then re-uploads and the PUT overwrites the stale record. Root/substituter purge-and-re-fetch behavior is unchanged. Adds pkg/cache/upload_only_purge_internal_test.go covering the non-destructive read, monotonic repeated reads, the non-upload-only regression boundary, and post-404 repair via re-upload. Syncs the narinfo-purge-serving spec and archives the OpenSpec change. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
This change is part of the following stack: Change managed by git-spice. |
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (3)
✅ Files skipped from review due to trivial changes (1)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughSummary by CodeRabbit
WalkthroughThis PR makes upload-only ( ChangesUpload-only Read Path Purge Behavior
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 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 prevents destructive narinfo purges on the upload path when a backing NAR is missing, resolving a non-monotonic path-validity issue that causes nix copy to abort. By returning the ErrNarInfoPurged sentinel without purging when IsUploadOnly(ctx) is true, the upload path safely returns a 404, allowing the client to re-upload and repair the record. The changes include comprehensive specifications, design docs, and unit tests. The reviewer suggested a minor improvement in the test setup to use t.TempDir() instead of manually managing a temporary directory with os.MkdirTemp.
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: 2
🤖 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
`@openspec/changes/archive/2026-06-03-fix-upload-read-no-purge/specs/narinfo-purge-serving/spec.md`:
- Line 17: Replace the ambiguous phrase "purge guard does NOT fire" with a clear
statement that the purge guard condition is satisfied but the destructive action
is suppressed for upload-only requests, e.g. "the purge guard condition is met,
but purgeNarInfo is not invoked for upload-only requests"; ensure you reference
the guard/purgeNarInfo behavior so tests know the control flow reaches the guard
but the purge action is intentionally skipped.
In `@openspec/specs/narinfo-purge-serving/spec.md`:
- Line 60: Replace the ambiguous sentence "the purge guard does NOT fire and
`purgeNarInfo` is NOT called" with precise wording that states the guard
condition is reached but destructive purge is bypassed for upload-only reads,
e.g. "the purge guard condition is reached but, for upload-only reads,
destructive purging is bypassed and `purgeNarInfo` is not called" so readers
understand the difference between condition evaluation and action suppression.
🪄 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: e0159dd7-d5e1-4643-a81f-47803bcbc088
📒 Files selected for processing (8)
openspec/changes/archive/2026-06-03-fix-upload-read-no-purge/.openspec.yamlopenspec/changes/archive/2026-06-03-fix-upload-read-no-purge/design.mdopenspec/changes/archive/2026-06-03-fix-upload-read-no-purge/proposal.mdopenspec/changes/archive/2026-06-03-fix-upload-read-no-purge/specs/narinfo-purge-serving/spec.mdopenspec/changes/archive/2026-06-03-fix-upload-read-no-purge/tasks.mdopenspec/specs/narinfo-purge-serving/spec.mdpkg/cache/cache.gopkg/cache/upload_only_purge_internal_test.go
Address PR #1321 review feedback: - newUploadOnlyPurgeCacheNoSeed now uses t.TempDir() instead of os.MkdirTemp + manual t.Cleanup, dropping the now-unused os import (gemini-code-assist). - Reword the upload-only scenario's THEN clause from "the purge guard does NOT fire" to "the purge guard's missing-NAR condition is met, but purgeNarInfo is NOT called" so it is unambiguous that the guard condition is reached and only the destructive purge is suppressed (coderabbitai). Applied to both the live spec and the archived delta to keep them in sync. Co-Authored-By: Claude Opus 4.8 <[email protected]>
## Summary `nix copy --to https://<host>/upload <closure>` aborted with `cannot add 'X' to the binary cache because the reference 'Y' does not exist` even after the purge fix (#1321) and **even at a single replica** (so this is not a cross-replica/NFS issue). Root cause: the NAR `HEAD` handler (`getNar(false)`) returned `200` whenever `GetNarFileSize` reported `size > 0`, and `GetNarFileSize` reads only the `nar_file` **DB record** — it never checks that the NAR bytes exist. The reference-check `GET` path, by contrast, decides existence from **actual bytes** (`statNarInStore`). When a `nar_file` row exists without backing bytes (a phantom), nix's pre-upload `HEAD /upload/nar/<h>.nar.zst` returns `200`, so nix **skips uploading the NAR** (it uploads NAR-first, narinfo-last) and writes only the narinfo → phantom → a dependent path's reference-verification `GET` `404`s → Lix aborts. The mass `PutNar ... context canceled` errors are the *cascade* of nix tearing down in-flight uploads at abort, not the cause. ## Fix - Add `Cache.IsNarServable(ctx, narURL) (bool, error)` — tri-state servability from actual bytes (whole-file or chunks): `(true,nil)` present, `(false,nil)` confirmed absent, `(false,err)` ambiguous storage probe. - Gate the HEAD size-shortcut on it: emit `200` only when the NAR is actually servable; otherwise fall through to `GetNar`, which resolves upload-only to `404` (so the client re-uploads) and the substituter path to upstream recovery — consistent with `GET`. Scope is the HEAD existence check only. Write-path seed prevention (`storeInDatabase` creating byteless `nar_file` rows) is a deliberate follow-up; the HEAD fix alone breaks the failure chain. Follow-up to #1321. ## Test plan - [x] `task fmt` / `task lint` / `task test` pass (race detector on) - [x] `TestGetNar_HeadBytelessNarIs404` — byteless NAR HEAD → `404`, then `200` after the NAR is uploaded (fast path preserved). (Repurposed from the old `TestGetNar_HeadOptimization`, which had codified the buggy `200`.) - [x] `TestGetNar_HeadAmbiguousStorageIsNotFalse200` — ambiguous storage probe must not yield a false `200`. - [x] `IsNarServable` cache tests: whole-file present, byteless `(false,nil)`, ambiguous `(false,err)`. - [x] `nar-cache-miss-recovery` spec synced (HEAD/servability requirement added). --------- Co-authored-by: Claude Opus 4.8 <[email protected]>
## Summary Fixes the persistent `nix copy --to .../upload` abort: `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 called `purgeNarInfo` when a backing NAR looked absent. Because the DB is shared across replicas, that delete is globally visible instantly, flipping a verified reference `200 -> 404` mid-copy. #1321 made only the `/upload` path non-destructive. - **Non-destructive root reads** — `getNarInfoFromDatabase` and `getNarInfoFromStore` now 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. - **Refcount-aware deletion** — `narinfo`↔`nar_file` is M:N (many narinfos → one NAR). `purgeNarInfo` now deletes a `nar_file` record and its NAR bytes only when no other narinfo still links it (orphan-only, mirroring `RunLRU`). Previously a false-positive purge could delete a present, still-shared NAR and break sibling narinfos. - Removed the now-unused, refcount-unsafe `deleteNarFromStore` helper. - Modifies the `narinfo-purge-serving` spec (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 - [x] `task fmt`, `task lint` (0 issues), `task test` (full suite, `pkg/cache` under `-race`) all pass - [x] New tests: substituter DB/store reads non-destructive; nar_file record preserved; refcount-safe purge (shared survives / orphan reclaimed); upstream heal-in-place - [x] Updated the prior `NonUploadOnlyStillPurges` test to assert the new non-destructive behavior
Summary
nix copy --to https://<host>/upload <closure>aborted withcannot add 'X' to the binary cache because the reference 'Y' does not existwhenever the closure contained a phantom narinfo (DB row present, backing
NAR bytes absent).
The read-path purge guard destructively purged such narinfos on every read,
including on the
/uploadroute. That made the destination's path-validityanswer non-monotonic within a single
nix copy: a path was present at theclient's
queryValidPathsphase, then purged before its reference was verified,so Lix's
BinaryCacheStore::addToStorereference check aborted the whole copy.Each retry re-
PUTthe narinfo, which re-seeded the phantom and was purged again— observed churn of 244 purge events in one production run.
Fix
getNarInfoFromDatabasenow skipspurgeNarInfowhen the request is upload-only(
cache.IsUploadOnly), returning the existingErrNarInfoPurgedsentinel thatGetNarInfoalready maps tostorage.ErrNotFound(HTTP 404) on that path. Theclient receives 404 and re-uploads; the
PUToverwrites the stale record.Root/substituter purge-and-re-fetch behavior is unchanged.
Scope is the read path only — phantom seed prevention at write time
(
PutNarInfocreating anar_filerecord without bytes) is deliberately aseparate follow-up.
Test plan
task fmt/task lint/task testpass (race detector on)pkg/cache/upload_only_purge_internal_test.go:200)narinfo-purge-servingspec synced (added upload-only requirement; scoped the upstream-refetch requirement to non-upload-only)