Skip to content

fix(cache): NAR HEAD must verify bytes, not DB record - #1323

Merged
kalbasit merged 2 commits into
mainfrom
user/wnasreddine/fix-nar-head-verify-bytes
Jun 4, 2026
Merged

kalbasit merged 2 commits into
mainfrom
user/wnasreddine/fix-nar-head-verify-bytes

Conversation

@kalbasit

@kalbasit kalbasit commented Jun 4, 2026

Copy link
Copy Markdown
Owner

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 404s →
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

  • task fmt / task lint / task test pass (race detector on)
  • 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.)
  • TestGetNar_HeadAmbiguousStorageIsNotFalse200 — ambiguous storage probe
    must not yield a false 200.
  • IsNarServable cache tests: whole-file present, byteless (false,nil),
    ambiguous (false,err).
  • nar-cache-miss-recovery spec synced (HEAD/servability requirement added).

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]>
@kalbasit

kalbasit commented Jun 4, 2026 •

Copy link
Copy Markdown
Owner Author

This change is part of the following stack:

Change managed by git-spice.

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

coderabbitai Bot commented Jun 4, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 589f7777-ee7c-4f11-81d6-02dcafbe851a

📥 Commits

Reviewing files that changed from the base of the PR and between 3a1da4c and 3752af8.

📒 Files selected for processing (1)
  • pkg/server/server_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/server/server_test.go

📝 Walkthrough

Summary by CodeRabbit

  • New Features

    • Added a servability check to ensure NAR existence is validated before HEAD responses.
  • Bug Fixes

    • Fixed HEAD requests that returned 200 for NAR records without backing bytes; upload-only backing-less NARs now return 404.
    • Ensured HEAD behavior aligns with GET for accurate substituter/recovery semantics and ambiguous storage results.
  • Tests

    • Added tests covering servable, byteless, and ambiguous storage scenarios.
  • Documentation

    • Updated spec and design docs for NAR cache-miss recovery and HEAD behavior.

Walkthrough

This PR prevents phantom NAR HEAD 200 responses by adding Cache.IsNarServable (tri-state servability check) and using it in the server HEAD fast-path so HEAD returns 200 only when NAR bytes/chunks are verifiably servable.

Changes

NAR HEAD Servability Fix

Layer / File(s) Summary
Design & Specification
openspec/changes/archive/2026-06-03-fix-nar-head-verify-bytes/design.md, proposal.md, tasks.md, .openspec.yaml, openspec/changes/archive/.../specs/nar-cache-miss-recovery/spec.md, openspec/specs/nar-cache-miss-recovery/spec.md
Design and spec updates describing the phantom-NAR issue, tri-state servability semantics, proposed Cache.IsNarServable(ctx, narURL) (bool, error), and control-flow gating for the HEAD handler; includes proposal and task checklist.
Cache Servability Method
pkg/cache/cache.go, pkg/cache/nar_servable_internal_test.go
Adds exported Cache.IsNarServable which uses statNarInStore (with .nar.zst fallback) and HasNarInChunks to determine servability with tri-state error semantics; includes newServableTestCache and tests for whole-file present, byteless absent, and ambiguous-stat error.
Server HEAD Handler Integration
pkg/server/server.go, pkg/server/server_test.go
getNar HEAD path now requires both DB size and IsNarServable to return 200; otherwise it falls through to GetNar recovery. Tests updated/added to assert 404 for byteless DB records and to ensure ambiguous storage stats do not produce false 200s.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • kalbasit/ncps#1299: Introduced tri-state storage-stat semantics and related StatNar/ambiguous-vs-absent handling used by IsNarServable.

Poem

🐰 A phantom in the database dwells,
No bytes to back its promises—
Now IsNarServable rings the bells,
And HEAD returns what truth expresses.
No more false 200s on the shelves.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 62.50% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately and concisely summarizes the main fix: NAR HEAD requests must verify actual bytes exist rather than relying solely on the database record.
Description check ✅ Passed The description provides comprehensive context about the root cause, the fix, scope, and test plan, all directly related to the changeset's objectives.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

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

Comment thread pkg/server/server_test.go Resolved
Comment thread pkg/server/server_test.go Resolved

@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 (1)
pkg/server/server_test.go (1)

851-859: ⚡ Quick win

Also lock out a false 404 here.

This assertion only guards against a false 200. It still passes if upload-path HEAD regresses to 404, 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

📥 Commits

Reviewing files that changed from the base of the PR and between 54d48fe and 3a1da4c.

📒 Files selected for processing (10)
  • openspec/changes/archive/2026-06-03-fix-nar-head-verify-bytes/.openspec.yaml
  • openspec/changes/archive/2026-06-03-fix-nar-head-verify-bytes/design.md
  • openspec/changes/archive/2026-06-03-fix-nar-head-verify-bytes/proposal.md
  • openspec/changes/archive/2026-06-03-fix-nar-head-verify-bytes/specs/nar-cache-miss-recovery/spec.md
  • openspec/changes/archive/2026-06-03-fix-nar-head-verify-bytes/tasks.md
  • openspec/specs/nar-cache-miss-recovery/spec.md
  • pkg/cache/cache.go
  • pkg/cache/nar_servable_internal_test.go
  • pkg/server/server.go
  • pkg/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]>
@kalbasit
kalbasit enabled auto-merge (squash) June 4, 2026 03:11
@kalbasit
kalbasit merged commit ca03c2c into main Jun 4, 2026
34 checks passed
@kalbasit
kalbasit deleted the user/wnasreddine/fix-nar-head-verify-bytes branch June 4, 2026 03:17
kalbasit added a commit that referenced this pull request Jun 5, 2026
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.
kalbasit added a commit that referenced this pull request Jun 5, 2026
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).
kalbasit added a commit that referenced this pull request Jun 5, 2026
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).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working go Pull requests that update go code size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant