Skip to content

fix(cache): no purge on upload-only narinfo reads - #1321

Merged
kalbasit merged 2 commits into
mainfrom
user/wnasreddine/fix-upload-read-no-purge
Jun 4, 2026
Merged

kalbasit merged 2 commits into
mainfrom
user/wnasreddine/fix-upload-read-no-purge

Conversation

@kalbasit

@kalbasit kalbasit commented Jun 3, 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
whenever 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 /upload route. That made the destination's path-validity
answer non-monotonic within a single nix copy: a path was present at the
client's queryValidPaths phase, then purged before its reference was verified,
so Lix's BinaryCacheStore::addToStore reference check aborted the whole copy.
Each retry re-PUT the narinfo, which re-seeded the phantom and was purged again
— observed churn of 244 purge events in one production run.

Fix

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 receives 404 and re-uploads; the PUT overwrites the stale record.
Root/substituter purge-and-re-fetch behavior is unchanged.

Scope is the read path only — phantom seed prevention at write time
(PutNarInfo creating a nar_file record without bytes) is deliberately a
separate follow-up.

Test plan

  • task fmt / task lint / task test pass (race detector on)
  • New pkg/cache/upload_only_purge_internal_test.go:
    • upload-only read → 404, narinfo row not purged
    • repeated upload-only reads → deterministic 404, non-mutating (monotonic)
    • non-upload-only read → still purges (regression boundary)
    • post-404 re-upload repairs the record (served 200)
  • narinfo-purge-serving spec synced (added upload-only requirement; scoped the upstream-refetch requirement to non-upload-only)

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

kalbasit commented Jun 3, 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 labels Jun 3, 2026
@coderabbitai

coderabbitai Bot commented Jun 3, 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: 5e6605c3-cf8e-44a9-8d4a-a76b9ba98810

📥 Commits

Reviewing files that changed from the base of the PR and between 8fc1a1e and 3117244.

📒 Files selected for processing (3)
  • openspec/changes/archive/2026-06-03-fix-upload-read-no-purge/specs/narinfo-purge-serving/spec.md
  • openspec/specs/narinfo-purge-serving/spec.md
  • pkg/cache/upload_only_purge_internal_test.go
✅ Files skipped from review due to trivial changes (1)
  • openspec/changes/archive/2026-06-03-fix-upload-read-no-purge/specs/narinfo-purge-serving/spec.md
🚧 Files skipped from review as they are similar to previous changes (2)
  • pkg/cache/upload_only_purge_internal_test.go
  • openspec/specs/narinfo-purge-serving/spec.md

📝 Walkthrough

Summary by CodeRabbit

  • Bug Fixes

    • Upload-only cache reads are now non-destructive: missing backing data returns HTTP 404 instead of deleting stale records, allowing clients to repair via re-upload and avoiding failures during copy operations.
  • Documentation

    • Added design, proposal, task checklist, and spec updates clarifying upload-only cache behavior and recovery scenarios.
  • Tests

    • Added tests validating non-destructive upload-only read behavior, monotonic 404 responses, and repair-by-PUT flows.

Walkthrough

This PR makes upload-only (/upload) narinfo reads non-destructive when the backing NAR is missing: the cache returns a not-found sentinel (HTTP 404) and skips calling purgeNarInfo, preserving DB rows so clients can repair by re-uploading.

Changes

Upload-only Read Path Purge Behavior

Layer / File(s) Summary
Specification and design documentation
openspec/changes/archive/2026-06-03-fix-upload-read-no-purge/.openspec.yaml, design.md, proposal.md, tasks.md, specs/narinfo-purge-serving/spec.md, openspec/specs/narinfo-purge-serving/spec.md
New requirement and supporting docs: upload-only narinfo GETs must not purge when the backing NAR is missing; treat as cache miss (return storage.ErrNotFound / HTTP 404) without upstream fetch. Non-upload-only requests still fall through to upstream fetch when the purge sentinel occurs.
Cache read-path implementation
pkg/cache/cache.go
getNarInfoFromDatabase checks IsUploadOnly(ctx) in the missing-NAR branch and returns the ErrNarInfoPurged sentinel early, avoiding purgeNarInfo and preserving the DB row for client repair.
Test helpers and validation cases
pkg/cache/upload_only_purge_internal_test.go
Helpers and tests create phantom narinfos and assert: upload-only internal read returns purge sentinel without deleting row; public upload-only GetNarInfo maps to storage.ErrNotFound and remains non-mutating across repeated reads; non-upload-only internal read still purges; upload PUT repairs the phantom and later reads succeed.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • kalbasit/ncps#1275: Both PRs modify the cache “purge narinfo” flow in pkg/cache/cache.go—one prevents purgeNarInfo for upload-only phantom reads, the other makes purgeNarInfo store deletions idempotent by ignoring storage.ErrNotFound.
  • kalbasit/ncps#1299: Both PRs modify narinfo purge/missing-NAR handling in pkg/cache/cache.go to change behavior when backing NAR is absent or storage stats are ambiguous.
  • kalbasit/ncps#1279: Both PRs change getNarInfoFromDatabase purge-guard behavior to avoid purging under specific “shouldn’t purge” conditions (upload-only vs. concurrent in-flight downloads).

Suggested labels

go

Poem

🐰 I sniff a stale narinfo near,
I skip the broom when uploads are here,
A gentle 404 I softly send,
So clients can mend and all is well again.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The PR title 'fix(cache): no purge on upload-only narinfo reads' clearly and concisely summarizes the main change: preventing purge operations on upload-only narinfo reads.
Description check ✅ Passed The PR description is directly related to the changeset, detailing the phantom narinfo problem, the fix applied, scope, and test plan with clear connection to the code changes.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
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 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.

@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

🤖 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

📥 Commits

Reviewing files that changed from the base of the PR and between e751305 and 8fc1a1e.

📒 Files selected for processing (8)
  • openspec/changes/archive/2026-06-03-fix-upload-read-no-purge/.openspec.yaml
  • openspec/changes/archive/2026-06-03-fix-upload-read-no-purge/design.md
  • openspec/changes/archive/2026-06-03-fix-upload-read-no-purge/proposal.md
  • openspec/changes/archive/2026-06-03-fix-upload-read-no-purge/specs/narinfo-purge-serving/spec.md
  • openspec/changes/archive/2026-06-03-fix-upload-read-no-purge/tasks.md
  • openspec/specs/narinfo-purge-serving/spec.md
  • pkg/cache/cache.go
  • pkg/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]>
@kalbasit
kalbasit merged commit 54d48fe into main Jun 4, 2026
34 checks passed
@kalbasit
kalbasit deleted the user/wnasreddine/fix-upload-read-no-purge branch June 4, 2026 01:09
kalbasit added a commit that referenced this pull request Jun 4, 2026
## 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]>
kalbasit added a commit that referenced this pull request Jun 5, 2026
## 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working 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