Skip to content

fix(cache): non-destructive narinfo purge on root path - #1326

Merged
kalbasit merged 2 commits into
mainfrom
user/wnasreddine/non-destructive-narinfo-purge
Jun 5, 2026
Merged

kalbasit merged 2 commits into
mainfrom
user/wnasreddine/non-destructive-narinfo-purge

Conversation

@kalbasit

@kalbasit kalbasit commented Jun 4, 2026

Copy link
Copy Markdown
Owner

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

  • task fmt, task lint (0 issues), task test (full suite, pkg/cache under -race) all pass
  • New tests: substituter DB/store reads non-destructive; nar_file record preserved; refcount-safe purge (shared survives / orphan reclaimed); upstream heal-in-place
  • Updated the prior NonUploadOnlyStillPurges test to assert the new non-destructive behavior

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.
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. 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

📝 Walkthrough

Summary by CodeRabbit

  • New Features
    • Non-destructive narinfo purge: missing-NAR reads now re-fetch upstream or return 404 without deleting existing records; NAR deletion is refcount-aware and only reclaims truly orphaned bytes. Added a durable "bytes stored" marker to track written NAR bytes across replicas.
  • Documentation
    • Added spec, design, tasks, and archive notes describing non-destructive purge semantics and healing behavior.
  • Tests
    • Added/updated tests covering non-destructive reads, refcount-safe deletion, chunk-backed availability, and upstream healing.
  • Chores
    • Database migrations to add the new nullable bytes-stored timestamp column.

Walkthrough

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

Changes

Non-Destructive Narinfo Purge with Refcount Safety

Layer / File(s) Summary
Specification & Design Documentation
openspec/changes/archive/2026-06-04-non-destructive-narinfo-purge/, openspec/specs/narinfo-purge-serving/spec.md
Design, proposal, and spec updates that define non‑destructive missing‑NAR handling: missing‑NAR read paths must not call purgeNarInfo or delete records; they should return ErrNarInfoPurged to enable upstream re‑fetch/healing. Spec requires refcount‑aware deletion of nar_file/NAR bytes and mapping leaked sentinels to HTTP 404.
Ent schema & generated builders
ent/schema/nar_file.go, ent/* generated files, ent/migrate/schema.go
Adds nullable nar_file.bytes_stored_at, wires it through Ent mutation/entity, predicates, create/upsert/update builders, ordering helper, and adjusts generated runtime/migration artifacts.
DB Migrations
migrations/*/20260605021047_add_bytes_stored_at_to_nar_files.sql
Adds nullable bytes_stored_at column to nar_files for MySQL/Postgres/SQLite.
Non-Destructive Cache Read Paths
pkg/cache/cache.go
getNarInfoFromStore and getNarInfoFromDatabase now treat missing backing NAR as a non‑destructive cache miss (debug log + return ErrNarInfoPurged), check chunk‑backed availability where applicable, and no longer call purgeNarInfo. ensureNarFileRecord now writes nar_file.bytes_stored_at on upsert; narFileBytesStored helper added; legacy deleteNarFromStore removed; deleteNarBytes added.
Refcount‑Safe Purge Logic
pkg/cache/cache.go
purgeNarInfo rewritten: inside a transaction delete the narinfo, inspect linked nar_file rows, and delete each nar_file only if it has zero remaining narinfo links; collect orphaned nar_file URLs and delete their NAR bytes afterwards via new deleteNarBytes (including .nar.zst for compression=none).
Test Helpers & Behavioural Tests
pkg/cache/nondestructive_narinfo_purge_internal_test.go, pkg/cache/purge_serving_internal_test.go, pkg/cache/upload_only_purge_internal_test.go
Added DB/store existence helpers and seedSharedNar; new and updated tests verify non‑destructive read‑path behavior (TestGetNarInfoFromStore_MissingNarDoesNotPurge, TestGetNarInfoFromDatabase_NonUploadOnly_PreservesNarFileRecord, TestGetNarInfo_SubstituterMissingNarHealsFromUpstreamWithoutPurging), chunk‑backed handling, bytes_stored_at semantics, compression=none reclaiming .nar.zst, and purge refcount safety (TestPurgeNarInfo_SharedNarFileSurvives, TestPurgeNarInfo_OrphanedNarFileDeleted).

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly Related PRs

  • kalbasit/ncps#1321: Related changes to missing‑NAR purge handling on upload‑only reads and upstream re‑fetch logic.
  • kalbasit/ncps#1201: Overlaps in purge/delete flow and Ent delete-path changes.
  • kalbasit/ncps#1279: Related adjustments to the purge guard/TOCTOU narrowing in getNarInfo read paths.

Suggested Labels

bug

Poem

🐰 I nibble bytes beneath the logbook tree,
No more vanish tricks — records safe with me.
Upstream mends the hole, no sudden purge alarm,
Shared NARs hold steady, kept from any harm.
A rabbit cheers: non‑destructive calm!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The PR title 'fix(cache): non-destructive narinfo purge on root path' clearly and concisely describes the main change: fixing narinfo purge behavior on the root/substituter path to be non-destructive.
Description check ✅ Passed The PR description is directly related to the changeset, explaining the root cause of the issue, the specific changes made to fix it, and referencing relevant test coverage.
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 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.

@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: 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

📥 Commits

Reviewing files that changed from the base of the PR and between d345d50 and b4366cc.

📒 Files selected for processing (10)
  • openspec/changes/archive/2026-06-04-non-destructive-narinfo-purge/.openspec.yaml
  • openspec/changes/archive/2026-06-04-non-destructive-narinfo-purge/design.md
  • openspec/changes/archive/2026-06-04-non-destructive-narinfo-purge/proposal.md
  • openspec/changes/archive/2026-06-04-non-destructive-narinfo-purge/specs/narinfo-purge-serving/spec.md
  • openspec/changes/archive/2026-06-04-non-destructive-narinfo-purge/tasks.md
  • openspec/specs/narinfo-purge-serving/spec.md
  • pkg/cache/cache.go
  • pkg/cache/nondestructive_narinfo_purge_internal_test.go
  • pkg/cache/purge_serving_internal_test.go
  • pkg/cache/upload_only_purge_internal_test.go

Comment thread pkg/cache/cache.go Resolved
Comment thread pkg/cache/cache.go Resolved
Comment thread pkg/cache/cache.go Resolved
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.

@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: 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

📥 Commits

Reviewing files that changed from the base of the PR and between fabde4f and 4c37e1f.

📒 Files selected for processing (2)
  • pkg/cache/cache.go
  • pkg/cache/nondestructive_narinfo_purge_internal_test.go

Comment thread pkg/cache/cache.go Resolved
@kalbasit
kalbasit force-pushed the user/wnasreddine/non-destructive-narinfo-purge branch from 4c37e1f to df94c19 Compare June 5, 2026 02:16
@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Jun 5, 2026

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

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 win

Collapse the orphan check and delete into one statement.

This is still a TOCTOU window. Another transaction can link nf.ID after Exist returns false but before DeleteOne runs, and then this purge can cascade-delete a freshly re-linked nar_file before 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 win

Normalize the NAR URL before checking bytes_stored_at.

storeInDatabase writes nar_file rows 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 to ErrNarInfoPurged/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

📥 Commits

Reviewing files that changed from the base of the PR and between 4c37e1f and df94c19.

⛔ Files ignored due to path filters (3)
  • migrations/mysql/atlas.sum is excluded by !**/*.sum
  • migrations/postgres/atlas.sum is excluded by !**/*.sum
  • migrations/sqlite/atlas.sum is excluded by !**/*.sum
📒 Files selected for processing (14)
  • ent/migrate/schema.go
  • ent/mutation.go
  • ent/narfile.go
  • ent/narfile/narfile.go
  • ent/narfile/where.go
  • ent/narfile_create.go
  • ent/narfile_update.go
  • ent/runtime.go
  • ent/schema/nar_file.go
  • migrations/mysql/20260605021047_add_bytes_stored_at_to_nar_files.sql
  • migrations/postgres/20260605021047_add_bytes_stored_at_to_nar_files.sql
  • migrations/sqlite/20260605021047_add_bytes_stored_at_to_nar_files.sql
  • pkg/cache/cache.go
  • pkg/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

@kalbasit
kalbasit force-pushed the user/wnasreddine/non-destructive-narinfo-purge branch from df94c19 to fabde4f Compare June 5, 2026 04:00
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels Jun 5, 2026
@kalbasit
kalbasit merged commit d49719f into main Jun 5, 2026
71 of 84 checks passed
@kalbasit
kalbasit deleted the user/wnasreddine/non-destructive-narinfo-purge branch June 5, 2026 19:07
kalbasit added a commit that referenced this pull request Jun 5, 2026
## 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]>
kalbasit added a commit to bryandph/ncps that referenced this pull request Jun 7, 2026
* 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

go Pull requests that update go code merge-stack 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