Skip to content

fix(cache): 404 un-reassemblable chunked NARs instead of truncated 200 - #1319

Merged
kalbasit merged 2 commits into
mainfrom
fix-cache-404-un-reassemblable
Jun 3, 2026
Merged

kalbasit merged 2 commits into
mainfrom
fix-cache-404-un-reassemblable

Conversation

@kalbasit

@kalbasit kalbasit commented Jun 3, 2026

Copy link
Copy Markdown
Owner

Summary

Production Nix clients were getting truncated NAR downloads from ncps
(unexpected end of nar, truncated input, SSL_read: SSL_ERROR_SYSCALL) on
responses that started as HTTP 200. Root cause, confirmed against the live DB:

Fix

getNarFromChunks now counts 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/response are committed → handler
responds 404 → Nix refetches upstream. total_chunks is the completion latch
(written only after all links commit), so this is never a mid-chunking race; the
progressive total_chunks = 0 path is left untouched and stays HA-safe.

The migrate-chunks-to-nar driver already maps ErrMissingChunk to
PurgeChunkedNar + 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-integrity capability + 2 added
requirements on cdc-drain-mode.

Test plan

  • task fmt / task lint (0 issues) / task test (all packages ok)
  • go test -race ./pkg/cache ./pkg/server — ok
  • New tests: serving 404-not-truncated-200, HA-safety on progressive path,
    missing-link → ErrMissingChunk, purge → clean cache-miss, and a CLI
    mix-migration test (skip broken + migrate good + report by hash)

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.
@kalbasit

kalbasit commented Jun 3, 2026

Copy link
Copy Markdown
Owner Author

This change is part of the following stack:

Change managed by git-spice.

@coderabbitai

coderabbitai Bot commented Jun 3, 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: 87e0a21b-ba16-4508-9f8c-9496684b6839

📥 Commits

Reviewing files that changed from the base of the PR and between 86be77b and ef505cd.

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

📝 Walkthrough

Summary by CodeRabbit

  • Bug Fixes

    • Prevents truncated NAR downloads by validating completed chunked NAR integrity before streaming; returns 404 on mismatch
    • Migration/drain now skips un-reassemblable NARs and makes them purgeable so they self-heal via refetch
  • Documentation

    • Added specs, design, proposal and task docs detailing serving-integrity and drain/migration behavior
  • Tests

    • Added regression and end-to-end tests covering completed/path integrity, mid-chunking behavior, migration skipping, purging, and CLI reporting

Walkthrough

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

Changes

Chunked NAR Integrity & Migration Fix

Layer / File(s) Summary
Problem statement & specification
openspec/changes/archive/..., openspec/specs/chunked-nar-serving-integrity/, openspec/specs/cdc-drain-mode/
Design, proposal, and spec text describing truncated NAR failures and requiring synchronous junction-link completeness validation for completed-chunk serves and drain-mode skip+purge behavior.
Serving integrity guard & tests
pkg/cache/cache.go, pkg/cache/cdc_test.go, pkg/cache/chunked_nar_serving_integrity_test.go, pkg/cache/chunked_nar_serving_integrity_internal_test.go
getNarFromChunks now counts nar_file_chunks links when total_chunks > 0 and returns storage.ErrNotFound if count ≠ total_chunks. Tests validate 404 on missing links and that progressive/mid-chunking (total_chunks = 0) remains unaffected.
Migration detection & purge tests
pkg/cache/migrate_chunks_to_nar_test.go
Adds dropLastChunkLink helper, tests that MigrateChunksToNar reports cache.ErrMissingChunk for missing-links, and tests PurgeChunkedNar produces a clean cache-miss while preserving narinfo.
End-to-end CLI migration test
pkg/ncps/migrate_chunks_to_nar_test.go
Integration test TestMigrateChunksToNar_CLI_SkipsBrokenNarMigratesRestAndReports seeds a broken and a good NAR, runs the CLI, asserts successful exit, verifies DB state changes (good migrated, broken purged), and asserts CLI summary includes succeeded:1 and purged:1 with the purged hash.

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
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related issues

  • #1289 — Overlaps getNarFromChunks changes; this issue proposed modifications to the progressive-chunk serve path which touches the same serving logic.

Possibly related PRs

Suggested labels

merge-stack

Poem

🐰 When junctions break and bytes fall short,
I count the links before we start—
If pieces lack the final door,
Send a 404, restore once more;
Drain will sweep, and fetch will mend the heart.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the main change: preventing truncated HTTP 200 responses by returning 404 for un-reassemblable chunked NARs instead.
Description check ✅ Passed The description comprehensively explains the production issue, root cause analysis, implemented fix, and test coverage—all directly relevant to the changeset.
Docstring Coverage ✅ Passed Docstring coverage is 84.62% 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.

@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 3, 2026

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

@dosubot

dosubot Bot commented Jun 3, 2026 •

Copy link
Copy Markdown

Documentation Updates

1 document(s) were updated by changes in this PR:

NAR File Download and Streaming
View 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).
 

How did I do? Any feedback?  Join Discord

@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

🧹 Nitpick comments (1)
pkg/cache/migrate_chunks_to_nar_test.go (1)

176-213: ⚡ Quick win

Consider 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

📥 Commits

Reviewing files that changed from the base of the PR and between 6233e78 and 86be77b.

📒 Files selected for processing (14)
  • openspec/changes/archive/2026-06-03-fix-truncated-chunked-nar-serving/.openspec.yaml
  • openspec/changes/archive/2026-06-03-fix-truncated-chunked-nar-serving/design.md
  • openspec/changes/archive/2026-06-03-fix-truncated-chunked-nar-serving/proposal.md
  • openspec/changes/archive/2026-06-03-fix-truncated-chunked-nar-serving/specs/cdc-drain-mode/spec.md
  • openspec/changes/archive/2026-06-03-fix-truncated-chunked-nar-serving/specs/chunked-nar-serving-integrity/spec.md
  • openspec/changes/archive/2026-06-03-fix-truncated-chunked-nar-serving/tasks.md
  • openspec/specs/cdc-drain-mode/spec.md
  • openspec/specs/chunked-nar-serving-integrity/spec.md
  • pkg/cache/cache.go
  • pkg/cache/cdc_test.go
  • pkg/cache/chunked_nar_serving_integrity_internal_test.go
  • pkg/cache/chunked_nar_serving_integrity_test.go
  • pkg/cache/migrate_chunks_to_nar_test.go
  • pkg/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]>
@kalbasit
kalbasit enabled auto-merge (squash) June 3, 2026 21:59
@kalbasit
kalbasit merged commit 6614a29 into main Jun 3, 2026
59 of 61 checks passed
@kalbasit
kalbasit deleted the fix-cache-404-un-reassemblable branch June 3, 2026 22:07
kalbasit added a commit that referenced this pull request Jun 3, 2026
## 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>
kalbasit added a commit that referenced this pull request Jun 8, 2026
## 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)
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

Development

Successfully merging this pull request may close these issues.

1 participant