Skip to content

fix(cache): serve a zstd request by recompressing CDC chunks - #1394

Merged
kalbasit merged 3 commits into
mainfrom
fix/serve-zstd-from-chunks
Jun 11, 2026
Merged

kalbasit merged 3 commits into
mainfrom
fix/serve-zstd-from-chunks

Conversation

@kalbasit

Copy link
Copy Markdown
Owner

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

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

Refs #1392

A client whose narinfo advertises Compression:zstd requests
/nar/<hash>.nar.zst, but under steady-state 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'. This is the inverse direction of the
narinfo<->nar_file compression desync (issue #1392) and the
counterpart to the merged uncompressed-serve fix (#1393); zstd is the
common upstream compression (cachix), so it 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 write-path-invariant and data-repair follow-ups.

Refs #1392

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

kalbasit commented Jun 11, 2026 •

Copy link
Copy Markdown
Owner Author

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

coderabbitai Bot commented Jun 11, 2026 •

Copy link
Copy Markdown

Review Change Stack

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: 5f53fc77-8480-474d-ae3f-bbc7ce695093

📥 Commits

Reviewing files that changed from the base of the PR and between 4d48899 and 8335944.

📒 Files selected for processing (1)
  • pkg/cache/cache.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/cache/cache.go

📝 Walkthrough

Summary by CodeRabbit

Release Notes

  • New Features

    • Server now automatically recompresses uncompressed archives to zstd format on-the-fly when requested, eliminating 404 errors and improving cache serving efficiency.
  • Documentation

    • Added comprehensive specification and design documentation detailing zstd recompression functionality and behavior.
  • Tests

    • Added regression tests to verify zstd recompression works correctly for chunked archives.

Walkthrough

Implements on-the-fly zstd recompression for NAR serving: when a request advertises Compression: zstd but the store holds only uncompressed CDC chunks, the system reassembles and recompresses bytes to zstd via a pooled writer over io.Pipe. Other unsupported compressions return not-found to enable upstream fallback. Includes spec, implementation, and regression test.

Changes

NAR Zstd Recompression via On-Demand Streaming

Layer / File(s) Summary
Specification and Design Documentation
openspec/specs/nar-serving-recompression/spec.md, openspec/changes/archive/2026-06-10-serve-compressed-nar-via-zstd-recompression/design.md, openspec/changes/archive/2026-06-10-serve-compressed-nar-via-zstd-recompression/proposal.md, openspec/changes/archive/2026-06-10-serve-compressed-nar-via-zstd-recompression/specs/nar-serving-recompression/spec.md, openspec/changes/archive/2026-06-10-serve-compressed-nar-via-zstd-recompression/tasks.md, openspec/changes/archive/2026-06-10-serve-compressed-nar-via-zstd-recompression/.openspec.yaml
Defines requirement and design for serving Compression: zstd by on-the-fly recompression of uncompressed CDC chunks, including acceptance criteria, scenarios (zstd from chunks, unchanged none requests, not-found fallback), trade-offs (unknown length, bounded CPU), and a TDD implementation plan.
Cache Serving Implementation: Zstd Recompression Path
pkg/cache/cache.go
serveNarFromStorageViaPipe now routes Compression: zstd requests from chunk storage to a new serveZstdFromChunks helper which reassembles uncompressed CDC chunks via getNarFromChunks and recompresses them to zstd on-the-fly through io.Pipe and zstd.NewPooledWriter, returning size -1. Other non-zstd compressed requests return a wrapped not-found to trigger upstream fallback.
Regression Test: Zstd Request from Chunks
pkg/cache/serve_zstd_from_chunks_internal_test.go
TestServeZstdRequestFromChunks verifies that a NAR stored only as uncompressed CDC chunks can be served as Compression: zstd on demand, asserting successful retrieval, correct zstd labeling in returned narinfo, and successful round-trip decompression to original NAR bytes.

Sequence Diagram

sequenceDiagram
  participant Client
  participant serveNarFromStorageViaPipe
  participant serveZstdFromChunks
  participant getNarFromChunks
  participant ChunkStorage
  participant ZstdWriter

  Client->>serveNarFromStorageViaPipe: Request Compression: zstd
  serveNarFromStorageViaPipe->>serveNarFromStorageViaPipe: Check if serving from chunks
  serveNarFromStorageViaPipe->>serveZstdFromChunks: Route zstd request
  serveZstdFromChunks->>getNarFromChunks: Read uncompressed chunk bytes
  getNarFromChunks->>ChunkStorage: Fetch CDC chunks
  ChunkStorage-->>getNarFromChunks: Uncompressed NAR bytes
  getNarFromChunks-->>serveZstdFromChunks: Stream uncompressed data
  serveZstdFromChunks->>ZstdWriter: Pipe bytes through pooled writer
  ZstdWriter-->>serveZstdFromChunks: Zstd-compressed stream
  serveZstdFromChunks-->>Client: Return zstd stream with size=-1
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related issues

Possibly related PRs

Suggested labels

bug, merge-stack

Poem

A rabbit hops through chunks of code so neat,
Reassembling bytes to make zstd complete. 🐇
Through pipes and pooled writers the stream does flow,
From scattered chunks to compressed glow. ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically describes the main change: serving zstd-compressed NAR requests by recompressing CDC chunks on-the-fly.
Description check ✅ Passed The description thoroughly explains the problem (404 when zstd is requested but only uncompressed chunks exist), the solution (recompress on-the-fly), scope (zstd only), and test coverage, 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.

✨ 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 implements on-the-fly zstd recompression when serving NARs that are only available as uncompressed CDC chunks, preventing 404 errors for clients requesting zstd-compressed NARs. The feedback suggests using a defer block in the recompression goroutine to ensure that both the zstd writer and the raw reader are safely closed, preventing resource leaks in case of panics or early exits.

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
Move encoder/reader/pipe teardown into a single deferred block so an
unexpected early exit or panic in io.Copy still returns the pooled zstd
encoder, closes the chunk reader, and closes the pipe (preventing a
consumer hang). PooledWriter.Close is idempotent.

Addresses PR #1394 review thread PRRT_kwDONV6tZs6Ip9A-.

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

Copy link
Copy Markdown
Owner Author

Good catch — fixed in the latest push. Adopted the defer-based teardown, with one improvement over the suggestion: pipeWriter.CloseWithError(...) is now inside the defer too, so a panic in io.Copy also closes the pipe and the consumer never hangs (the suggested version left the pipe close outside the defer). PooledWriter.Close is idempotent, so the single close in the defer is sufficient.

The recompressed zstd does not byte-match the origin, so its
FileHash/FileSize differ from the client's narinfo. Document why Nix
tolerates this: the signature fingerprint excludes
FileHash/FileSize/Compression/URL, narFromPath never verifies FileHash
(producer-only) and uses FileSize only for progress, and integrity is
the signed NarHash verified after decompression (our stream decompresses
to the identical NAR). Pre-empts the recurring 'won't this break the
client's recorded FileHash?' question.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@kalbasit
kalbasit enabled auto-merge (squash) June 11, 2026 06:23
@codecov

codecov Bot commented Jun 11, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 0.00%. Comparing base (68cf7d4) to head (8335944).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@     Coverage Diff      @@
##   main   #1394   +/-   ##
============================
============================

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@kalbasit
kalbasit merged commit 5568a18 into main Jun 11, 2026
70 of 73 checks passed
@kalbasit
kalbasit deleted the fix/serve-zstd-from-chunks branch June 11, 2026 06:25
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 11, 2026
…1396)

## Summary

Stacked on #1394 / the data-repair PR. A live cache accumulated ~5.5M
orphaned chunk rows and ~8164 `nar_file_chunks` links while **zero**
nar_files have `total_chunks > 0`. fsck's orphaned-chunk reclamation
only deletes chunks with NO link, so chunks held by a stale link to a
dechunked (`total_chunks = 0`) nar_file are never orphaned and never
reclaimed; `collectNarFilesWithChunkIssues` only inspects `total_chunks
> 0` rows, so the stale links escape there too. The residue grows
unbounded.

Add `reclaimStaleChunkLinks`, invoked from `repairFsckIssues` under
`--repair` + CDC mode (which #1364's chunk-residue signal already
enables post-drain): delete `nar_file_chunks` whose parent nar_file is
dechunked and not actively chunking, then reclaim the chunks left with
no remaining links (DB rows + chunk-store blobs). Chunks shared with a
still-chunked nar_file keep a live link and are retained; chunked NARs
are untouched; idempotent.

## Test plan

- [x] New `TestReclaimStaleChunkLinks`: stale link + its chunk
reclaimed; shared chunk and chunked NAR retained; idempotent.
- [x] `task fmt`/`lint` green; targeted fsck tests pass.

Refs #1392

---------

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

enhancement New feature or request 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