Repository navigation
fix(cache): close the CDC url=none/xz-NAR desync (prevention + repair) - #1332
Conversation
|
This change is part of the following stack:
Change managed by git-spice. |
|
Too much diff to scan? Review this PR in Change Stack to start with the highest-impact changes. Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent 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 (13)
✅ Files skipped from review due to trivial changes (5)
🚧 Files skipped from review as they are similar to previous changes (5)
📝 WalkthroughSummary by CodeRabbit
WalkthroughThis PR fixes CDC narinfo URL/compression desynchronization by removing eager store-time normalization, adding per-dialect repair migrations, updating contract tests to verify truthful persistence, introducing a regression test, and documenting the change across specs and design docs. ChangesCDC narinfo URL/compression inconsistency resolution
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related issues
Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
Comment |
There was a problem hiding this comment.
Code Review
This pull request removes the store-time eager-CDC URL normalization to prevent desynchronization between persisted narinfos and their actual backing storage. Previously, narinfos were prematurely normalized to compression 'none' before background chunking completed, leading to 404 errors if chunking failed or was interrupted. The changes ensure that narinfos are persisted truthfully with their upstream compression (e.g., xz) until they are genuinely chunked. Additionally, database migrations are provided for MySQL, Postgres, and SQLite to repair existing stranded narinfos, and corresponding tests have been updated or added to verify the new behavior. No review comments were provided, so there is no additional feedback.
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.
|
Related Knowledge 1 document with suggested updates is ready for review. kalbasit's Space NAR File Download and StreamingView Suggested Changes@@ -291,18 +291,18 @@
#### GetNarInfo In-Memory Normalization
-When CDC is enabled and lazy chunking is used, narinfos are initially stored in the database with the upstream compression (e.g., `Compression: xz`) while the NAR is chunked in the background. After chunking completes, the database is updated asynchronously. During this window, `GetNarInfo` normalizes the narinfo in-memory before returning to prevent compression mismatches.
+When CDC is enabled, narinfos are persisted to the database with their truthful upstream compression (e.g., `Compression: xz`) and URL until CDC chunking actually completes. The `pullNarInfo` function does NOT normalize narinfos to `compression=none` at store time, regardless of whether lazy chunking is enabled or not. This prevents a narinfo/storage desync where the database advertises `nar/<hash>.nar` (compression=none) while the NAR is still stored under its original compression (e.g., xz), causing 404 errors and `nix copy` reference check failures.
The normalization behavior:
-- If the NAR is already in chunks (`HasNarInChunks` returns true): rewrites `Compression`, `URL`, `FileHash`, and `FileSize` in memory only—the database record is not modified synchronously
+- **Store time**: The narinfo is persisted with its truthful upstream compression and URL. The `pullNarInfo` function only normalizes `Compression:none` upstreams (e.g., Harmonia's zstd-stored, none-served path); CDC narinfos are never normalized at store time.
+- **Serve time**: `GetNarInfo` normalizes the narinfo in-memory via `maybeCDCNormalizeNarInfoURL` before returning to clients, but only once the NAR is genuinely chunked (`HasNarInChunks` returns true). This rewrites `Compression`, `URL`, `FileHash`, and `FileSize` in memory only—the database record is not modified synchronously.
- Normalizes the URL hash before the `HasNarInChunks` lookup to handle nix-serve-style prefixed hashes (e.g., `abc-hash` → `hash`) matching nar_file rows correctly
- Skips normalization entirely when CDC is disabled
-This ensures that clients receive consistent `Compression: none` / `.nar` URL without waiting for the database update, eliminating the race condition where `GetNarInfo` could return `Compression: xz` while `GetNar` serves uncompressed chunk data—which causes Nix to fail with "input compression not recognized".
-
-**Compression Preservation:**
-
-When lazy chunking is enabled and a NAR file has not yet been chunked (`total_chunks = 0`), the system preserves the original compression format (e.g., xz) and FileSize from the upstream cache in the narinfo response. This ensures clients receive accurate metadata during the chunking transition period. The `pullNarInfo` function skips the compression normalization step that would otherwise convert all CDC-enabled narinfos to `compression=none` immediately, allowing the original compressed NAR to be served until chunking completes.
+This ensures that the persisted narinfo always matches actual storage state:
+- If chunking hasn't completed (or never completes due to a crash/restart), the narinfo truthfully advertises its original compression (e.g., xz) and URL
+- Once chunking completes, serve-time normalization presents `compression=none` to clients
+- The narinfo never advertises chunks that don't exist yet, preventing 404 errors during background chunking or after process restarts
**Delayed Deletion:**
|
64d30e0 to
f114ec1
Compare
f114ec1 to
97a8661
Compare
b7e45dd to
acd2f76
Compare
97a8661 to
bbe3526
Compare
Eager CDC pulls rewrote the persisted narinfo URL to nar/<hash>.nar (Compression none) and nulled FileHash synchronously in pullNarInfo, BEFORE the background chunking ran. The nar_file is first written whole-file under its real compression (e.g. xz, total_chunks=0) and only flipped to none/chunked later by SetTotalChunks. If chunking never completes (process crash/restart in that window), the narinfo is left permanently advertising a none URL while the NAR is stored xz-only at /nar/<hash>.nar.xz -- so a client GET of /nar/<hash>.nar 404s and a `nix copy --to .../upload` reference check aborts with "the reference does not exist". Confirmed in production: 127 narinfos in this state, seeded as far back as the CDC snapshot. 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. Updates two CDC contract tests that asserted the removed store-time "normalize to none" behavior to instead assert the narinfo-storage consistency invariant, and points the phantom-recovery test at the URL the narinfo now advertises. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Forward-only data repair for the 127 production narinfos stranded by
the now-removed store-time eager-CDC URL normalization: each advertises
url=nar/<hash>.nar (Compression none) while its ONLY backing nar_file is
a whole-file xz NAR (compression=xz, total_chunks=0), so the none URL
404s and `nix copy` reference checks abort.
Restore each such narinfo to match its actual storage -- xz url,
compression, file_hash ('sha256:'||nar_file.hash) and file_size -- all
reconstructed from the joined nar_file. Narinfos that also have a
servable none/chunked backing are excluded via NOT EXISTS (already
correct). Idempotent: after repair the url ends in .nar.xz and no longer
matches; a no-op on databases without affected rows. Validated live
against the CDC snapshot DB (UPDATE 3, second run 0).
Per-dialect (sqlite UPDATE..FROM, postgres UPDATE..FROM, mysql
UPDATE..JOIN..SET); atlas.sum rehashed.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
OpenSpec change for the truthful-CDC-narinfo fix: spec delta for cdc-chunking (store-time url=none normalization removed; serve-time HasNarInChunks-gated normalization is the sole presenter of none), plus proposal, design, and tasks covering the 127-row repair migration. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Add the store-time CDC-normalization requirement to the cdc-chunking spec and move the change to the archive. (--no-validate: the existing cdc-chunking spec predates strict SHALL/MUST validation, repo-wide.) Co-Authored-By: Claude Opus 4.8 <[email protected]>
bbe3526 to
0e73997
Compare
…ck + prevention) (#1333) ## Summary Stacked on #1332. Roots out the cause of the cache being stuck in CDC **drain mode** (2,499 chunked NARs the de-chunk pass silently skipped), and removes a related **fsck data-loss hazard**. **Root cause:** the `narinfo_nar_files` join link is created in the narinfo-write path (`storeInDatabase`), decoupled from the async CDC chunking that finalizes the chunked `nar_file`. A rare race (~0.8% of CDC NARs in a prod snapshot) leaves the chunked `nar_file` **unlinked**. That link is the *only* way `linkedNarinfoNarHash` resolves the verification hash, so de-chunk skipped every unlinked NAR (`ErrNoNarHashToVerify`) → drain never exits. Worse, fsck classified those valid, reachable narinfos as orphans and **deleted** them. Three fixes (A+C in `cache.go`, B in `fsck.go`): - **A — de-chunk robustness:** `linkedNarinfoNarHash` falls back to resolving the narinfo by the NAR's `Compression:none` URL when no join link exists, so an unlinked chunked NAR is still content-verified and drained. - **C — creation-race prevention:** `checkAndFixNarInfosForNar` (runs right after chunking completes) reconciles the link via upsert — a no-op when it already exists, closing the race at the source. - **B — fsck safety:** repair the missing link (recreate it when the nar_file the URL references is present) instead of deleting the narinfo; only genuine orphans are still reclaimed. A follow-up data remediation (backfill/repair the existing 2,499, re-run `migrate-chunks-to-nar`, exit drain) is performed operationally against prod with this image. ## Test plan - [x] `task fmt` / `task lint` / `task test` pass - [x] de-chunk of an unlinked chunked NAR succeeds via URL fallback - [x] chunking-completion reconciles the missing link - [x] fsck repairs an unlinked narinfo with a backing nar_file; still deletes one with no backing (`-count=3`, non-flaky) - [ ] prod: re-run de-chunk drains all chunked NARs, then exit drain mode --------- 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
getNarFromStore streams the raw bytes of the whole file it opened (e.g. xz), but then overwrote narURL.Compression with the compression of the record returned by getNarFileFromDB, which is CDC-first and returns the coexisting chunked compression=none row during the lazy-chunking transition window. The response then advertised Compression:none while the body was raw xz, with Content-Length set to the xz size (< NarSize), so nix failed with 'NAR is incomplete' / 'input compression not recognized'. This deterministically broke the enable-CDC-on-an-existing- whole-file-cache upgrade path. Query the nar_file row for the representation actually being served (hash + served compression + query) instead of the CDC-first lookup, and stop overwriting narURL.Compression. The served compression now matches the streamed bytes; the last_accessed_at touch targets the served row. This is the NAR-serve counterpart to the narinfo-side normalization in maybeCDCNormalizeNarInfoURL (#1332). Caught by the new CDC lifecycle e2e (dev-scripts/test-cdc-lifecycle-e2e.py). Includes a pkg/cache regression test and the OpenSpec change artifacts. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…1346) ## Summary `getNarFromStore` streams the raw bytes of the whole file it opened (e.g. `xz`), but then overwrote `narURL.Compression` with the compression of the record returned by `getNarFileFromDB`, which is **CDC-first** and returns the coexisting chunked `compression=none` row during the lazy-chunking transition window. The response then advertised `Compression: none` while the body was raw xz, with `Content-Length` set to the xz size (< `NarSize`), so `nix` failed with: - `error: NAR for '…' fetched from … is incomplete` - `error: input compression not recognized` This deterministically broke the **enable-CDC-on-an-existing-whole-file-cache** upgrade path. It is the NAR-serve counterpart to the narinfo-side normalization already done in `maybeCDCNormalizeNarInfoURL` (#1332). ## Fix Query the `nar_file` row for the representation actually being served (`hash + served compression + query`) instead of the CDC-first lookup, and stop overwriting `narURL.Compression`. The served compression now matches the streamed bytes; the `last_accessed_at` touch targets the served row. Adds a `pkg/cache` regression test (`TestCDCWholeFileServeReportsServedCompression`) and the OpenSpec change `fix-cdc-incomplete-nar-serve` (adds a `cdc-chunking` requirement: GetNar must advertise the compression of the bytes it serves). ## Test plan - [x] New regression test fails before the fix (returns `none`, short length) and passes after - [x] `task fmt`, `task lint`, full `task test` green - [x] Caught + then validated end-to-end by the new CDC lifecycle e2e driver (top of stack) --------- Co-authored-by: Claude Opus 4.8 <[email protected]>
Summary
Stacked on #1330. Root-cause fix + data repair for the production
nix copy --to .../uploadaborts (cannot add X because the reference Y does not exist).Root cause (confirmed against the live CDC snapshot DB):
pullNarInforewrote the persisted narinfo URL to
nar/<hash>.nar(Compression none)ran. The nar_file is first written whole-file under its real compression
(xz,
total_chunks=0) and only flipped to none/chunked later bySetTotalChunks. A crash/restart in that window strands the narinfoadvertising a
noneURL while the NAR is stored xz-only at/nar/<hash>.nar.xz→ the none URL 404s → reference check aborts. Thebroken narinfos' URL hash is the xz file hash, not the NAR hash, and
file_hashis NULL — the fingerprint of this exact path.Prevention (commit 1)
Persist the narinfo truthfully. Only normalize to
nonefor genuinelyCompression:noneupstreams (stored zstd, served none transparently — theHarmonia path, unchanged). Do not predict
nonefor CDC. Serve-timemaybeCDCNormalizeNarInfoURLalready presentsurl=noneonce the NAR isgenuinely chunked (
HasNarInChunks), so the steady-state serve contractis 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
task fmt/task lint/task testpass-count=3, non-flaky)migration applies