Skip to content

fix(cache): durable-bytes marker for /upload reference presence - #1330

Merged
kalbasit merged 6 commits into
mainfrom
user/wnasreddine/upload-presence-marker
Jun 5, 2026
Merged

kalbasit merged 6 commits into
mainfrom
user/wnasreddine/upload-presence-marker

Conversation

@kalbasit

@kalbasit kalbasit commented Jun 5, 2026

Copy link
Copy Markdown
Owner

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

  • task fmt / task lint / task test pass
  • 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

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. go Pull requests that update go code labels Jun 5, 2026
@coderabbitai

coderabbitai Bot commented Jun 5, 2026 •

Copy link
Copy Markdown

PR changed again? Review this PR in Change Stack to compare snapshots and stay oriented.

Review Change Stack

Warning

Review limit reached

@kalbasit, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 4 minutes and 47 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: e5601b72-911c-4601-a2e8-14c77628f8f8

📥 Commits

Reviewing files that changed from the base of the PR and between f7b3765 and acd2f76.

⛔ 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 (20)
  • 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
  • openspec/changes/archive/2026-06-05-upload-reference-presence-marker/.openspec.yaml
  • openspec/changes/archive/2026-06-05-upload-reference-presence-marker/design.md
  • openspec/changes/archive/2026-06-05-upload-reference-presence-marker/proposal.md
  • openspec/changes/archive/2026-06-05-upload-reference-presence-marker/specs/upload-reference-presence/spec.md
  • openspec/changes/archive/2026-06-05-upload-reference-presence-marker/tasks.md
  • openspec/specs/upload-reference-presence/spec.md
  • pkg/cache/cache.go
  • pkg/cache/nondestructive_narinfo_purge_internal_test.go
📝 Walkthrough

Walkthrough

This PR introduces a durable bytes_stored_at marker to the nar_files table, enabling cross-replica presence checks on the /upload path without requiring local filesystem visibility. The field is threaded through Ent (schema, generated ORM, migrations), set during upsert by ensureNarFileRecord, queried by a new narFileBytesStored helper for compression-agnostic lookup, and used to suppress purge/miss sentinels on upload-only reads.

Changes

bytes_stored_at field and cache presence logic

Layer / File(s) Summary
Schema definition and database migrations
ent/schema/nar_file.go, migrations/mysql/*, migrations/postgres/*, migrations/sqlite/*
Adds optional, nullable bytes_stored_at timestamp field to NarFile schema; per-dialect migrations define the column add/drop.
Ent ORM code generation for bytes_stored_at
ent/migrate/schema.go, ent/runtime.go, ent/mutation.go, ent/narfile.go, ent/narfile/narfile.go, ent/narfile/where.go, ent/narfile_create.go, ent/narfile_update.go
Generated Ent code integrates the new field into entity struct, mutation tracking, create/update/upsert builders, predicates, scanning/assignment, and index metadata for full ORM participation.
Record and clear bytes_stored_at marker during upsert/delete
pkg/cache/cache.go
Normalizes narURL on upsert, sets bytes_stored_at with updated_at on both insert and conflict-update; clears marker on DeleteNar so deleted NARs won't be reported present.
Check marker and bypass purge/miss logic
pkg/cache/cache.go
Adds narFileBytesStored helper (compression-agnostic hash+query lookup for non-NULL marker); applies upload-only exceptions in getNarInfoFromStore and getNarInfoFromDatabase to avoid false misses/purges when peer has written bytes.
Tests for bytes_stored_at marker behavior
pkg/cache/nondestructive_narinfo_purge_internal_test.go
Validates that upload-path trusts the marker (present without local bytes, compression-agnostic), that placeholders without marker remain a miss, and that DeleteNar clears the marker.
OpenSpec proposal and requirements
openspec/changes/archive/2026-06-05-upload-reference-presence-marker/, openspec/specs/upload-reference-presence/spec.md
Proposes and specifies upload-only marker trust, design rationale (written vs. present trade-off), tasks checklist, and verification procedure.

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • kalbasit/ncps#1321: Modifies getNarInfoFromDatabase purge behavior on upload-only reads; this PR adds the marker-based presence exception to the same code path.
  • kalbasit/ncps#1205: Converts ensureNarFileRecord upsert to Ent semantics; this PR adds bytes_stored_at write logic to the same function.
  • kalbasit/ncps#1275: Makes purgeNarInfo/deleteNarFromStore idempotent; this PR clears the marker during the same deletion code path.

Suggested labels

bug, merge-stack

Poem

🐰 A timestamp springs eternal, marking bytes so true,
Cross-replica whispers—"I have stored for you!"
No purge, no miss when peers write on high,
Upload paths trust the marker, no fear, no sigh. ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The PR title clearly identifies the main change: adding a durable-bytes marker for /upload reference presence checking, which aligns with the primary objective of fixing nix copy failures.
Description check ✅ Passed The PR description comprehensively explains the problem, the two-part solution (bytes_stored_at marker and compression-agnostic lookup), design rationale, and test plan, all directly related to the changeset.
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.


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 introduces a bytes_stored_at timestamp field to the nar_files table schema, along with corresponding database migrations and generated Ent code. This field is used to track when a NAR's bytes are durably stored, allowing peer replicas to trust this shared database marker over local filesystem stats on the upload path, thereby preventing false 404 errors during concurrent nix copy operations. The feedback highlights two critical issues where narURL is used directly without normalization in ensureNarFileRecord and narFileBytesStored. This can lead to duplicate database rows and query mismatches when dealing with prefixed NAR URLs from nix-serve style upstreams. Normalizing the URLs before database operations is recommended to resolve these issues.

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

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 4012-4040: The current narFileBytesStored helper trusts any
non-NULL nar_files.bytes_stored_at marker forever, causing false-positive
reference checks after blob deletions because DeleteNar removes bytes from
narStore but never clears bytes_stored_at; update all code paths that delete or
remove NAR bytes (e.g., DeleteNar and any other narStore deletion functions) to
also clear/unset the bytes_stored_at marker in the database (via the Ent NarFile
update for the given hash/query) immediately after successful byte deletion, and
ensure PutNar still sets bytes_stored_at on success so the flag stays consistent
with actual blob presence; target the DeleteNar implementation and any
garbage-collection or prune routines touching narStore to perform the DB update.
🪄 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: b7e1812e-ca94-4c4d-bc6f-2c624a0e1583

📥 Commits

Reviewing files that changed from the base of the PR and between fabde4f and 6e6472e.

⛔ 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

Comment thread pkg/cache/cache.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)
openspec/changes/upload-reference-presence-marker/design.md (1)

17-19: ⚡ Quick win

Verify the eviction trade-off is acceptable for the upload path.

The design notes that an eviction could clear NAR bytes without clearing the bytes_stored_at marker, meaning a reference check would report the NAR present but a subsequent GET might find it missing. You've documented this as "acceptable on the upload path", but this could cause a GET to fail and require upstream re-pull after a reference check succeeded.

Can you confirm this is the intended behavior? Specifically:

  1. Should eviction logic clear the bytes_stored_at marker when it removes NAR bytes?
  2. Or is the design intentionally allowing this race because the worst-case outcome (GET re-pulls from upstream after reference check succeeds) is tolerable?

If intentional, consider adding a note in the Risks section about the expected behavior when this occurs (e.g., "GET will fall back to upstream re-pull" or similar).

🤖 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 `@openspec/changes/upload-reference-presence-marker/design.md` around lines 17
- 19, Clarify that the eviction race is intentional: update the "Risks /
Trade-offs" section to explicitly state that the design intentionally allows the
marker (bytes_stored_at) to persist after NAR bytes are evicted on the upload
path, and that this will cause a reference check to sometimes succeed while a
subsequent GET will fall back to re-pulling from upstream; mention that the
substituter path must not trust the marker. Ensure you reference the marker name
bytes_stored_at, the upload path behavior, and the substituter path so reviewers
can locate and verify the change.
🤖 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 `@openspec/changes/upload-reference-presence-marker/design.md`:
- Around line 17-19: Clarify that the eviction race is intentional: update the
"Risks / Trade-offs" section to explicitly state that the design intentionally
allows the marker (bytes_stored_at) to persist after NAR bytes are evicted on
the upload path, and that this will cause a reference check to sometimes succeed
while a subsequent GET will fall back to re-pulling from upstream; mention that
the substituter path must not trust the marker. Ensure you reference the marker
name bytes_stored_at, the upload path behavior, and the substituter path so
reviewers can locate and verify the change.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: e082b279-64f9-420a-ba2b-13307fb8f6b6

📥 Commits

Reviewing files that changed from the base of the PR and between 6e6472e and 556907e.

📒 Files selected for processing (5)
  • openspec/changes/upload-reference-presence-marker/.openspec.yaml
  • openspec/changes/upload-reference-presence-marker/design.md
  • openspec/changes/upload-reference-presence-marker/proposal.md
  • openspec/changes/upload-reference-presence-marker/specs/upload-reference-presence/spec.md
  • openspec/changes/upload-reference-presence-marker/tasks.md
✅ Files skipped from review due to trivial changes (3)
  • openspec/changes/upload-reference-presence-marker/proposal.md
  • openspec/changes/upload-reference-presence-marker/.openspec.yaml
  • openspec/changes/upload-reference-presence-marker/tasks.md

kalbasit added a commit that referenced this pull request Jun 5, 2026
Addresses PR #1330 review comments:

- Normalize the NAR URL in ensureNarFileRecord and narFileBytesStored
  (threads HQhTI, HQhTO) so they use the same canonical key
  storeInDatabase writes under. A nix-serve-style prefixed URL would
  otherwise split the marker onto a duplicate prefixed row while the
  narinfo stays linked to the normalized row, defeating the /upload
  presence check.

- Clear nar_file.bytes_stored_at in DeleteNar after the bytes are
  removed (thread HQkfd). The marker was sticky: an evicted NAR kept a
  non-NULL marker forever, so the /upload reference check reported it
  present (false positive). Purge/LRU delete the row (marker goes with
  it) and chunking-migration keeps the marker valid as chunks, so
  DeleteNar is the path that needed the explicit clear.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

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

1545-1591: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Stamp bytes_stored_at in every whole-file write path.

This new marker becomes the /upload source of truth, but MigrateChunksToNar writes whole-file bytes back into narStore and flips the existing nar_file row without ever setting bytes_stored_at. On another replica, getNarInfoFromDatabase can still false-miss that de-chunked NAR until local storage visibility catches up.

💡 Minimal fix
-	if err := c.withEntTransaction(ctx, "MigrateChunksToNar.flip", func(tx *ent.Tx) error {
+	if err := c.withEntTransaction(ctx, "MigrateChunksToNar.flip", func(tx *ent.Tx) error {
+		now := time.Now()
 		if _, err := tx.NarFileChunk.Delete().
 			Where(entnarfilechunk.NarFileID(nr.ID)).
 			Exec(ctx); err != nil {
 			return fmt.Errorf("error deleting chunk links: %w", err)
 		}

 		if _, err := tx.NarFile.UpdateOneID(nr.ID).
 			SetTotalChunks(0).
+			SetBytesStoredAt(now).
 			ClearChunkingStartedAt().
-			SetUpdatedAt(time.Now()).
+			SetUpdatedAt(now).
 			Save(ctx); err != nil {
 			return fmt.Errorf("error flipping nar_file to whole-file: %w", err)
 		}
🤖 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 1545 - 1591, The database marker
bytes_stored_at must be set whenever a whole-file NAR is written; find the
whole-file write paths (notably ensureNarFileRecord's tx.NarFile.Create() upsert
and the MigrateChunksToNar code path that writes a de-chunked NAR into narStore)
and ensure they call SetBytesStoredAt(now) on insert and also on
conflicts/updates (e.g., in the ent.NarFileUpsert callback use
u.SetBytesStoredAt(now) alongside u.SetFileSize(...) and u.SetUpdatedAt(...));
likewise, any function that flips a nar_file row after writing whole-file bytes
must set bytes_stored_at to the current time so getNarInfoFromDatabase sees the
NAR as present on other replicas.
🤖 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 1545-1591: The database marker bytes_stored_at must be set
whenever a whole-file NAR is written; find the whole-file write paths (notably
ensureNarFileRecord's tx.NarFile.Create() upsert and the MigrateChunksToNar code
path that writes a de-chunked NAR into narStore) and ensure they call
SetBytesStoredAt(now) on insert and also on conflicts/updates (e.g., in the
ent.NarFileUpsert callback use u.SetBytesStoredAt(now) alongside
u.SetFileSize(...) and u.SetUpdatedAt(...)); likewise, any function that flips a
nar_file row after writing whole-file bytes must set bytes_stored_at to the
current time so getNarInfoFromDatabase sees the NAR as present on other
replicas.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: da1a069a-b6f8-42c5-89d2-78d764ea2489

📥 Commits

Reviewing files that changed from the base of the PR and between 556907e and 4775811.

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

@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 `@openspec/specs/upload-reference-presence/spec.md`:
- Line 4: Replace the "TBD" placeholder in the Purpose section with a concrete
purpose statement describing why upload-reference-presence exists and what it
achieves; locate the Purpose header in
openspec/specs/upload-reference-presence/spec.md (search for the "Purpose"
section and the "TBD" token) and replace that token with a clear, concise
sentence or two that summarizes the feature's intent, scope, and intended
consumers.
🪄 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: 5bb4eecc-2f11-4a82-82bd-c51a50708649

📥 Commits

Reviewing files that changed from the base of the PR and between 4775811 and f7b3765.

📒 Files selected for processing (6)
  • openspec/changes/archive/2026-06-05-upload-reference-presence-marker/.openspec.yaml
  • openspec/changes/archive/2026-06-05-upload-reference-presence-marker/design.md
  • openspec/changes/archive/2026-06-05-upload-reference-presence-marker/proposal.md
  • openspec/changes/archive/2026-06-05-upload-reference-presence-marker/specs/upload-reference-presence/spec.md
  • openspec/changes/archive/2026-06-05-upload-reference-presence-marker/tasks.md
  • openspec/specs/upload-reference-presence/spec.md
💤 Files with no reviewable changes (5)
  • openspec/changes/archive/2026-06-05-upload-reference-presence-marker/.openspec.yaml
  • openspec/changes/archive/2026-06-05-upload-reference-presence-marker/proposal.md
  • openspec/changes/archive/2026-06-05-upload-reference-presence-marker/design.md
  • openspec/changes/archive/2026-06-05-upload-reference-presence-marker/specs/upload-reference-presence/spec.md
  • openspec/changes/archive/2026-06-05-upload-reference-presence-marker/tasks.md

kalbasit added a commit that referenced this pull request Jun 5, 2026
Base automatically changed from user/wnasreddine/non-destructive-narinfo-purge to main June 5, 2026 19:07
@kalbasit
kalbasit enabled auto-merge (squash) June 5, 2026 19:07
@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
kalbasit and others added 6 commits June 5, 2026 19:08
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).
The /upload narinfo presence check looked up the backing nar_file by
the narinfo URL's advertised compression. Production has CDC-residue
narinfos that advertise url=nar/<hash>.nar (Compression:none) while the
NAR is durably stored only under a different compression (xz). The
compression-keyed lookup missed the xz row, so the reference check
404'd a present NAR and aborted concurrent `nix copy --to .../upload`
with "the reference does not exist".

Query the nar_file by hash (+query) regardless of compression, gated on
bytes_stored_at being set. The hash identifies the NAR and the marker
proves PutNar durably wrote its bytes, so presence no longer depends on
which compression variant the narinfo URL happens to advertise. A
byte-less placeholder row is still NOT trusted, so phantoms stay
excluded.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
OpenSpec change for the /upload reference-presence fix: new capability
upload-reference-presence (the bytes_stored_at durable marker is trusted,
compression-agnostically, on the upload-only path so a peer-stored or
compression-mismatched NAR is not 404'd), plus proposal, design, tasks.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Addresses PR #1330 review comments:

- Normalize the NAR URL in ensureNarFileRecord and narFileBytesStored
  (threads HQhTI, HQhTO) so they use the same canonical key
  storeInDatabase writes under. A nix-serve-style prefixed URL would
  otherwise split the marker onto a duplicate prefixed row while the
  narinfo stays linked to the normalized row, defeating the /upload
  presence check.

- Clear nar_file.bytes_stored_at in DeleteNar after the bytes are
  removed (thread HQkfd). The marker was sticky: an evicted NAR kept a
  non-NULL marker forever, so the /upload reference check reported it
  present (false positive). Purge/LRU delete the row (marker goes with
  it) and chunking-migration keeps the marker valid as chunks, so
  DeleteNar is the path that needed the explicit clear.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Sync the upload-reference-presence capability spec into openspec/specs/
and move the change to the archive.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@kalbasit
kalbasit force-pushed the user/wnasreddine/upload-presence-marker branch from b7e45dd to acd2f76 Compare June 5, 2026 19:08
@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 0caba3e into main Jun 5, 2026
36 checks passed
@kalbasit
kalbasit deleted the user/wnasreddine/upload-presence-marker branch June 5, 2026 19:15
kalbasit added a commit that referenced this pull request Jun 5, 2026
#1332)

## Summary

Stacked on #1330. Root-cause fix + data repair for the production
`nix copy --to .../upload` aborts (`cannot add X because the reference Y
does not exist`).

**Root cause** (confirmed against the live CDC snapshot DB):
`pullNarInfo`
rewrote the persisted narinfo URL to `nar/<hash>.nar` (Compression none)
+ nulled FileHash **synchronously, before** background eager-CDC
chunking
ran. The nar_file is first written whole-file under its real compression
(xz, `total_chunks=0`) and only flipped to none/chunked later by
`SetTotalChunks`. A crash/restart in that window strands the narinfo
advertising a `none` URL while the NAR is stored xz-only at
`/nar/<hash>.nar.xz` → the none URL 404s → reference check aborts. The
broken narinfos' URL hash is the **xz file hash, not the NAR hash**, and
`file_hash` is NULL — the fingerprint of this exact path.

### Prevention (commit 1)
Persist the narinfo **truthfully**. Only normalize to `none` for
genuinely
`Compression:none` upstreams (stored zstd, served none transparently —
the
Harmonia path, unchanged). Do **not** predict `none` for CDC. Serve-time
`maybeCDCNormalizeNarInfoURL` already presents `url=none` once the NAR
is
genuinely chunked (`HasNarInChunks`), so the steady-state serve contract
is unchanged — only the pre-chunk window now advertises the truthful
compression instead of a not-yet-true `none`.

Two CDC contract tests that asserted the removed store-time "normalize
to
none" behavior are rewritten to assert the **narinfo↔storage consistency
invariant** instead; the phantom-recovery test now addresses the NAR via
the URL the narinfo advertises.

### Repair (commit 2)
Forward-only per-dialect data migration restoring the **127** production
narinfos already in this state: rewrite `url`→`.nar.xz`,
`compression`→xz,
`file_hash`→`'sha256:'||nar_file.hash`, `file_size`→nar_file.file_size,
all reconstructed from the joined nar_file. Narinfos that also have a
servable none/chunked backing are excluded (`NOT EXISTS`). Idempotent;
no-op on clean DBs. Validated live against the CDC snapshot (UPDATE 3,
second run 0).

## Test plan

- [x] `task fmt` / `task lint` / `task test` pass
- [x] New internal test: eager-CDC xz pull persists the truthful xz URL
- [x] CDC consistency tests + phantom-recovery green (`-count=3`,
non-flaky)
- [x] Repair UPDATE validated live on the CDC snapshot DB (3 rows,
idempotent)
- [ ] Deploy + confirm the 127 previously-broken paths serve once the
      migration applies

---------

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