Repository navigation
fix(cache): durable-bytes marker for /upload reference presence - #1330
Conversation
|
This change is part of the following stack:
Change managed by git-spice. |
|
PR changed again? Review this PR in Change Stack to compare snapshots and stay oriented. Warning Review limit reached
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 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 configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: ⛔ Files ignored due to path filters (3)
📒 Files selected for processing (20)
📝 WalkthroughWalkthroughThis PR introduces a durable Changesbytes_stored_at field and cache presence logic
🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Comment |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
⛔ Files ignored due to path filters (3)
migrations/mysql/atlas.sumis excluded by!**/*.summigrations/postgres/atlas.sumis excluded by!**/*.summigrations/sqlite/atlas.sumis excluded by!**/*.sum
📒 Files selected for processing (14)
ent/migrate/schema.goent/mutation.goent/narfile.goent/narfile/narfile.goent/narfile/where.goent/narfile_create.goent/narfile_update.goent/runtime.goent/schema/nar_file.gomigrations/mysql/20260605021047_add_bytes_stored_at_to_nar_files.sqlmigrations/postgres/20260605021047_add_bytes_stored_at_to_nar_files.sqlmigrations/sqlite/20260605021047_add_bytes_stored_at_to_nar_files.sqlpkg/cache/cache.gopkg/cache/nondestructive_narinfo_purge_internal_test.go
There was a problem hiding this comment.
🧹 Nitpick comments (1)
openspec/changes/upload-reference-presence-marker/design.md (1)
17-19: ⚡ Quick winVerify 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_atmarker, 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:
- Should eviction logic clear the
bytes_stored_atmarker when it removes NAR bytes?- 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
📒 Files selected for processing (5)
openspec/changes/upload-reference-presence-marker/.openspec.yamlopenspec/changes/upload-reference-presence-marker/design.mdopenspec/changes/upload-reference-presence-marker/proposal.mdopenspec/changes/upload-reference-presence-marker/specs/upload-reference-presence/spec.mdopenspec/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
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]>
There was a problem hiding this comment.
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 winStamp
bytes_stored_atin every whole-file write path.This new marker becomes the
/uploadsource of truth, butMigrateChunksToNarwrites whole-file bytes back intonarStoreand flips the existingnar_filerow without ever settingbytes_stored_at. On another replica,getNarInfoFromDatabasecan 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
📒 Files selected for processing (2)
pkg/cache/cache.gopkg/cache/nondestructive_narinfo_purge_internal_test.go
There was a problem hiding this comment.
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
📒 Files selected for processing (6)
openspec/changes/archive/2026-06-05-upload-reference-presence-marker/.openspec.yamlopenspec/changes/archive/2026-06-05-upload-reference-presence-marker/design.mdopenspec/changes/archive/2026-06-05-upload-reference-presence-marker/proposal.mdopenspec/changes/archive/2026-06-05-upload-reference-presence-marker/specs/upload-reference-presence/spec.mdopenspec/changes/archive/2026-06-05-upload-reference-presence-marker/tasks.mdopenspec/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
…_kwDONV6tZs6HcSnS) Co-Authored-By: Claude Opus 4.8 <[email protected]>
Multi-replica + shared-NFS regression: `nix copy --to .../upload` aborts with "reference X does not exist". A path's narinfo and NAR are PUT to different replicas; a concurrent reference check (GET /upload/Y.narinfo) on a replica whose local NFS view has not yet observed the peer's NAR write returns 404, aborting the copy. 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]>
…_kwDONV6tZs6HcSnS) Co-Authored-By: Claude Opus 4.8 <[email protected]>
b7e45dd to
acd2f76
Compare
#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]>
* 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
Summary
Stacked on #1326. Fixes
nix copy --to .../uploadaborting withcannot add X because the reference Y does not existagainst aproduction cache carrying CDC-era residue.
Two parts:
bytes_stored_atmarker — a dedicatednar_filecolumn (distinctfrom fsck's
verified_at) thatPutNarsets once a NAR's bytes aredurably written. On the
/uploadpath the narinfo presence checktrusts 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.
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 isstored 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
/uploadpath only: the substituter (root) path must keepself-healing a genuinely missing NAR from upstream; trusting the marker
there could mask a real eviction.
Test plan
task fmt/task lint/task testpassupload path, placeholder-not-trusted phantom guard
nix copy --to .../uploadof thepreviously-failing closures succeeds