Repository navigation
fix(cache): NAR HEAD must verify bytes, not DB record - #1323
Conversation
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). That HEAD(record)/GET(bytes) asymmetry breaks `nix copy --to .../upload`: when a nar_file row exists without backing bytes (a phantom), nix's pre-upload HEAD of the NAR returns 200, so nix skips uploading the NAR (it uploads NAR-first, narinfo-last) and leaves a phantom; a dependent path's reference-verification GET then 404s and Lix aborts with "the reference does not exist". Reproduces at a single replica, so it is not a cross-replica/NFS issue. Add Cache.IsNarServable (tri-state: bytes present -> true; confirmed absent -> (false,nil); ambiguous storage error -> (false,err)) and 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. Repurposes the old TestGetNar_HeadOptimization (which asserted the buggy 200-for-byteless-NAR) into TestGetNar_HeadBytelessNarIs404 (404 then 200 after upload), adds an ambiguous-HEAD server test, and IsNarServable cache tests. Syncs the nar-cache-miss-recovery 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 (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughSummary by CodeRabbit
WalkthroughThis PR prevents phantom NAR HEAD 200 responses by adding ChangesNAR HEAD Servability Fix
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 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 ensures that NAR HEAD requests verify actual servability (backing bytes or chunks) rather than relying solely on database records, preventing clients from skipping uploads on phantom records. Feedback on the changes highlights resource leaks in the newly added test TestGetNar_HeadAmbiguousStorageIsNotFalse200, where both the database client and the test cache are not properly closed/cleaned up.
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.
🧹 Nitpick comments (1)
pkg/server/server_test.go (1)
851-859: ⚡ Quick winAlso lock out a false
404here.This assertion only guards against a false
200. It still passes if upload-pathHEADregresses to404, which would also violate the ambiguous-probe contract.🧪 Suggested tightening
assert.NotEqual(t, http.StatusOK, resp.StatusCode, "an ambiguous storage probe must not yield a 200 from the nar_file record alone") + assert.NotEqual(t, http.StatusNotFound, resp.StatusCode, + "an ambiguous storage probe must not be treated as a confirmed absence") resp.Body.Close()🤖 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/server/server_test.go` around lines 851 - 859, The test only prevents a false 200 from the upload-path HEAD probe but still allows a false 404; update the assertion after sending the HEAD request to ensure resp.StatusCode is neither http.StatusOK nor http.StatusNotFound (use the existing resp from ts.Client().Do(req) / resp.StatusCode and narURL for context), e.g. replace the single assert.NotEqual check with assertions that disallow both 200 and 404 so the ambiguous-probe contract is enforced.
🤖 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 `@pkg/server/server_test.go`:
- Around line 851-859: The test only prevents a false 200 from the upload-path
HEAD probe but still allows a false 404; update the assertion after sending the
HEAD request to ensure resp.StatusCode is neither http.StatusOK nor
http.StatusNotFound (use the existing resp from ts.Client().Do(req) /
resp.StatusCode and narURL for context), e.g. replace the single assert.NotEqual
check with assertions that disallow both 200 and 404 so the ambiguous-probe
contract is enforced.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: b565cede-fbc6-4d23-beed-fc0a0d8a4a35
📒 Files selected for processing (10)
openspec/changes/archive/2026-06-03-fix-nar-head-verify-bytes/.openspec.yamlopenspec/changes/archive/2026-06-03-fix-nar-head-verify-bytes/design.mdopenspec/changes/archive/2026-06-03-fix-nar-head-verify-bytes/proposal.mdopenspec/changes/archive/2026-06-03-fix-nar-head-verify-bytes/specs/nar-cache-miss-recovery/spec.mdopenspec/changes/archive/2026-06-03-fix-nar-head-verify-bytes/tasks.mdopenspec/specs/nar-cache-miss-recovery/spec.mdpkg/cache/cache.gopkg/cache/nar_servable_internal_test.gopkg/server/server.gopkg/server/server_test.go
Address PR #1323 review (gemini-code-assist): the new TestGetNar_HeadAmbiguousStorageIsNotFalse200 opened a database client and constructed a cache without releasing them, leaking file descriptors and the cache's background goroutines for the test's lifetime. Register t.Cleanup to close both, matching the cleanup the cache-package tests already use. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Multi-replica + shared-NFS regression: `nix copy --to .../upload` aborts with "reference X does not exist". A path's narinfo and NAR are PUT to different replicas; a concurrent reference check (GET /upload/Y.narinfo) on a replica whose local NFS view has not yet observed the peer's NAR write returns 404, aborting the copy. 0.10 made the /upload narinfo presence check depend on a per-replica os.Stat of the NAR (statNarInStore) to prevent phantoms (#1323), which introduced the NFS cross-replica false-negative. The nar_file table already has an (unused) verified_at column: set it in ensureNarFileRecord when PutNar durably writes the bytes. Because the database is strongly consistent across replicas, verified_at proves the NAR was stored by SOME replica even before the local filesystem catches up. On the upload path only, treat verified_at IS NOT NULL as present, trusting the shared DB over the local stat. Gated to IsUploadOnly so the substituter (root) read path keeps self-healing a genuinely missing NAR via upstream re-pull. A bare placeholder (narinfo PUT, verified_at NULL) is not trusted, so phantom prevention is preserved.
Multi-replica + shared-NFS regression: `nix copy --to .../upload` aborts with "reference X does not exist". A path's narinfo and NAR are PUT to different replicas; a concurrent reference check (GET /upload/Y.narinfo) on a replica whose local NFS view has not yet observed the peer's NAR write returns 404, aborting the copy. Confirmed: fails at replicas=2, works at replicas=1. 0.10 made the /upload narinfo presence check depend on a per-replica os.Stat of the NAR (statNarInStore) to prevent phantoms (#1323), which introduced the NFS cross-replica false-negative. Add a dedicated nar_file.bytes_stored_at column, set by PutNar when it durably writes the bytes (NULL on the narinfo-PUT placeholder). It is deliberately distinct from verified_at, which fsck owns as its integrity-check timestamp (PutNar does not verify the hash, so it must not masquerade as fsck-verified). Because the database is strongly consistent across replicas, bytes_stored_at proves the NAR was stored by SOME replica even before the local filesystem catches up. On the upload path only, treat bytes_stored_at IS NOT NULL as present, trusting the shared DB over the local stat. Gated to IsUploadOnly so the substituter (root) read path keeps self-healing a genuinely missing NAR via upstream re-pull. A bare placeholder (bytes_stored_at NULL) is not trusted, preserving phantom prevention. Migration: add_bytes_stored_at_to_nar_files (sqlite/postgres/mysql).
Multi-replica + shared-NFS regression: `nix copy --to .../upload` aborts with "reference X does not exist". A path's narinfo and NAR are PUT to different replicas; a concurrent reference check (GET /upload/Y.narinfo) on a replica whose local NFS view has not yet observed the peer's NAR write returns 404, aborting the copy. Confirmed: fails at replicas=2, works at replicas=1. 0.10 made the /upload narinfo presence check depend on a per-replica os.Stat of the NAR (statNarInStore) to prevent phantoms (#1323), which introduced the NFS cross-replica false-negative. Add a dedicated nar_file.bytes_stored_at column, set by PutNar when it durably writes the bytes (NULL on the narinfo-PUT placeholder). It is deliberately distinct from verified_at, which fsck owns as its integrity-check timestamp (PutNar does not verify the hash, so it must not masquerade as fsck-verified). Because the database is strongly consistent across replicas, bytes_stored_at proves the NAR was stored by SOME replica even before the local filesystem catches up. On the upload path only, treat bytes_stored_at IS NOT NULL as present, trusting the shared DB over the local stat. Gated to IsUploadOnly so the substituter (root) read path keeps self-healing a genuinely missing NAR via upstream re-pull. A bare placeholder (bytes_stored_at NULL) is not trusted, preserving phantom prevention. Migration: add_bytes_stored_at_to_nar_files (sqlite/postgres/mysql).
Summary
nix copy --to https://<host>/upload <closure>aborted withcannot add 'X' to the binary cache because the reference 'Y' does not existeven after the purge fix (#1321) and even at a single replica (so this is
not a cross-replica/NFS issue).
Root cause: the NAR
HEADhandler (getNar(false)) returned200wheneverGetNarFileSizereportedsize > 0, andGetNarFileSizereads only thenar_fileDB record — it never checks that the NAR bytes exist. Thereference-check
GETpath, by contrast, decides existence from actual bytes(
statNarInStore). When anar_filerow exists without backing bytes (aphantom), nix's pre-upload
HEAD /upload/nar/<h>.nar.zstreturns200, so nixskips uploading the NAR (it uploads NAR-first, narinfo-last) and writes only
the narinfo → phantom → a dependent path's reference-verification
GET404s →Lix aborts. The mass
PutNar ... context cancelederrors are the cascade ofnix tearing down in-flight uploads at abort, not the cause.
Fix
Cache.IsNarServable(ctx, narURL) (bool, error)— tri-state servabilityfrom actual bytes (whole-file or chunks):
(true,nil)present,(false,nil)confirmed absent,
(false,err)ambiguous storage probe.200only when the NAR is actuallyservable; otherwise fall through to
GetNar, which resolves upload-only to404(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
(
storeInDatabasecreating bytelessnar_filerows) is a deliberate follow-up;the HEAD fix alone breaks the failure chain. Follow-up to #1321.
Test plan
task fmt/task lint/task testpass (race detector on)TestGetNar_HeadBytelessNarIs404— byteless NAR HEAD →404, then200after the NAR is uploaded (fast path preserved). (Repurposed from the old
TestGetNar_HeadOptimization, which had codified the buggy200.)TestGetNar_HeadAmbiguousStorageIsNotFalse200— ambiguous storage probemust not yield a false
200.IsNarServablecache tests: whole-file present, byteless(false,nil),ambiguous
(false,err).nar-cache-miss-recoveryspec synced (HEAD/servability requirement added).