Skip to content

fix(cache): serve uncompressed NAR from any stored whole-file compression - #1393

Merged
kalbasit merged 2 commits into
mainfrom
fix/narinfo-nar-compression-desync-serve
Jun 10, 2026
Merged

kalbasit merged 2 commits into
mainfrom
fix/narinfo-nar-compression-desync-serve

Conversation

@kalbasit

Copy link
Copy Markdown
Owner

Summary

Fixes the production error: file 'nar/<hash>.nar' does not exist in binary cache (and Lzma: No progress is possible) failures that abort nix builds even though the NAR bytes are present locally.

Root cause — narinfo↔nar_file compression desync on the serve path. A NAR whose narinfo advertises Compression: none can be physically stored whole-file as .nar.xz. The serve path (getNarFromStore / statNarInStore) only ever transparently decompressed a stored .nar.zst for a none request — never .nar.xz — so it reported the NAR absent and 404'd / re-downloaded. With the upstream missing or unhealthy the client saw "does not exist in binary cache".

The drift is generated by CDC (which normalizes narinfos to Compression: none) and left as residue after CDC is disabled and NARs re-download at the upstream's compression. It is CDC-state-independent — reproduced both after converting a cache CDC on→off and on a steady-state CDC deployment.

Evidence. DB inspection of the live cache found ~259 drifted narinfo/nar_file pairs (none|xz 110, none|zstd 90, xz|none 53, xz|zstd 6); every client-reported failing hash was narinfo=none / stored=xz.

What changed

  • New wholeFileServeCompressions() helper ([zstd, xz], preference order).
  • getNarFromStore: for a Compression: none request, find whichever supported whole-file compression is stored and decompress it transparently via nar.DecompressReader; the served stream is labeled none; transparent-zstd pass-through stays gated on the stored file being zstd.
  • statNarInStore: the existence check reports present when any servable whole-file compression is on disk.
  • LRU touch follows the bytes actually served — touches the stored compression's nar_file row instead of synthesizing a spurious none row; healing only when no row exists.

Covers the dominant direction (none advertised / compressed stored).

Scope / follow-ups

Deferred (tracked in #1392): the inverse direction (narinfo advertises xz/zstd while stored uncompressed or as chunks — needs serve-time re-compression), a one-shot data repair of existing drifted pairs, and a write-path invariant keeping a narinfo's advertised compression equal to a servable representation.

Distinct from the closed #1329 (opaque/UUID nar-url parsing).

Closes #1392

Test plan

  • New proving test TestServeNoneRequestFromXzWholeFile (RED→GREEN): store a NAR whole-file as .nar.xz, no upstream, request it as Compression: none → served decompressed; no spurious none row created.
  • TestCDCWholeFileServeReportsServedCompression and all TestGetNar* still pass.
  • task fmt, task lint, task test all green.

A NAR whose narinfo advertises Compression:none can be physically
stored whole-file as .nar.xz (the narinfo<->nar_file compression
desync: CDC normalizes narinfos to none, and the drift is left as
residue after CDC is disabled and NARs re-download at the upstream's
compression). The serve path only ever transparently decompressed a
stored .nar.zst for a none request, never .nar.xz, so it reported the
NAR absent and returned 404 / re-downloaded even though the bytes were
present locally. With the upstream missing or unhealthy the client saw
'does not exist in binary cache', aborting nix builds. DB inspection of
the live cache found ~259 drifted narinfo/nar_file pairs.

Generalize the existing zstd transparent-decompress convention to any
supported stored whole-file compression via wholeFileServeCompressions()
in both statNarInStore (existence) and getNarFromStore (serve): resolve
the NAR by hash, decompress the stored whole file to satisfy a none
request, label the served stream none, and touch the row matching the
bytes actually served rather than synthesizing a spurious none row.

Covers the dominant direction (none advertised / compressed stored).
The inverse direction (advertise xz/zstd, stored uncompressed/chunked,
needs serve-time re-compression), a data repair of existing drifted
pairs, and a write-path invariant are deferred follow-ups.

Refs #1392

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

kalbasit commented Jun 10, 2026 •

Copy link
Copy Markdown
Owner Author

This change is part of the following stack:

Change managed by git-spice.

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

coderabbitai Bot commented Jun 10, 2026 •

Copy link
Copy Markdown

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 5 minutes and 10 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: 6d3edabf-4753-4b2a-b345-1f16230c16b9

📥 Commits

Reviewing files that changed from the base of the PR and between 0bd82a3 and efb0a8e.

📒 Files selected for processing (2)
  • pkg/cache/cache.go
  • pkg/cache/narinfo_nar_compression_desync_serve_internal_test.go
📝 Walkthrough

Walkthrough

This PR introduces a fix for narinfo↔nar_file compression desynchronization in the NAR serving path. It enables clients requesting Compression: none to be served transparently decompressed whole-file NAR artifacts from any locally stored compressed representation (zstd or xz), eliminating false 404s and avoiding unnecessary re-downloads when only a compressed variant is cached.

Changes

NAR compression desync fix

Layer / File(s) Summary
Specification and design documentation
openspec/changes/archive/2026-06-10-fix-narinfo-nar-compression-desync-serve/{.openspec.yaml,design.md,proposal.md,specs/*}, openspec/specs/nar-serving-compression-fallback/spec.md, openspec/changes/archive/2026-06-10-fix-narinfo-nar-compression-desync-serve/tasks.md
Requirements and implementation plan defining transparent decompression for Compression: none requests from any stored whole-file compression (zstd or xz), correct presence checking, decompression labeling, LRU/last-accessed tracking tied to actual served representation, and regression test scenarios.
NAR serving implementation with transparent decompression
pkg/cache/cache.go (helper function, whole-file selection, decompression switch, DB touch/heal)
getNarFromStore adds a helper to list candidate compressions, probes stored representations in preference order (zstd, then xz), conditionally decompresses based on stored vs. requested compression, correctly sets response compression and Content-Length, and touches the nar_file row corresponding to the actual served representation (with fallback healing when the served representation row is missing).
Presence checking for multiple compression representations
pkg/cache/cache.go (statNarInStore)
statNarInStore updated to iterate through same candidate stored compressions for Compression: none, reporting presence when any candidate exists locally instead of only checking zstd.
Regression test for compression desync serving
pkg/cache/narinfo_nar_compression_desync_serve_internal_test.go
TestServeNoneRequestFromXzWholeFile verifies GetNar serves a stored .nar.xz as decompressed when requested with Compression: none, validates correct response compression labeling, matching decompressed content, and nar_file persistence without creating spurious none entries.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related issues

Possibly related PRs

  • kalbasit/ncps#1346: Both PRs update getNarFromStore in pkg/cache/cache.go to ensure the served NAR's Compression/Content-Length and nar_file touch correspond to the exact stored representation actually streamed, fixing compression-mismatch desync under different scenarios.

Suggested labels

bug, go, size:L

Poem

🐰 A bunny's cache was quite out of sync,
Storing xz where zstd once would link.
With decompression on request, we're freed—
Now "none" gets served, whatever the seed!
No 404s when the bytes reside,
Just honest decompression with transparent pride.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately and concisely describes the main change: serving uncompressed NARs from any stored whole-file compression format.
Description check ✅ Passed The description is directly related to the changeset, explaining the root cause, what changed, and the rationale for the fix.
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 resolves a compression desync issue where clients requesting uncompressed (none) NARs receive 404 errors or trigger unnecessary downloads because the physical file is stored under a different compression (e.g., .nar.xz). The changes generalize the serve and existence check paths to transparently decompress any supported stored whole-file compression. Feedback on the changes suggests simplifying the LRU touch logic by directly querying and updating the row of the actual stored compression (storedComp) rather than conditionally falling back to it.

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

@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 3661-3673: The delete/GC path must mirror the new whole-file
fallback list so XZ blobs aren't leaked: update deleteNarBytes (the function
called by DeleteNar/purge/LRU) to iterate the same candidates returned by
wholeFileServeCompressions() when attempting to delete stored whole-file NAR
variants (not just .nar.zst), attempt deletion for each candidate, and treat
storage.ErrNotFound as non-fatal while aggregating/reporting other errors;
ensure DeleteNar continues to return storage.ErrNotFound only if none of the
candidate blobs exist and preserve existing DB row removal semantics.
🪄 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: ab48f0ed-68d5-4c9e-a985-fd234d58058c

📥 Commits

Reviewing files that changed from the base of the PR and between ce0e63b and 0bd82a3.

📒 Files selected for processing (8)
  • openspec/changes/archive/2026-06-10-fix-narinfo-nar-compression-desync-serve/.openspec.yaml
  • openspec/changes/archive/2026-06-10-fix-narinfo-nar-compression-desync-serve/design.md
  • openspec/changes/archive/2026-06-10-fix-narinfo-nar-compression-desync-serve/proposal.md
  • openspec/changes/archive/2026-06-10-fix-narinfo-nar-compression-desync-serve/specs/nar-serving-compression-fallback/spec.md
  • openspec/changes/archive/2026-06-10-fix-narinfo-nar-compression-desync-serve/tasks.md
  • openspec/specs/nar-serving-compression-fallback/spec.md
  • pkg/cache/cache.go
  • pkg/cache/narinfo_nar_compression_desync_serve_internal_test.go

Comment thread pkg/cache/cache.go Resolved
Widening the serve/existence fallback to .nar.xz (statNarInStore,
getNarFromStore) made a drifted none->xz NAR report present, but the
delete/GC path (DeleteNar, deleteNarBytes) still only removed the
.nar.zst variant. A none NAR backed only by .nar.xz would therefore
return ErrNotFound on delete, or purge/LRU would drop the DB row while
leaking the xz blob on disk.

Iterate wholeFileServeCompressions() in both delete sites so delete
mirrors the serve fallback. Adds TestDeleteNoneDeletesXzWholeFile.

Addresses PR #1393 review thread PRRT_kwDONV6tZs6IorjU.

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

Copy link
Copy Markdown
Owner Author

Thanks for the reviews — addressed:

CodeRabbit (delete/GC symmetry, PRRT_kwDONV6tZs6IorjU): valid catch, fixed in efb0a8e. DeleteNar and deleteNarBytes now iterate wholeFileServeCompressions() so a drifted none→xz NAR's .nar.xz blob is deleted rather than leaked (and DeleteNar no longer returns ErrNotFound for it). Added TestDeleteNoneDeletesXzWholeFile.

Gemini (always touch storedComp row, PRRT_kwDONV6tZs6IooOT): not applying — it would regress the canonical case. An uncompressed (Compression: none) NAR is physically stored as .nar.zst but its nar_file row is compression=none (with bytes_stored_at set); there is no zstd row. Always touching storedComp (= zstd) would miss the existing none row and trigger a spurious heal on every uncompressed serve. The current logic touches the served-representation (none) row when it exists and falls back to the stored compression's row only for the desync case (none requested, only an xz row exists), which is the correct behavior. Covered by TestServeNoneRequestFromXzWholeFile (asserts no spurious none row is created).

@kalbasit
kalbasit merged commit 68cf7d4 into main Jun 10, 2026
45 of 57 checks passed
@kalbasit
kalbasit deleted the fix/narinfo-nar-compression-desync-serve branch June 10, 2026 23:11
kalbasit added a commit that referenced this pull request Jun 11, 2026
After the serve-side fixes (#1393, serve-zstd-from-chunks) ncps
tolerates most narinfo<->nar_file compression drift at serve time by
transcoding. The one case it still cannot serve is a narinfo
advertising a compression ncps has no compressor for (xz) whose
backing NAR is stored under a different compression (none/zstd/chunks)
-- ~59 such pairs on the live cache. These pre-existing drifted rows
cannot be healed at request time, so they need a one-shot data repair.

Add repairNarInfoCompressionDesync, invoked from repairFsckIssues under
--repair: find narinfos advertising xz with no matching xz nar_file but
a backing non-xz nar_file, and rewrite each to the servable none form
(URL nar/<hash>.nar, Compression: none, FileHash/FileSize cleared),
reusing the advertised hash so the resolve-by-hash serve path (#1393)
decompresses the stored bytes. Healthy narinfos are untouched and the
repair is idempotent.

Refs #1392

Co-Authored-By: Claude Opus 4.8 <[email protected]>
kalbasit added a commit that referenced this pull request Jun 11, 2026
After the serve-side fixes (#1393, serve-zstd-from-chunks) ncps
tolerates most narinfo<->nar_file compression drift at serve time by
transcoding. The one case it still cannot serve is a narinfo
advertising a compression ncps has no compressor for (xz) whose
backing NAR is stored under a different compression (none/zstd/chunks)
-- ~59 such pairs on the live cache. These pre-existing drifted rows
cannot be healed at request time, so they need a one-shot data repair.

Add repairNarInfoCompressionDesync, invoked from repairFsckIssues under
--repair: find narinfos advertising xz with no matching xz nar_file but
a backing non-xz nar_file, and rewrite each to the servable none form
(URL nar/<hash>.nar, Compression: none, FileHash/FileSize cleared),
reusing the advertised hash so the resolve-by-hash serve path (#1393)
decompresses the stored bytes. Healthy narinfos are untouched and the
repair is idempotent.

Refs #1392

Co-Authored-By: Claude Opus 4.8 <[email protected]>
kalbasit added a commit that referenced this pull request Jun 11, 2026
## Summary

Inverse direction of the merged uncompressed-serve fix (#1393) and the
steady-state-CDC manifestation of the narinfo↔nar_file compression
desync (#1392). A client whose narinfo advertises `Compression: zstd`
requests `/nar/<hash>.nar.zst`, but under CDC the NAR is stored only as
uncompressed chunks. `serveNarFromStorageViaPipe` returned `404` ("only
available as chunks, cannot serve as zstd"), aborting the build with
`does not exist in binary cache`. zstd is the common upstream
compression (cachix), so this blocks CDC-on caches.

Recompress on the fly: reassemble the uncompressed chunks via
`getNarFromChunks` and stream them through `zstd.NewPooledWriter` into
an `io.Pipe` (mirroring the existing none→zstd store path), serving a
`zstd`-labeled response. Scoped to zstd, the one streaming compressor
ncps vendors; `xz` (no compressor) keeps the 404/fallback and is handled
by the data-repair PR stacked on top.

## Test plan

- [x] New `TestServeZstdRequestFromChunks` (RED→GREEN): chunk a NAR
under CDC, request it as `zstd`, assert the served stream decompresses
to the original (was 404).
- [x] Existing `TestGetNar*` / CDC serve tests pass; `task
fmt`/`lint`/`test` green.

Refs #1392

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
kalbasit added a commit that referenced this pull request Jun 11, 2026
After the serve-side fixes (#1393, serve-zstd-from-chunks) ncps
tolerates most narinfo<->nar_file compression drift at serve time by
transcoding. The one case it still cannot serve is a narinfo
advertising a compression ncps has no compressor for (xz) whose
backing NAR is stored under a different compression (none/zstd/chunks)
-- ~59 such pairs on the live cache. These pre-existing drifted rows
cannot be healed at request time, so they need a one-shot data repair.

Add repairNarInfoCompressionDesync, invoked from repairFsckIssues under
--repair: find narinfos advertising xz with no matching xz nar_file but
a backing non-xz nar_file, and rewrite each to the servable none form
(URL nar/<hash>.nar, Compression: none, FileHash/FileSize cleared),
reusing the advertised hash so the resolve-by-hash serve path (#1393)
decompresses the stored bytes. Healthy narinfos are untouched and the
repair is idempotent.

Refs #1392

Co-Authored-By: Claude Opus 4.8 <[email protected]>
kalbasit added a commit that referenced this pull request Jun 11, 2026
…1395)

## Summary

Stacked on #1394. After the serve-side fixes (#1393, #1394) ncps
tolerates most narinfo↔nar_file compression drift at serve time by
transcoding. The one case it still cannot serve is a narinfo advertising
a compression ncps has no compressor for (`xz`) whose backing NAR is
stored otherwise (none/zstd/chunks) — ~59 such pairs on the live cache.
These pre-existing drifted rows cannot be healed at request time, so
they need a one-shot data repair.

Add `repairNarInfoCompressionDesync`, invoked from `repairFsckIssues`
under `--repair`: find narinfos advertising `xz` with no matching `xz`
nar_file but a backing non-xz nar_file, and rewrite each to the servable
`none` form (`URL: nar/<hash>.nar`, `Compression: none`,
`FileHash`/`FileSize` cleared), reusing the advertised hash so the
resolve-by-hash serve path (#1393) decompresses the stored bytes.
Healthy narinfos are untouched; the repair is idempotent.

## Test plan

- [x] New `TestRepairNarInfoCompressionDesync`: a desynced
xz-advertised/none-stored narinfo is rewritten to none; a healthy xz/xz
pair is untouched; a second run is a no-op.
- [x] `task fmt`/`lint` green; targeted fsck tests pass.

Refs #1392

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
kalbasit added a commit that referenced this pull request Jun 23, 2026
## Summary

Fixes the `e2e-nightly` kubernetes leg, which has failed every scheduled
run since 2026-06-11 on the CDC scenarios (`single-s3-postgres-cdc`,
`ha-s3-postgres-cdc`, `ha-s3-postgres-cdc-lifecycle`) with `PostgreSQL
database is empty (0 chunks)`.

**Root cause (confirmed via local Kind e2e + pod logs + bucket-empty
proof):** the kubernetes harness isolates a database per scenario but
shared a single Garage bucket (`ncps-bucket`) across every scenario and
never cleaned it. Earlier non-CDC scenarios reuse the same test narinfo
hashes and leave whole-file `.nar.xz` objects in `store/nar/`. When a
CDC scenario then runs with a fresh database against that dirty bucket,
ncps (since #1393 treats a stored `.nar.xz` as a present
`Compression:none` NAR) sees the residual whole file as already present,
**skips the upstream download + eager chunking**, and
`BackgroundMigrateNarToChunks` fails with `error fetching nar from
store: not found` — so zero chunk rows are created and validation fails.
Pre-#1393 the path only checked `.nar.zst`, missed the residual,
re-downloaded and eager-chunked (the last green run produced 4 chunks).
`cdc-lifecycle` passes because it uses local per-pod storage with no
shared residue.

## What changed (test harness only — no ncps / chart / CDC behavior
change)

- `harness_config.scenario_bucket_name()` — single source of truth
deriving `ncps-<scenario>`.
- `config.nix` — each scenario's generated Helm values use its own
bucket.
- `k8s_tests.py` — garage setup creates + grants a bucket per S3
scenario (idempotent); test-config carries the per-scenario bucket.
- `k8s_tests_tester.py` — S3 storage validation reads the per-scenario
bucket.

A per-scenario **bucket** (not prefix) isolates the NAR, narinfo,
**and** chunk stores at once — the chunk store ignores the configured S3
prefix, so a per-scenario prefix would leave chunks colliding.

## Test plan

- [x] `nix eval` confirms each S3 scenario renders a distinct
`ncps-<name>` bucket; local scenarios get none
- [x] New harness unit test (`test_s3_bucket_isolation.py`);
`e2e-harness-unit` net green (66 passed)
- [x] `task fmt`, `task lint`, `task test` (0 failures) green
- [x] Live Kind run: `single-s3-postgres` (non-CDC) then all three CDC
scenarios → **4/4 pass, 4 chunks each** (cross-scenario isolation
proven)
- [ ] `e2e-nightly` `workflow_dispatch` on this branch goes green
(kubernetes leg)

---------

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

Projects

None yet

1 participant