Repository navigation
fix(cache): harden NAR cache-miss recovery & retry - #1296
Conversation
The phantom nar_file defect surfaced as permanent "nar does not exist" 404s for paths whose narinfo was just served: a backing-less nar_file row (total_chunks=0, chunking_started_at=NULL) created at narinfo-fetch time, left behind by a failed background download, was treated as servable and short-circuited GET /nar to a terminal 404. Prior PRs (#1255-#1290) already fixed the core read path. This change closes the remaining gaps and hardens against regression: - D5: extend upstream 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. - D1: unify the duplicated, drift-prone servability checks in GetNar and prePullNar's hasAsset behind a single isServable() predicate (plus narFileServable()), so a placeholder row is never servable and the regression cannot return via divergent checks. Behavior preserving. - Recovery sweep: runCDCLazyRecovery now skips backing-less stuck rows (no whole-file in store). 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. Tests: phantom_recovery_test.go reproduces the production scenario (narinfo 200 -> failed download -> recovery on next request) and the genuine-404 path; transient_retry_test.go covers the new retriable errors and that a 404 is not retried; recovery_skip_internal_test.go proves the sweep skips backing-less rows but re-drives store-present ones. No schema migration. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
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:
📝 WalkthroughWalkthroughTreat backing-less ChangesPhantom NAR Cache Miss Fix
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related issues
Possibly related PRs
Suggested labels
🚥 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.
Code Review
This pull request unifies NAR servability checks under a single isServable predicate to prevent backing-less placeholder records from causing terminal 404s, treating them instead as cache misses that trigger synchronous upstream re-downloads. It also hardens upstream requests by retrying on transient transport errors (such as HTTP/2 timeouts, connection resets, and broken pipes) and updates the CDC lazy-recovery job to skip backing-less stuck rows. Feedback on these changes highlights a high-severity queue starvation hazard in the lazy-recovery job: skipping backing-less records without updating their created_at timestamp will cause them to repeatedly fill the query results in subsequent cron runs, starving actual stuck records that need chunking. A code suggestion is provided to touch the created_at timestamp of skipped records to prevent this head-of-line blocking.
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 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 `@openspec/changes/archive/2026-05-29-fix-phantom-nar-cache-miss/proposal.md`:
- Line 3: Change the typo "narinfo ncps just served `200`" to a clearer phrase
such as "narinfo responses just served `200`" in the problem statement so the
sentence reads "paths whose `narinfo` responses just served `200`"; locate the
sentence referencing `narinfo`, `nar/<hash>.nar.xz`, `nar_file`, `total_chunks`,
and `chunking_started_at` and replace only the "ncps" token with "responses" (or
an equivalent clear term) to preserve the surrounding technical symbols like
`GET /nar`.
In `@openspec/specs/nar-cache-miss-recovery/spec.md`:
- Around line 65-71: Update the scenario text for the CDC lazy-recovery job to
match implemented behavior: state that the sweep SHOULD re-drive or clear stuck
nar_file rows when possible but MAY skip backing-less rows that lack a
whole-file (these are left for on-demand recovery by GetNar), and retain the
requirement that the sweep SHALL NOT indefinitely retry hashes that upstream
genuinely does not have; reference the CDC lazy-recovery job, nar_file rows, and
GetNar in the wording so the spec matches the logic in pkg/cache/cache.go that
skips backing-less/no-whole-file rows.
🪄 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: 7df3be0a-1e3b-4652-a290-0f14ac699dc3
📒 Files selected for processing (16)
openspec/changes/archive/2026-05-29-fix-phantom-nar-cache-miss/.openspec.yamlopenspec/changes/archive/2026-05-29-fix-phantom-nar-cache-miss/design.mdopenspec/changes/archive/2026-05-29-fix-phantom-nar-cache-miss/proposal.mdopenspec/changes/archive/2026-05-29-fix-phantom-nar-cache-miss/specs/cdc-chunking/spec.mdopenspec/changes/archive/2026-05-29-fix-phantom-nar-cache-miss/specs/nar-cache-miss-recovery/spec.mdopenspec/changes/archive/2026-05-29-fix-phantom-nar-cache-miss/specs/nar-concurrent-streaming/spec.mdopenspec/changes/archive/2026-05-29-fix-phantom-nar-cache-miss/tasks.mdopenspec/specs/cdc-chunking/spec.mdopenspec/specs/nar-cache-miss-recovery/spec.mdopenspec/specs/nar-concurrent-streaming/spec.mdpkg/cache/cache.gopkg/cache/cdc_test.gopkg/cache/phantom_recovery_test.gopkg/cache/recovery_skip_internal_test.gopkg/cache/upstream/cache.gopkg/cache/upstream/transient_retry_test.go
"narinfo ncps just served 200" → "narinfo was just served 200". Co-Authored-By: Claude Opus 4.8 <[email protected]>
The CDC lazy-recovery sweep selects stuck nar_file rows ordered by id and limited to batchSize, skipping backing-less rows (no whole-file to migrate) without mutating them. Under the failed-download scenario this job exists to tolerate, thousands of backing-less placeholder rows accumulate at the low end of the id space. With more than batchSize of them, every per-run snapshot is filled by the same low-id rows, permanently starving genuinely re-drivable rows (whole-file present, needs chunking) at higher ids. Carry a keyset cursor (nar_files.id) across cron invocations so each run resumes after the highest id it last examined and wraps to 0 at the end. This guarantees forward progress without touching created_at, which the schema marks Immutable(). Co-Authored-By: Claude Opus 4.8 <[email protected]>
The sweep re-drives only store-backed stuck rows and skips backing-less ones (left to GetNar's on-demand re-download), per pkg/cache/cache.go. Update the scenario to match, and record the new no-head-of-line-starvation guarantee. Co-Authored-By: Claude Opus 4.8 <[email protected]>
TestSchemaEquivalence runs its per-dialect subtests with t.Parallel(). Each performs an Ent/Atlas schema replay-diff (schema.NewMigrate -> NamedDiff -> planReplay -> realm -> tables -> aIndexes), which reads process-global state in entgo.io/ent's Atlas integration that is not safe for concurrent use. Under the race detector the parallel dialects intermittently trip a data race in entgo.io/ent/dialect/sql/schema/atlas.go, failing the postgres CI cohort. Guard the replay-diff section with a package-level mutex so the dialect subtests serialize through it while keeping t.Parallel() for setup and teardown. Errors are captured under the lock and asserted after unlock so a failed require never leaves the mutex held. Co-Authored-By: Claude Opus 4.8 <[email protected]>
BackgroundMigrateNarToChunks ran the CDC migration in a detached goroutine (analytics.SafeGo with a context.WithoutCancel) that did not register with backgroundWG, so Close() did not wait for it. The goroutine could keep writing chunk files after the owning cache was torn down. In the lazy-recovery tests this raced t.TempDir cleanup, intermittently failing the mysql CI cohort with "directory not empty" during RemoveAll. Register the migration goroutine with backgroundWG (Add before SafeGo, defer Done inside) so Close() drains in-flight migrations on shutdown, matching the other background goroutines. This makes shutdown graceful and removes the test teardown race. Co-Authored-By: Claude Opus 4.8 <[email protected]>
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 7489-7496: Close() currently waits on c.backgroundWG before
stopping c.cron, which can race with cron-triggered jobs; modify Close() to call
c.cron.Stop() first, wait for the returned context to finish (block on the
context returned by cron.Stop() or its Done channel), and only then call
c.backgroundWG.Wait() so background migrations (e.g.,
Cache.BackgroundMigrateNarToChunks) complete without being re-enqueued by cron;
ensure you reference c.cron.Stop(), the returned context, c.backgroundWG.Wait(),
and the BackgroundMigrateNarToChunks goroutine tracking when making the change.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
Close() waited on backgroundWG before stopping the cron. Now that BackgroundMigrateNarToChunks registers with backgroundWG, a cron-fired runCDCLazyRecovery could enqueue a tracked migration (backgroundWG.Add) while Close() was already in backgroundWG.Wait() — an Add-concurrent- with-Wait race that is especially unsafe when the counter is zero. Stop the cron first and block on the context it returns (which completes once any in-flight scheduled job finishes) before draining backgroundWG. This guarantees no scheduled job can enqueue more tracked work after the drain begins. Addresses CodeRabbit review on #1296. Co-Authored-By: Claude Opus 4.8 <[email protected]>
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
pkg/cache/cache.go (1)
6435-6442:⚠️ Potential issue | 🟠 Major | 🏗️ Heavy liftPersist the lazy-recovery cursor outside process memory.
cursorIDonly lives in this closure. After a pod restart—or whenever another instance wins thecdc-lazy-recoverylock—the scan starts over at0, so the same low-ID backing-less rows can fill the batch again and higher-ID recoverable rows can still starve in clustered/restarting deployments. This needs shared state (for example a DB/config cursor row) or a query strategy that doesn't depend on per-process memory.Also applies to: 6489-6505
🤖 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.go` around lines 6435 - 6442, The local variable cursorID used as the keyset cursor (cursorID in pkg/cache/cache.go) cannot live only in process memory because restarts or lock handoffs reset it to 0; persist this cursor in shared storage (for example a DB table/row or a config/key-value row) and read/update that persisted cursor inside the same transactional flow that advances the scan so other instances see progress; alternatively replace the in-memory cursorID strategy with a query that selects the next batch using a durable marker (e.g., WHERE id > last_processed_id fetched from and written back to the DB) and apply the same change for the related code region referenced around lines 6489-6505 so the scan state survives restarts and lock transfers.
🤖 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.
Outside diff comments:
In `@pkg/cache/cache.go`:
- Around line 6435-6442: The local variable cursorID used as the keyset cursor
(cursorID in pkg/cache/cache.go) cannot live only in process memory because
restarts or lock handoffs reset it to 0; persist this cursor in shared storage
(for example a DB table/row or a config/key-value row) and read/update that
persisted cursor inside the same transactional flow that advances the scan so
other instances see progress; alternatively replace the in-memory cursorID
strategy with a query that selects the next batch using a durable marker (e.g.,
WHERE id > last_processed_id fetched from and written back to the DB) and apply
the same change for the related code region referenced around lines 6489-6505 so
the scan state survives restarts and lock transfers.
The keyset cursor lived only in the scheduled closure's memory, so a pod restart or a cdc-lazy-recovery lock handoff to another instance reset the scan to 0. A low-id backlog of backing-less placeholders could then refill every batch and starve higher-id re-drivable rows forever in clustered or restarting deployments. Persist the cursor in the existing config key-value table (cdc_lazy_recovery_cursor) via loadRecoveryCursor/saveRecoveryCursor: each sweep resumes from the stored value and writes back after advancing or wrapping. The cdc-lazy-recovery distributed lock serializes sweeps, so a plain upsert is sufficient; no schema migration. Addresses CodeRabbit outside-diff review on #1296. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #1296 +/- ##
============================
============================
☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
## Summary Three hardening follow-ups left over from the archived `fix-phantom-nar-cache-miss` change (and its keyset-cursor commit), stacked on #1296. OpenSpec change `cdc-recovery-followups` (proposal/design/specs/tasks, all 17 tasks complete, `/opsx:verify` clean, archived). - **Placeholder-row GC** (`feat(cache): GC genuinely-absent placeholder rows`): the CDC lazy-recovery sweep skipped backing-less `nar_file` placeholder rows but never cleared them, so rows for NARs genuinely gone upstream accumulated and were re-scanned every cursor cycle. New `upstream.NarInfoExistence` returns a tri-state `Existence{Present,Absent,Unknown}` — it probes the **narinfo** HEAD (unambiguous) and, unlike `HasNar`/`HasNarInfo`, does **not** collapse a timeout into "absent". The sweep deletes a row only when **every** healthy upstream is definitively `Absent` (≥1 healthy upstream, none Present/Unknown). `ON DELETE CASCADE` cleans up links. Present / Unknown / no-upstreams / row-newer-than-cutoff all keep the row, so a transient outage or in-flight download is never mistaken for genuine absence. - **Bounded retry backoff** (`feat(upstream): backoff for transient retries`): `doRequest` retried transient transport errors (GOAWAY, http2 header timeout, conn reset, broken pipe) immediately. Add a capped exponential `waitRetryBackoff` (base `defaultRetryBackoff`, cap `defaultRetryBackoffCap`, override `Options.RetryBackoff`) that respects `ctx` cancellation. Genuine 404 still never retries (it returns a response, not a transport error). - **Streaming fast-fail** (`fix(cache): fast-fail stalled progressive streaming`): `streamProgressiveChunks` only failed a stalled stream after the 30s per-chunk timeout. Add a stale-lock fast-fail (`time.Since(chunking_started_at) > cdcChunkingLockTTL` → not-found in ~200ms), never closing a truncated 200. ## Test plan - [x] `task fmt` clean; changed packages lint clean - [x] `task test` green; `pkg/cache/...` (cache + upstream) under `-race` - [x] GC: `TestRecoveryGC{DeletesGenuinelyAbsent,KeepsPresentUpstream,KeepsOnTransientProbe,SkipsFresh}`, `TestNarInfoExistence` - [x] Backoff: `TestDoRequest_{RetriesUseBackoff,BackoffRespectsContextCancellation,GenuineNotFoundIsNotRetried}` - [x] Streaming: `TestGetNarFromChunks_{AbortedChunkingErrorsNotShortBody,StalledChunkingFailsFast}` - [ ] CI cohorts (postgres/mysql/s3/redis) green --------- Co-authored-by: Claude Opus 4.8 <[email protected]>
The keyset cursor lived only in the scheduled closure's memory, so a pod restart or a cdc-lazy-recovery lock handoff to another instance reset the scan to 0. A low-id backlog of backing-less placeholders could then refill every batch and starve higher-id re-drivable rows forever in clustered or restarting deployments. Persist the cursor in the existing config key-value table (cdc_lazy_recovery_cursor) via loadRecoveryCursor/saveRecoveryCursor: each sweep resumes from the stored value and writes back after advancing or wrapping. The cdc-lazy-recovery distributed lock serializes sweeps, so a plain upsert is sufficient; no schema migration. Addresses CodeRabbit outside-diff review on #1296. Co-Authored-By: Claude Opus 4.8 <[email protected]>
## Summary Follow-up to #1297 (stacked on it) addressing review feedback from CodeRabbit (#1296 outside-diff) and Gemini (#1297). Each fix is its own commit, TDD'd. - **Persist the lazy-recovery cursor** (CodeRabbit, #1296): the keyset cursor lived only in the scheduled closure's memory, so a pod restart or `cdc-lazy-recovery` lock handoff reset the scan to 0 — a low-id backlog of backing-less placeholders could then refill every batch and starve higher-id re-drivable rows in clustered/restarting deployments. Persist it in the existing config KV table (`cdc_lazy_recovery_cursor`) via `loadRecoveryCursor`/`saveRecoveryCursor`. The distributed lock serializes sweeps, so a plain upsert suffices; **no migration**. - **GC only when all linked narinfos are absent** (Gemini, #1297): the placeholder GC resolved a single narinfo via `First()`; multiple store paths can share one NAR, so a still-present narinfo could be missed and an active NAR wrongly deleted. Query **all** linked narinfos and delete only when every one is genuinely absent upstream. - **Skip backoff on the final retry attempt** (Gemini, #1297): `waitRetryBackoff` ran after the last failed attempt too, padding the latency of an already-doomed request. Guard with `i < defaultHTTPRetries-1` (and flatten `doRequest` into guard clauses). ## Test plan - [x] `task fmt` clean; changed packages lint clean - [x] `pkg/cache/...` (cache + upstream) pass under `-race`; full unit suite green - [x] Cursor: `TestRunCDCLazyRecoveryCursorPersists` (persists + resumes across a fresh closure) - [x] GC: `TestRecoveryGCKeepsWhenAnyLinkedNarInfoPresent` - [x] Backoff: `TestDoRequest_NoBackoffOnFinalAttempt` - [ ] CI cohorts green --------- Co-authored-by: Claude Opus 4.8 <[email protected]>
…1299) ## Summary On a high-latency or shared-storage backend (e.g. the `local` backend on a network filesystem with multiple replicas), two failure modes still surfaced to clients as spurious cache-miss 404s and gateway 504s despite #1296/#1297/#1298: 1. **False-purge cascade.** `HasNar` collapsed *every* error into `false`, so an ambiguous/stale NFS stat was indistinguishable from a confirmed absence. The narinfo purge guard then destructively purged the narinfo, which clients saw as `does not exist in binary cache` (the `"requesting a purge"` log line). 2. **Unbounded per-chunk wait.** Progressive CDC streaming waited a hard-coded 30s per chunk; a legitimately slow chunk on high-latency storage accumulated past the reverse-proxy timeout and surfaced as a 504 / truncated transfer. ## Changes - Add `storage.NarStore.StatNar` returning **present / confirmed-absent / unknown**; implemented in `local` (`os.IsNotExist`) and `s3` (`NoSuchKey`); `HasNar` now delegates to it. - `getNarInfoFromDatabase` skips the purge on an **ambiguous (non-not-found)** storage result and keeps the narinfo, letting the next request re-evaluate. - Make the per-chunk wait operator-configurable via `cache.cdc.chunk-wait-timeout` (`CACHE_CDC_CHUNK_WAIT_TIMEOUT`, default 30s), replacing the hard-coded value so it can be aligned with the gateway timeout. - Storage-backend selection docs (README + `config.example.yaml`): `local` assumes single-writer POSIX semantics; multi-replica should use an object store; CDC suits low-latency storage. ## Notes - Most of the original investigation's scope was **already shipped** in the deployed `sha-7d071cf` (phantom recovery, aborted-chunking guards); this PR targets the two remaining gaps that map to the observed production failures. - **Deferred to a follow-up:** pre-commit chunk-set verification with fallback-to-redownload — reworking `GetNar` servability is regression-risky and per-chunk pre-flight stats add load to the same slow backend. Its spec requirement was removed before archive so the spec matches what is implemented. - openspec change `fix-nar-serving-failures` archived (delta specs synced into `openspec/specs/`). ## Test plan - [x] `task fmt`, `task lint`, `task test` green - [x] TDD, RED verified: `TestGetNarInfoFromDatabase_AmbiguousStorageErrorDoesNotPurge` (RED = "the narinfo was purged"), `TestStreamProgressiveChunks_ChunkWaitTimeoutIsConfigurable` - [ ] CI `nix flake check` (per-backend integration cohorts) --------- Co-authored-by: Claude Opus 4.8 <[email protected]>
Reclaim safety: migrate-chunks-to-nar no longer deletes chunks out from under in-flight serves. A serve that began streaming from chunks before the record flip may still be reading those chunk files; deleting them mid-stream would truncate that transfer (the failure class #1296/#1297 fixed). - MigrateChunksToNar(ctx, narURL, forceReclaim): by default it flips the record and leaves now-orphaned chunks for the GC. forceReclaim=true (CLI --force-reclaim) reclaims immediately for drained/maintenance-window runs. Dedup-safe in both paths (shared chunks retained). - Spec (chunks-to-nar-migration): reclamation deferred-by-default + always dedup-safe; Purpose filled in. Helm chart: - Opt-in migrate-chunks-to-nar Job (post-install/post-upgrade hook) with forceReclaim / dryRun / concurrency toggles, so the de-chunking migration can be driven from the chart. Reuses the deployment's db/storage/redis config. (The cache.cdc.chunk-wait-timeout chart wiring already lives in main; not re-added here.) Docs (docs/docs): - New "Operations/Chunks to NAR Migration" page (reverse migration, --dry-run, --force-reclaim with in-flight-serve safety, Helm Job, verification/skip, failure isolation); linked from the Operations index and CDC feature page. Tests: cache tests under -race (default-leaves-chunks, force-reclaim-deletes, force-reclaim-retains-shared) + CLI tests (default-defer, force-reclaim, dry-run, hash-mismatch). task fmt/lint/test green; 146 helm unittests pass. Co-Authored-By: Claude Opus 4.8 <[email protected]>
## Summary
Adds `migrate-chunks-to-nar`, the reverse of `migrate-nar-to-chunks`: it
reconstructs CDC-chunked NARs back into whole files so a deployment can
**exit CDC**. Previously the forward migration was one-way (with
`delete-delay` the whole files are GC'd), so once chunked there was no
supported path back to whole-file storage.
### Cache — `Cache.MigrateChunksToNar(ctx, narURL, forceReclaim)`
- Per-hash `TryLock("migration-to-nar:"+hash)`, mirroring the forward
migration.
- Reconstructs from chunks (`getNarFromChunks`), verifies the assembled
SHA-256 against the linked narinfo's `NarHash` (+ size), and writes the
whole file via `narStore.PutNar` (bypassing `c.PutNar` so CDC does not
re-chunk it). **Verified-or-nothing** — a NAR is never de-chunked unless
it verifies.
- **Write → flip → reclaim** ordering for crash-safe resumability.
- **Reclaim is deferred by default**: a serve that began streaming from
chunks before the flip may still be reading those chunk files, so
deleting them mid-stream would truncate that transfer (the failure class
#1296/#1297 fixed). Orphaned chunks are left for the GC.
`--force-reclaim` opts into immediate, dedup-safe reclamation for
drained/maintenance-window runs.
- Sentinels: `ErrNarAlreadyWholeFile`, `ErrNoNarHashToVerify` (no
`NarHash` → left chunked, not de-chunked unverified),
`ErrNarHashMismatch`.
### CLI — `ncps migrate-chunks-to-nar`
Mirrors `migrate-nar-to-chunks` (storage/db/lock flags, `errgroup`
concurrency, `--dry-run`). Adds `--force-reclaim`. Per-NAR failures are
isolated (the batch continues) and the command exits non-zero if any NAR
failed. Registered in the root command.
### Helm chart
Opt-in `migrate-chunks-to-nar` Job (`post-install`/`post-upgrade` hook)
with `migrateChunksToNar.{enabled,dryRun,forceReclaim,concurrency}`,
reusing the deployment's db/storage/redis config.
### Docs
New "Operations / Chunks to NAR Migration" page (CLI, `--dry-run`,
`--force-reclaim` with the in-flight-serve safety note, the Helm Job,
verification/skip behavior, failure isolation); linked from the
Operations index and the CDC feature page;
`--cache-cdc-chunk-wait-timeout` documented in the CDC flags table.
### openspec
New `chunks-to-nar-migration` capability (proposal/design/specs/tasks),
archived and synced.
## Test plan
- [x] TDD, RED-verified. Cache tests under `-race`:
reconstruct+verify+store, record flip, default-leaves-chunks-for-GC,
force-reclaim-deletes-orphans, force-reclaim-retains-shared.
- [x] CLI tests: success (default-defer), force-reclaim,
dry-run-makes-no-changes, hash-mismatch → non-zero exit without
destroying data.
- [x] `task fmt` / `task lint` (0 issues) / `task test` green; 146 helm
unittests pass.
- [ ] CI `nix flake check`
---------
Co-authored-by: Claude Opus 4.8 <[email protected]>
Summary
Closes the remaining gaps behind the "phantom nar_file" defect — permanent
error: file 'nar/<hash>.nar.xz' does not exist404s for paths whose narinfowas just served. A backing-less
nar_filerow (total_chunks=0,chunking_started_at=NULL) left by a failed background download was treated asservable and short-circuited
GET /narto a terminal 404. Prior PRs(#1255–#1290) fixed the core read path; this hardens the edges and prevents the
recurring regression.
GOAWAYto also coverhttp2: timeout awaiting response headers, connection reset, and broken pipevia
isRetriableTransportError. Genuine 404s return a response (not atransport error) and stay non-retryable.
servability checks in
GetNarandprePullNar'shasAssetbehind oneisServable()predicate (+narFileServable()), so a placeholder row isnever servable and the regression can't return via divergent checks.
Behavior-preserving.
runCDCLazyRecoverynow skips backing-less stuck rows.BackgroundMigrateNarToChunkscan only chunk a store-present NAR, sore-driving placeholder/genuinely-absent rows every interval was futile
error fetching nar from store: not foundspam that indefinitely retriedunmigratable hashes. Such rows are recovered on demand by
GetNar.No schema migration. OpenSpec change
fix-phantom-nar-cache-missarchived andits delta specs synced into
openspec/specs/.Test plan
task fmtclean; changed packages lint cleantask testgreen (all packages;pkg/cache+pkg/cache/upstreamunder-race)phantom_recovery_test.go— reproduces narinfo 200 → failed download → recovery on next request, plus the genuine-404 pathtransient_retry_test.go— new retriable errors retried; genuine 404 not retriedrecovery_skip_internal_test.go— sweep skips backing-less rows, re-drives store-present ones (RED→GREEN verified)