Skip to content

fix(cache): close the CDC url=none/xz-NAR desync (prevention + repair) - #1332

Merged
kalbasit merged 4 commits into
mainfrom
user/wnasreddine/cdc-url-desync-prevention
Jun 5, 2026
Merged

kalbasit merged 4 commits into
mainfrom
user/wnasreddine/cdc-url-desync-prevention

Conversation

@kalbasit

@kalbasit kalbasit commented Jun 5, 2026

Copy link
Copy Markdown
Owner

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

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

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jun 5, 2026
@dosubot dosubot Bot added bug Something isn't working go Pull requests that update go code labels Jun 5, 2026
@coderabbitai

coderabbitai Bot commented Jun 5, 2026 •

Copy link
Copy Markdown

Too much diff to scan? Review this PR in Change Stack to start with the highest-impact changes.

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 2d54ac01-d9d5-4f56-baa8-3b2c302b2cd2

📥 Commits

Reviewing files that changed from the base of the PR and between f114ec1 and 0e73997.

⛔ 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 (13)
  • migrations/mysql/20260605045447_repair_url_none_xz_narinfos.sql
  • migrations/postgres/20260605045447_repair_url_none_xz_narinfos.sql
  • migrations/sqlite/20260605045447_repair_url_none_xz_narinfos.sql
  • openspec/changes/archive/2026-06-05-prevent-cdc-narinfo-url-desync/.openspec.yaml
  • openspec/changes/archive/2026-06-05-prevent-cdc-narinfo-url-desync/design.md
  • openspec/changes/archive/2026-06-05-prevent-cdc-narinfo-url-desync/proposal.md
  • openspec/changes/archive/2026-06-05-prevent-cdc-narinfo-url-desync/specs/cdc-chunking/spec.md
  • openspec/changes/archive/2026-06-05-prevent-cdc-narinfo-url-desync/tasks.md
  • openspec/specs/cdc-chunking/spec.md
  • pkg/cache/cache.go
  • pkg/cache/cdc_test.go
  • pkg/cache/cdc_url_desync_prevention_internal_test.go
  • pkg/cache/phantom_recovery_test.go
✅ Files skipped from review due to trivial changes (5)
  • openspec/changes/archive/2026-06-05-prevent-cdc-narinfo-url-desync/.openspec.yaml
  • openspec/changes/archive/2026-06-05-prevent-cdc-narinfo-url-desync/design.md
  • openspec/changes/archive/2026-06-05-prevent-cdc-narinfo-url-desync/tasks.md
  • openspec/specs/cdc-chunking/spec.md
  • openspec/changes/archive/2026-06-05-prevent-cdc-narinfo-url-desync/proposal.md
🚧 Files skipped from review as they are similar to previous changes (5)
  • openspec/changes/archive/2026-06-05-prevent-cdc-narinfo-url-desync/specs/cdc-chunking/spec.md
  • pkg/cache/cdc_test.go
  • pkg/cache/cache.go
  • pkg/cache/phantom_recovery_test.go
  • migrations/mysql/20260605045447_repair_url_none_xz_narinfos.sql

📝 Walkthrough

Summary by CodeRabbit

  • Bug Fixes

    • Resolved a NAR information desynchronization issue where URLs and compression indicators were incorrectly persisted in certain scenarios.
    • Applied forward-only database repair migrations across all supported platforms (SQLite, PostgreSQL, MySQL) to restore 127 affected records.
  • Tests

    • Updated cache layer tests to validate consistency between NAR information and actual storage state.
  • Documentation

    • Clarified specification and design documentation regarding URL normalization and persistence behavior.

Walkthrough

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

Changes

CDC narinfo URL/compression inconsistency resolution

Layer / File(s) Summary
Remove eager CDC store-time normalization
pkg/cache/cache.go
pullNarInfo normalization to Compression:none now applies only when upstream already reports none; removes earlier eager-CDC prediction branch. Comments document deferring none presentation to maybeCDCNormalizeNarInfoURL serve-time logic gated by HasNarInChunks.
Database repair migrations for inconsistent narinfos
migrations/mysql/20260605045447_repair_url_none_xz_narinfos.sql, migrations/postgres/20260605045447_repair_url_none_xz_narinfos.sql, migrations/sqlite/20260605045447_repair_url_none_xz_narinfos.sql
Three dialect-specific forward-only migrations identify narinfos with .nar URLs backed by whole-file XZ (total_chunks=0) without competing non-XZ/chunked backings, then rewrite URL to .nar.xz, set compression to xz, reconstruct file_hash and file_size from joined nar_files, and update updated_at. Down sections are non-rollback documentation.
CDC contract tests — truthful persistence and serve-time normalization
pkg/cache/cdc_test.go
testCDCPullNarInfoNormalizesCompression and testCDCPullNarInfoSetsFileSizeForCDC now initialize CDC chunker, serve real .nar.xz upstream bytes, assert stored Compression matches URL extension, validate FileHash/FileSize coherence by advertised compression, and verify GetNar reassembles correctly from the advertised URL.
Regression test: eager CDC does not prematurely normalize XZ URLs
pkg/cache/cdc_url_desync_prevention_internal_test.go
New TestPullNarInfo_EagerCDC_DoesNotPrematurelyNormalizeXzURL sets up eager CDC with lazy chunking and prefetch disabled, triggers a pull through missing-NAR guard, and asserts persisted narinfo retains .nar.xz URL and xz compression (no premature none normalization).
Phantom recovery test — use advertised narinfo URL
pkg/cache/phantom_recovery_test.go
testCDCBackingLessRecordRecoversAfterTransientFailure now parses advertised narinfo.URL for requests instead of hardcoding CompressionTypeNone, and asserts recovered/healed payloads equal full XZ-compressed bytes (xzContent) exactly rather than decompressed content.
Specifications and documentation updates
openspec/specs/cdc-chunking/spec.md, openspec/changes/archive/2026-06-05-prevent-cdc-narinfo-url-desync/design.md, openspec/changes/archive/2026-06-05-prevent-cdc-narinfo-url-desync/proposal.md, openspec/changes/archive/2026-06-05-prevent-cdc-narinfo-url-desync/specs/cdc-chunking/spec.md, openspec/changes/archive/2026-06-05-prevent-cdc-narinfo-url-desync/tasks.md, openspec/changes/archive/2026-06-05-prevent-cdc-narinfo-url-desync/.openspec.yaml
Add CDC narinfo URL normalization requirement and scenarios to main spec, introduce design and proposal docs explaining root cause (eager store-time none prediction before chunking completes) and fix (remove eager trigger, rely on compression truth and serve-time gating), add .openspec.yaml metadata, and update task checklist with migration repair and verification steps.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related issues

Possibly related PRs

  • kalbasit/ncps#1255: Implements the serve-time normalization (maybeCDCNormalizeNarInfoURL and HasNarInChunks gating) that complements this PR's store-time fix by handling the presentation of Compression:none only after chunking is confirmed.

Poem

🐰 No more eager guesses, compression stays true,
Store what upstream says until chunks come through.
Serve-time decides when to normalize the way,
Narinfos sync'd up to save the day! 🎯

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: fixing a CDC (Content-Defined Chunking) desynchronization issue between the URL and compression state of NARs, encompassing both prevention and repair.
Description check ✅ Passed The description comprehensively explains the root cause, prevention strategy, repair approach, and test plan—all directly related to the changeset's purpose of fixing the CDC narinfo URL/xz-NAR desynchronization.
Docstring Coverage ✅ Passed Docstring coverage is 83.33% 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 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.

@dosubot

dosubot Bot commented Jun 5, 2026

Copy link
Copy Markdown

Related Knowledge

1 document with suggested updates is ready for review.

kalbasit's Space

NAR File Download and Streaming
View 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:**
 

[Accept] [Edit] [Decline]

How did I do? Any feedback?  Join Discord

@kalbasit
kalbasit force-pushed the user/wnasreddine/cdc-url-desync-prevention branch 3 times, most recently from 64d30e0 to f114ec1 Compare June 5, 2026 17:59
@kalbasit
kalbasit force-pushed the user/wnasreddine/cdc-url-desync-prevention branch from f114ec1 to 97a8661 Compare June 5, 2026 19:07
@kalbasit
kalbasit force-pushed the user/wnasreddine/upload-presence-marker branch from b7e45dd to acd2f76 Compare June 5, 2026 19:08
@kalbasit
kalbasit force-pushed the user/wnasreddine/cdc-url-desync-prevention branch from 97a8661 to bbe3526 Compare June 5, 2026 19:08
Base automatically changed from user/wnasreddine/upload-presence-marker to main June 5, 2026 19:15
kalbasit and others added 4 commits June 5, 2026 19:15
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]>
@kalbasit
kalbasit force-pushed the user/wnasreddine/cdc-url-desync-prevention branch from bbe3526 to 0e73997 Compare June 5, 2026 19:15
@kalbasit
kalbasit enabled auto-merge (squash) June 5, 2026 19:15
@kalbasit
kalbasit merged commit 793d9c2 into main Jun 5, 2026
34 checks passed
@kalbasit
kalbasit deleted the user/wnasreddine/cdc-url-desync-prevention branch June 5, 2026 19:23
kalbasit added a commit that referenced this pull request Jun 5, 2026
…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]>
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
kalbasit added a commit that referenced this pull request Jun 7, 2026
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]>
kalbasit added a commit that referenced this pull request Jun 7, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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