Repository navigation
fix(cache): fix compression mismatch in CDC lazy-chunking - #1255
Conversation
|
This change is part of the following stack: Change managed by git-spice. |
|
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:
📝 WalkthroughWalkthroughAdds an in-memory CDC normalization helper and tighter runtime guards: GetNarInfo will present completed CDC chunked NARs as Compression=none (clearing FileHash/FileSize) and requests for non-none compression are rejected if only chunks exist. Tests cover normalization and chunk/whole-file serving transitions. ChangesCDC narinfo compression normalization & chunk serving guards
Sequence Diagram(s)sequenceDiagram
participant Client
participant CacheHandler
participant DB
participant Storage
Client->>CacheHandler: GET /narinfo or GET /nar (narURL)
CacheHandler->>DB: HasNarInChunks(narURL)
DB-->>CacheHandler: TotalChunks (0 or >0)
alt TotalChunks > 0 and request compression == none
CacheHandler->>Storage: stream chunks -> Client
else TotalChunks > 0 and request compression != none
CacheHandler-->>Client: return storage.ErrNotFound
else TotalChunks == 0
CacheHandler->>Storage: serve whole-file (if present) -> Client
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
pkg/cache/cache_test.go (1)
2907-2909: ⚡ Quick winBreak these long
t.Runcalls across lines to satisfylll.These additions are likely to trip strict line-length linting; please split each call into multiline form.
As per coding guidelines, "Break long lines (especially function calls) into multiple lines to comply with the
llllinter".🤖 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_test.go` around lines 2907 - 2909, The three long t.Run calls should be split across multiple lines to satisfy the lll linter: break each t.Run("GetNarInfo_CDCNormalizesCompressionWhenChunked", testGetNarInfoCDCNormalizesCompressionWhenChunked(factory)) (and the two siblings testGetNarInfoCDCNoNormalizationWhenNotChunked(factory) and testGetNarInfoCDCDisabledNoNormalization(factory)) into a multi-line call form with the name string on one line and the test function invocation on the following line (or equivalent indentation) so each line length is under the linter limit.
🤖 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_test.go`:
- Around line 3827-3835: The test currently seeds a NarInfo without file
metadata so the "cleared" assertion is non‑proving; when creating the seeded row
via the NarInfo builder (the dbClient.Ent().NarInfo.Create() chain that sets
Hash/URL/Compression/StorePath/NarHash/NarSize), also SetFileHash to a non-empty
string and SetFileSize to a non-zero value so there is real metadata to be
cleared; then call the existing GetNarInfo helper and assert that returned
FileHash is empty/nil and FileSize is zero. Apply the same change for the other
seed at the later occurrence referenced in the comment (around the other NarInfo
Create call).
---
Nitpick comments:
In `@pkg/cache/cache_test.go`:
- Around line 2907-2909: The three long t.Run calls should be split across
multiple lines to satisfy the lll linter: break each
t.Run("GetNarInfo_CDCNormalizesCompressionWhenChunked",
testGetNarInfoCDCNormalizesCompressionWhenChunked(factory)) (and the two
siblings testGetNarInfoCDCNoNormalizationWhenNotChunked(factory) and
testGetNarInfoCDCDisabledNoNormalization(factory)) into a multi-line call form
with the name string on one line and the test function invocation on the
following line (or equivalent indentation) so each line length is under the
linter limit.
🪄 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: e1521010-a7f2-427b-88b5-00490ea6f7c0
📒 Files selected for processing (2)
pkg/cache/cache.gopkg/cache/cache_test.go
There was a problem hiding this comment.
Code Review
This pull request introduces in-memory normalization of narinfo URLs and compression settings when Content-Defined Chunking (CDC) is enabled and a NAR has already been migrated to chunks. This change addresses a race condition where GetNarInfo might return stale compression metadata while the data is served uncompressed from chunks, which previously caused Nix to fail. The implementation includes the maybeCDCNormalizeNarInfoURL helper and comprehensive unit tests covering various CDC states. I have no feedback to provide.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #1255 +/- ##
=====================================
Coverage 4.86% 4.86%
=====================================
Files 6 6
Lines 452 452
=====================================
Hits 22 22
Misses 426 426
Partials 4 4 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
In lazy CDC deployments, GetNarInfo returns a stale "Compression: xz" narinfo while migrateNarToChunksCleanup updates the DB asynchronously. During this window, GetNar detects the NAR is in chunks and serves uncompressed data, while Nix expects xz — producing "input compression not recognized". Fix by calling HasNarInChunks synchronously in GetNarInfo whenever a non-none compression narinfo is fetched from the DB with CDC enabled. If chunks already exist, normalize URL and Compression to none in-memory before returning, eliminating the race window. The async DB update via migrateNarToChunksCleanup is unchanged — it reduces future query overhead once the narinfo is fixed in DB. The normalization is extracted into maybeCDCNormalizeNarInfoURL to keep GetNarInfo's nesting within lint limits. Narinfo signing fingerprints cover StorePath/NarHash/NarSize/References — not URL or Compression — so no re-signing is needed. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
When CDC chunking finishes, the .nar.xz whole-file is deleted and only uncompressed chunks remain. Nix clients with a locally cached .nar.xz narinfo continue to request the xz URL directly without re-fetching. Previously, serveNarFromStorageViaPipe detected the Compression=none nar_file record via CDC fallback and routed to getNarFromChunks, sending raw uncompressed bytes to a client expecting xz data, causing \"input compression not recognized\". Fix: only promote hasInStore to serveFromChunks when the request asks for Compression=none. When only chunks remain and the client wants xz, return storage.ErrNotFound so Nix falls back to the upstream cache and retrieves the original compressed file. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
2e568c8 to
4300f36
Compare
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 6515-6522: The code is calling HasNarInChunks with the raw narURL
which can differ from the key used when storing rows (storeInDatabase uses
narURL.Normalize()), so normalize the URL first and use that normalized URL for
the chunk existence check; in practice, call narURL.Normalize() (or use the same
normalized variable produced by maybeCDCNormalizeNarInfoURL) and pass the
normalized URL into HasNarInChunks and into the subsequent noneURL construction
so GetNarInfo returns the correct, de-duplicated narinfo for
prefixed/nix-serve-style URLs.
🪄 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: ad076a46-4825-4763-a5ec-d1d1e3cac452
📒 Files selected for processing (2)
pkg/cache/cache.gopkg/cache/cache_test.go
Without lazy chunking, MigrateNarToChunks detects TotalChunks>0 and calls migrateNarToChunksCleanup, which deletes the xz whole-file from narStore. This creates a race with getNarFromStore, causing sporadic "not found" failures in CI under parallel load. The transition period where both the xz file and CDC chunks coexist only occurs in lazy-chunking deployments (immediate deletion is skipped). Enabling lazy chunking in the test is therefore also semantically correct. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
maybeCDCNormalizeNarInfoURL was passing the raw narURL to HasNarInChunks; nix-serve-style prefixed hashes (e.g. "abc-hash") would never match nar_file rows, which store normalized hashes. Call narURL.Normalize() first so the lookup is hash-format-agnostic. Also seed FileHash/FileSize on the NarInfo.Create() in the CDC normalization test so the nil/0 assertions are non-trivial and actually prove the in-memory normalization cleared those fields.
Document the two behaviors added by the compression-not-recognized fix: - GetNarInfo normalizes Compression/URL in-memory during the transition window when the NAR is already chunked but the DB record still shows xz - GetNar returns 404 for compressed URLs when the NAR exists only as CDC chunks, preventing "input compression not recognized" from Nix clients
|
Documentation Updates 1 document(s) were updated by changes in this PR: NAR File Download and StreamingView Changes@@ -270,8 +270,21 @@
**Serving Logic:**
When CDC is enabled and a NAR is requested, the system checks the `nar_file` record:
-- If `total_chunks > 0`: Serve from CDC chunks for optimal performance and deduplication
+- If `total_chunks > 0` AND the request is for `Compression=none`: Serve from CDC chunks for optimal performance and deduplication
- If `total_chunks = 0`: Serve the raw compressed NAR from storage while background workers perform chunking
+
+Chunks are always stored uncompressed. If a client requests a compressed NAR (e.g., `.nar.xz`) but only chunks exist in storage (the whole-file has been deleted), `GetNar` returns `ErrNotFound` to allow the client to fall back to an upstream cache that still has the original compressed file. This prevents "input compression not recognized" errors that would occur if the system served raw uncompressed chunk data to a client expecting compressed data.
+
+#### 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.
+
+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
+- 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:**
|
## Summary Closes the remaining gaps behind the "phantom nar_file" defect — permanent `error: file 'nar/<hash>.nar.xz' does not exist` 404s for paths whose narinfo was just served. A backing-less `nar_file` row (`total_chunks=0`, `chunking_started_at=NULL`) left by a failed background download was treated as servable and short-circuited `GET /nar` to a terminal 404. Prior PRs (#1255–#1290) fixed the core read path; this hardens the edges and prevents the recurring regression. - **Upstream retry (D5):** extend GET/HEAD retry beyond `GOAWAY` to also cover `http2: timeout awaiting response headers`, connection reset, and broken pipe via `isRetriableTransportError`. Genuine 404s return a response (not a transport error) and stay non-retryable. - **Single source of truth (D1):** unify the duplicated, drift-prone servability checks in `GetNar` and `prePullNar`'s `hasAsset` behind one `isServable()` predicate (+ `narFileServable()`), so a placeholder row is never servable and the regression can't return via divergent checks. Behavior-preserving. - **Recovery sweep:** `runCDCLazyRecovery` now skips backing-less stuck rows. `BackgroundMigrateNarToChunks` can only chunk a store-present NAR, so re-driving placeholder/genuinely-absent rows every interval was futile `error fetching nar from store: not found` spam that indefinitely retried unmigratable hashes. Such rows are recovered on demand by `GetNar`. No schema migration. OpenSpec change `fix-phantom-nar-cache-miss` archived and its delta specs synced into `openspec/specs/`. ## Test plan - [x] `task fmt` clean; changed packages lint clean - [x] `task test` green (all packages; `pkg/cache` + `pkg/cache/upstream` under `-race`) - [x] `phantom_recovery_test.go` — reproduces narinfo 200 → failed download → recovery on next request, plus the genuine-404 path - [x] `transient_retry_test.go` — new retriable errors retried; genuine 404 not retried - [x] `recovery_skip_internal_test.go` — sweep skips backing-less rows, re-drives store-present ones (RED→GREEN verified) --------- Co-authored-by: Claude Opus 4.8 <[email protected]>
#1375) The coordination poll loop called hasFinishedAsset then hasAsset on every 200ms tick, each repeating HasNarInStore (a storage stat / S3 HEAD) and the nar_file lookup — redundant I/O and DB load under contention. Extract one oracle, narServability(ctx, narURL) (servable, finished, err), and have isServable and hasFinishedNar both delegate to it (preserving the single-source-of-truth that prevents the divergent-check regressions #1255/#1263/#1279/#1290). Collapse coordinateDownload / pollForDownloadOrTakeOver from two predicate closures to one checkAsset(ctx) (servable, finished); the tick now computes both states in a single call. Behavior is unchanged (full -race suite green). Resolves threads PRRT_kwDONV6tZs6H_WfI, _WfM, _WfP, _WfR, _WfW, _Wfa, _Wfc, _Wfn, _Wfo.
#1375) The coordination poll loop called hasFinishedAsset then hasAsset on every 200ms tick, each repeating HasNarInStore (a storage stat / S3 HEAD) and the nar_file lookup — redundant I/O and DB load under contention. Extract one oracle, narServability(ctx, narURL) (servable, finished, err), and have isServable and hasFinishedNar both delegate to it (preserving the single-source-of-truth that prevents the divergent-check regressions #1255/#1263/#1279/#1290). Collapse coordinateDownload / pollForDownloadOrTakeOver from two predicate closures to one checkAsset(ctx) (servable, finished); the tick now computes both states in a single call. Behavior is unchanged (full -race suite green). Resolves threads PRRT_kwDONV6tZs6H_WfI, _WfM, _WfP, _WfR, _WfW, _Wfa, _Wfc, _Wfn, _Wfo.
#1375) The coordination poll loop called hasFinishedAsset then hasAsset on every 200ms tick, each repeating HasNarInStore (a storage stat / S3 HEAD) and the nar_file lookup — redundant I/O and DB load under contention. Extract one oracle, narServability(ctx, narURL) (servable, finished, err), and have isServable and hasFinishedNar both delegate to it (preserving the single-source-of-truth that prevents the divergent-check regressions #1255/#1263/#1279/#1290). Collapse coordinateDownload / pollForDownloadOrTakeOver from two predicate closures to one checkAsset(ctx) (servable, finished); the tick now computes both states in a single call. Behavior is unchanged (full -race suite green). Resolves threads PRRT_kwDONV6tZs6H_WfI, _WfM, _WfP, _WfR, _WfW, _Wfa, _Wfc, _Wfn, _Wfo.
Root cause
In lazy CDC deployments, narinfos are initially stored with upstream
compression (e.g.
Compression: xz). Chunking happens in thebackground;
migrateNarToChunksCleanupupdates the narinfo in the DBto
Compression: noneasynchronously. Two races cause "inputcompression not recognized" on the Nix client:
Race 1 — GetNarInfo returns stale xz narinfo while NAR is already
chunked. During the window between chunking completing and the DB
update,
GetNarInforeturns a narinfo withCompression: xz. When Nixdownloads the NAR,
GetNardetects it is in chunks (via theCompression=noneCDC fallback ingetNarFileFromDB) and serves rawuncompressed bytes — which Nix cannot decode as xz.
Race 2 — Nix client has locally cached the old xz narinfo. Even
after the DB is updated, Nix clients that cached the old
.nar.xznarinfo request the
.nar.xzURL directly without re-fetching thenarinfo.
serveNarFromStorageViaPipewas routing these requests tochunks anyway (via the CDC fallback), again serving raw bytes to a
client expecting xz data.
Fixes
Fix 1 (
GetNarInfo): After triggering background migration for anarinfo with non-none compression in CDC mode, call
HasNarInChunks.If the NAR is already chunked, normalize URL and Compression to
nonein-memory before returning. Extracted into
maybeCDCNormalizeNarInfoURLto keep nesting within lint limits. Narinfo fingerprints cover
StorePath/NarHash/NarSize/References — not URL or Compression — so no
re-signing is needed.
Fix 2 (
serveNarFromStorageViaPipe): Only promotehasInStoretoserveFromChunkswhen the request itself is forCompression=none.For xz requests where only chunks remain (whole-file deleted), return
storage.ErrNotFoundso Nix falls back to an upstream cache that stillhas the original compressed file. This handles stale client-side
narinfo caches regardless of what the DB says.
Test plan
TestCacheBackends/*/GetNarInfo_CDCNormalizesCompressionWhenChunked— Fix 1: narinfo normalized when chunks existTestCacheBackends/*/GetNarInfo_CDCNoNormalizationWhenNotChunked— Fix 1: no normalization before chunkingTestCacheBackends/*/GetNarInfo_CDCDisabledNoNormalization— Fix 1: no normalization without CDCTestCacheBackends/*/GetNar_CDCXzRequestReturnsErrWhenChunked— Fix 2: ErrNotFound for xz request when only chunks existTestCacheBackends/*/GetNar_CDCXzServesFromStoreWhenBothExist— Fix 2: xz served from whole-file during lazy-chunking transition🤖 Generated with Claude Code