Repository navigation
fix(cache): 404 un-reassemblable chunked NARs instead of truncated 200 - #1319
Conversation
A completed chunked NAR (total_chunks > 0) can lose nar_file_chunks junction links when a shared chunk row is deleted, because nar_file_chunks.chunk_id -> chunks(id) is ON DELETE CASCADE and the delete does not reset total_chunks. The serve fast path only detected the resulting link gap inside the streaming goroutine, after the HTTP layer had already committed 200 + Content-Length, so clients received a truncated body (unexpected end of nar / SSL_ERROR_SYSCALL) they could not fall back from. getNarFromChunks now counts the junction links in its init transaction on the total_chunks > 0 fast path and returns storage.ErrNotFound synchronously when links != total_chunks, before the pipe and response are committed -> the handler responds 404 and Nix refetches upstream. total_chunks is the completion latch (set only after all links commit), so this is never a mid-chunking race; the progressive (total_chunks = 0) path is deliberately untouched and stays HA-safe. The migrate-chunks-to-nar driver already maps ErrMissingChunk to PurgeChunkedNar + continue + report, and the guard routes link-loss into that path, so un-reassemblable NARs are purged and self-heal on refetch. Adds serving, HA-safety, drain skip/report, and purge-to-cache-miss tests; syncs the chunked-nar-serving-integrity and cdc-drain-mode specs.
|
This change is part of the following stack: Change managed by git-spice. |
|
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 selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughSummary by CodeRabbit
WalkthroughAdds spec/design docs, implements a synchronous completeness check in getNarFromChunks for completed chunked NARs (returning storage.ErrNotFound / 404 when junction-link counts mismatch), and hardens drain/migration to skip, report, and purge un-reassemblable NARs; includes unit, integration, and CLI tests. ChangesChunked NAR Integrity & Migration Fix
Sequence Diagram(s)sequenceDiagram
participant Client
participant HTTPHandler as GetNar
participant Cache as getNarFromChunks
participant DB as nar_file_chunks
participant Drain as migrate-chunks-to-nar
Client->>HTTPHandler: Request completed chunked NAR (total_chunks > 0)
HTTPHandler->>Cache: init fast-path serve
Cache->>DB: COUNT nar_file_chunks WHERE nar_file_id = X
alt count == total_chunks
Cache-->>HTTPHandler: returns reader
HTTPHandler->>Client: HTTP 200 + stream
else count < total_chunks
Cache-->>HTTPHandler: storage.ErrNotFound
HTTPHandler->>Client: HTTP 404 (no truncated body)
end
Drain->>DB: scan and detect missing links/blobs
Drain->>Drain: skip + record broken NAR
Drain->>Cache: PurgeChunkedNar(broken) (delete nar_file + links, keep narinfo)
Drain-->>Drain: report succeeded/purged counts
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related issues
Possibly related PRs
Suggested labels
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 addresses an issue where Nix clients receive truncated NAR downloads (HTTP 200 followed by a premature connection termination) due to missing chunk junction links. A synchronous completeness guard has been added to the completed fast path (total_chunks > 0) in getNarFromChunks to verify that the number of database junction links matches the expected total chunks before returning a reader. If a mismatch is detected, it synchronously returns storage.ErrNotFound (resulting in an HTTP 404), allowing clients to fall back to upstream substituters. Progressive chunking (total_chunks == 0) remains unaffected. Additionally, the migration/drain path has been hardened to skip, purge, and report un-reassemblable NARs instead of aborting. Comprehensive unit and integration tests have been added to verify these changes. No review comments were provided, so there is no feedback to address.
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.
|
Documentation Updates 1 document(s) were updated by changes in this PR: NAR File Download and StreamingView Changes@@ -114,6 +114,7 @@
When CDC is enabled, `nar_file` records in the database can exist in multiple distinct states:
- **Fully chunked**: Records with `total_chunks > 0` and `chunking_started_at` set. These records represent NAR files that have been successfully chunked and are ready for CDC streaming.
+ - **Completeness check**: For completed chunked NARs (`total_chunks > 0`), the cache performs a synchronous completeness check before committing any HTTP response. This check verifies that the number of `nar_file_chunks` junction links equals `total_chunks`. If the NAR cannot be reassembled (fewer links than `total_chunks`), the cache returns `ErrNotFound` (HTTP 404) instead of starting an HTTP 200 response. This prevents the previous behavior where clients would receive "unexpected end of nar", "truncated input", or SSL errors on incomplete chunked NARs. The check only applies to completed NARs; the progressive path (`total_chunks = 0`) is unchanged and continues to stream chunks as they appear. `total_chunks` is the completion latch: it is set only after all junction links are durably committed, so `total_chunks > 0 && links < total_chunks` is always genuine post-completion loss (e.g., junction links stripped by the `nar_file_chunks.chunk_id -> chunks(id) ON DELETE CASCADE` foreign key without resetting `total_chunks`), never a mid-chunking race.
- **Actively chunking**: Records with `chunking_started_at` set but `total_chunks = 0`. These records indicate that chunking is in progress. When lazy chunking is disabled, the `chunking_started_at` timestamp is set within milliseconds of download start (before decompression completes), allowing other HA instances to immediately detect active chunking operations and use progressive streaming. The system uses progressive streaming to serve these NARs while chunking completes.
- **Pending migration (lazy chunking)**: Records with `total_chunks = 0` and `chunking_started_at = NULL`. When lazy chunking is enabled, these records represent compressed NAR files stored without chunking that are awaiting background migration. Background workers asynchronously chunk these files using the `migrate-nar-to-chunks` infrastructure. If ncps is restarted before background chunking completes, these records can become "stuck" and will be recovered by the periodic recovery cron job (see "Recovery of Stuck NARs" in the lazy chunking section).
- **Placeholder/Failed**: Records with `total_chunks = 0` and `chunking_started_at = NULL` can also represent placeholder records created during narinfo storage (via `storeInDatabase`) to link the narinfo to its eventual NAR file. If the subsequent background NAR download fails (e.g., temporary directory missing), or if a chunking operation fails partway through (e.g., "no space left on device"), these placeholder records persist in the database without actual chunked data. When chunking fails due to most errors, the system automatically clears the `chunking_started_at` lock via the `ClearNarFileChunkingStarted` database operation to prevent subsequent requests from waiting indefinitely for chunks that will never arrive. However, when chunking fails specifically due to truncation detection (where the total bytes consumed do not match the expected `NarSize`), the system intentionally leaves `chunking_started_at` set and relies on the stale lock recovery mechanism (1-hour TTL cleanup) to handle it, rather than clearing the lock immediately.
@@ -137,6 +138,10 @@
- `--force-reclaim`: Bypass the in-flight-serve safety check
Per-NAR failures are isolated—the batch continues processing remaining NARs. When a NAR encounters `ErrNarHashMismatch` or `ErrMissingChunk`, the command calls `PurgeChunkedNar` to delete the `nar_file` record, remove chunk links, and reclaim orphaned chunks. The narinfo record is intentionally left intact so the next `GetNarInfo` can trigger a clean upstream re-fetch. Purged NARs are counted separately from failures in metrics and logs. The command exits 0 when all NARs were either successfully migrated, skipped, or purged. Only genuine migration errors (not hash mismatches or missing chunks) cause non-zero exit.
+
+**Handling Un-reassemblable Chunked NARs:**
+
+The migration command skips un-reassemblable chunked NARs instead of aborting the entire run. When `migrate-chunks-to-nar` encounters a chunked NAR that cannot be reassembled—because its `nar_file_chunks` links are incomplete (fewer links than `total_chunks`) or because a referenced chunk's blob is absent from the chunk store—it skips that NAR and continues migrating the remaining NARs. Un-reassemblable NARs are counted and reported by hash at the end of the run, allowing operators to identify and address them. These NARs can be purged to a clean cache-miss state using `PurgeChunkedNar`, which deletes the `nar_file` record and chunk links while retaining the linked narinfo, allowing the NAR to be refetched from upstream on the next request. This makes HTTP 404 responses for incomplete chunked NARs self-healing rather than permanent failures.
When lazy chunking is enabled (via `--cache-cdc-lazy-chunking-enabled=true`), compressed NAR files are stored without immediate chunking, and background workers automatically perform migration using the same infrastructure as the `migrate-nar-to-chunks` command. The background workers can be configured via `--cache-cdc-background-workers` (default: number of CPUs).
|
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
pkg/cache/migrate_chunks_to_nar_test.go (1)
176-213: ⚡ Quick winConsider adding narinfo retention assertion for test completeness.
The test comment states the contract includes "while leaving the linked narinfo intact so that refetch can proceed," but the test doesn't verify narinfo retention. While
TestPurgeChunkedNar_RetainsNarInfoRecord(lines 387-409) covers this behavior separately, adding the assertion here would make this test fully self-documenting and reduce cross-test dependencies for contract verification.📋 Proposed addition to verify complete contract
assert.Zero(t, count, "purged NAR's nar_file record must be deleted so the next GetNar is a cache miss") + + // Verify narinfo is retained so the next request can refetch from upstream + narInfoCount, err := dbClient.Ent().NarInfo.Query().Count(ctx) + require.NoError(t, err) + assert.Positive(t, narInfoCount, "purged NAR's narinfo must be retained for upstream refetch") }🤖 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/migrate_chunks_to_nar_test.go` around lines 176 - 213, Add an assertion that the linked narinfo record still exists after calling c.PurgeChunkedNar so the test enforces the contract that narinfo is retained for refetch; after the existing checks (HasNarInChunks/HasNarInStore and nar_file Count) query the narinfo table via dbClient.Ent().NarInfo.Query().Where(entnarinfo.HashEQ(noneURL.Hash)).Count(ctx) (or Only(ctx) and check no error) and assert the count is 1 (or that the record exists) to confirm the narinfo remains; keep the added check adjacent to the existing DB assertions in TestPurgeChunkedNar_LeavesCleanCacheMissForRefetch.
🤖 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/chunked_nar_serving_integrity_internal_test.go`:
- Around line 58-64: The test currently only asserts no error from calling
getNarFromChunks but doesn't verify the returned reader; add an assertion that
the returned reader is non-nil by inserting require.NotNil(t, rc) after
require.NoError and before t.Cleanup to ensure the progressive path actually
returned a reader (referencing getNarFromChunks and the rc variable).
---
Nitpick comments:
In `@pkg/cache/migrate_chunks_to_nar_test.go`:
- Around line 176-213: Add an assertion that the linked narinfo record still
exists after calling c.PurgeChunkedNar so the test enforces the contract that
narinfo is retained for refetch; after the existing checks
(HasNarInChunks/HasNarInStore and nar_file Count) query the narinfo table via
dbClient.Ent().NarInfo.Query().Where(entnarinfo.HashEQ(noneURL.Hash)).Count(ctx)
(or Only(ctx) and check no error) and assert the count is 1 (or that the record
exists) to confirm the narinfo remains; keep the added check adjacent to the
existing DB assertions in TestPurgeChunkedNar_LeavesCleanCacheMissForRefetch.
🪄 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: bc6751d7-3261-4f73-9e0a-7e6100566fff
📒 Files selected for processing (14)
openspec/changes/archive/2026-06-03-fix-truncated-chunked-nar-serving/.openspec.yamlopenspec/changes/archive/2026-06-03-fix-truncated-chunked-nar-serving/design.mdopenspec/changes/archive/2026-06-03-fix-truncated-chunked-nar-serving/proposal.mdopenspec/changes/archive/2026-06-03-fix-truncated-chunked-nar-serving/specs/cdc-drain-mode/spec.mdopenspec/changes/archive/2026-06-03-fix-truncated-chunked-nar-serving/specs/chunked-nar-serving-integrity/spec.mdopenspec/changes/archive/2026-06-03-fix-truncated-chunked-nar-serving/tasks.mdopenspec/specs/cdc-drain-mode/spec.mdopenspec/specs/chunked-nar-serving-integrity/spec.mdpkg/cache/cache.gopkg/cache/cdc_test.gopkg/cache/chunked_nar_serving_integrity_internal_test.gopkg/cache/chunked_nar_serving_integrity_test.gopkg/cache/migrate_chunks_to_nar_test.gopkg/ncps/migrate_chunks_to_nar_test.go
The HA-safety test for mid-chunking NARs asserted only that getNarFromChunks did not error synchronously; a (nil, nil) return would have slipped past the require.NoError and only surfaced as a nil-pointer panic at cleanup. Add require.NotNil(t, rc) so the test fails cleanly and matches its documented contract that the progressive path returns a reader. Co-Authored-By: Claude Opus 4.8 <[email protected]>
## Summary - **`openspec/specs/cdc-drain-mode/spec.md`**: fix a pre-existing `openspec validate` failure (`requirements.1.text: Requirement must contain SHALL or MUST keyword`). The validator parses a requirement's text as only its **first physical line** and checks that line for `SHALL`/`MUST`. The "server MUST enter drain mode" requirement put its normative `SHALL` on the third wrapped line, so the validator never saw it. Reworded to open with `The server SHALL enter drain mode when it starts with …` — keyword now in the first line. Pure wording; meaning, scenarios, and behavior unchanged. - **`docs/.../Chunks to NAR Migration.md`**: minor code-fence language-tag cleanup. This is independent of #1319 (a pre-existing validation bug), branched off `main` so it can merge on its own. ## Test plan - [x] `openspec validate cdc-drain-mode` → valid - [x] `task fmt` clean - [x] No code changes; no test/lint impact --------- Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
## Summary The `[Unreleased]` section was populated in #1309 but skewed toward the recent CDC-drain, in-flight-staging, and Ent-migration work, omitting several user-facing features and fixes that also landed since v0.9.4. This backfills the missing notable changes, each cross-referenced by PR. **Added** - `ncps fsck` command + Helm fsck CronJob (#975, #996, #998, #999, #1000, #1004, #1006, #1176) - Closure pinning HTTP endpoints `POST`/`DELETE /pin/{hash}.narinfo`, `GET /pins` (#1108) - pprof server via `--pprof-addr` (#1063) - CDC lazy chunking as a feature + `--cache-cdc-lazy-cleanup-schedule` + recovery cron (#1082, #1083, #1089, #1096) - Helm: auto `GOMEMLIMIT` (#1061), configurable temp volume / `volumeClaimTemplate` (#1074, #1077), SQLite `Recreate` strategy (#1012) - Startup storage reporting + deprecated-narinfo warning (#959, #961) - `docker-dev` image (#1097) **Fixed** - `store/tmp` no longer wiped on startup (#1313) - `nix-hash` NAR verification (#1101) - Prometheus counters primed at startup (#1337, #1343) - 404 on un-reassemblable chunked NARs (#1319), purged narinfo no longer 500 (#1318), fail-fast tmp validation (#1086) - Further CDC/cache reliability fixes (#1317, #1346, #1341, #1342, #1331, #1347) **Changed** - CDC config now persisted in the DB config table (#971) Dependency bumps, CI/test-only changes, and the internal Ent-conversion PRs are intentionally excluded; the existing Ent-migration entry already covers that work. ## Test plan - [x] `nix fmt` reports no changes (docs-only edit) - [x] CHANGELOG section structure intact (Added/Fixed/Changed/Removed/Migration/CI)
Summary
Production Nix clients were getting truncated NAR downloads from ncps
(
unexpected end of nar,truncated input,SSL_read: SSL_ERROR_SYSCALL) onresponses that started as
HTTP 200. Root cause, confirmed against the live DB:nar_file_chunks.chunk_id -> chunks(id)isON DELETE CASCADE. Deleting ashared
chunksrow strips its junction links from completed chunked NARs(
total_chunks > 0) without resettingtotal_chunks. Nothing enforcedcount(links) == total_chunks.expected N chunks but got M)inside the streaming goroutine, after
server.gohad already written200 OK+Content-Length— so the client got a body it couldn't fulfill andNix could not fall back.
total_chunks = 0mid-chunking orphans). Of 2499 completed chunked NARs in prod, 71 had
links < total_chunks.Fix
getNarFromChunksnow counts junction links in its init transaction on thetotal_chunks > 0fast path and returnsstorage.ErrNotFoundsynchronouslywhen
links != total_chunks, before the pipe/response are committed → handlerresponds
404→ Nix refetches upstream.total_chunksis the completion latch(written only after all links commit), so this is never a mid-chunking race; the
progressive
total_chunks = 0path is left untouched and stays HA-safe.The
migrate-chunks-to-nardriver already mapsErrMissingChunktoPurgeChunkedNar+ continue + report; the guard routes link-loss into that path,so the 71 broken NARs self-heal (purge → refetch) on the next drain.
Specs synced: new
chunked-nar-serving-integritycapability + 2 addedrequirements on
cdc-drain-mode.Test plan
task fmt/task lint(0 issues) /task test(all packages ok)go test -race ./pkg/cache ./pkg/server— okmissing-link →
ErrMissingChunk, purge → clean cache-miss, and a CLImix-migration test (skip broken + migrate good + report by hash)