Skip to content

feat(cache): CDC recovery follow-ups (GC, backoff, streaming) - #1297

Merged
kalbasit merged 6 commits into
mainfrom
user/wnasreddine/cdc-recovery-followups
May 30, 2026
Merged

kalbasit merged 6 commits into
mainfrom
user/wnasreddine/cdc-recovery-followups

Conversation

@kalbasit

Copy link
Copy Markdown
Owner

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

  • task fmt clean; changed packages lint clean
  • task test green; pkg/cache/... (cache + upstream) under -race
  • GC: TestRecoveryGC{DeletesGenuinelyAbsent,KeepsPresentUpstream,KeepsOnTransientProbe,SkipsFresh}, TestNarInfoExistence
  • Backoff: TestDoRequest_{RetriesUseBackoff,BackoffRespectsContextCancellation,GenuineNotFoundIsNotRetried}
  • Streaming: TestGetNarFromChunks_{AbortedChunkingErrorsNotShortBody,StalledChunkingFailsFast}
  • CI cohorts (postgres/mysql/s3/redis) green

@kalbasit

kalbasit commented May 30, 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 May 30, 2026
@coderabbitai

coderabbitai Bot commented May 30, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Summary by CodeRabbit

  • New Features

    • Garbage-collection of backing-less placeholder cache entries when definitively absent upstream.
    • Capped, context-aware backoff for transient upstream fetch retries.
  • Bug Fixes

    • Streaming aborts/stalls now surface as errors (no truncated-success bodies).
    • Stale chunking locks detected and fail fast during progressive streaming.
  • Documentation

    • Added specs, design notes, proposal and task checklist for recovery GC and fetch resilience.
  • Tests

    • New tests for recovery GC, streaming abort/stall, existence probing, and backoff behavior.

Walkthrough

This PR implements three CDC recovery hardening items: provable GC for backing-less nar_file placeholders using tri-state upstream probes and bounded checks, fail-fast stale-lock detection in progressive streaming, and capped/context-aware backoff for transient upstream retries, plus tests and spec updates.

Changes

CDC Recovery and Resilience Improvements

Layer / File(s) Summary
Specifications and Architecture Decisions
openspec/changes/archive/2026-05-29-cdc-recovery-followups/*, openspec/specs/cdc-chunking/spec.md, openspec/specs/upstream-fetch-resilience/spec.md
Adds archived proposal, design, tasks, and capability specs formalizing GC rules for backing-less placeholders, upstream fetch resilience (bounded backoff, no 404 retries), and streaming abort/stall test requirements (decisions D1–D4).
Upstream Cache Existence Probing and Retry Backoff
pkg/cache/upstream/cache.go, pkg/cache/upstream/backoff_test.go, pkg/cache/upstream/existence_test.go
Introduces Existence tri-state and Cache.NarInfoExistence(ctx,hash) (HEAD-based mapping), configurable Options.RetryBackoff, capped exponential waitRetryBackoff() honoring ctx cancellation, integrates backoff into retry path, and adds timing/cancellation tests.
CDC Recovery GC for Backing-less Placeholders
pkg/cache/cache.go, pkg/cache/recovery_gc_internal_test.go
runCDCLazyRecovery now invokes gcOrSkipBackingLessNarFile() which uses conservative narInfoGenuinelyAbsentUpstream() to decide deletion; placeholder deletion occurs only when provably absent and respects cutoff; tests cover absent/present/transient/fresh-cutoff behaviors.
Progressive Streaming Stale-Lock Fail-Fast
pkg/cache/cache.go, pkg/cache/streaming_abort_internal_test.go
streamProgressiveChunks now fails fast with storage.ErrNotFound when chunking_started_at is stale and total_chunks==0 (initial and inner-loop checks). Adds tests to ensure aborted and stalled chunking return errors and do not produce short truncated bodies.

Sequence Diagram(s)

sequenceDiagram
  participant ComponentA
  participant ComponentB
  ComponentA->>ComponentB: observable interaction
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related issues

Possibly related PRs

  • kalbasit/ncps#1204: Related edits to CDC lazy-recovery and nar_file handling in pkg/cache/cache.go.
  • kalbasit/ncps#1207: Related CDC progressive chunk streaming changes intersecting streamProgressiveChunks.
  • kalbasit/ncps#1251: Related streaming/recovery adjustments in the same codepaths.

Suggested labels

size:L

Poem

🐰 I hopped through specs and test-run nights,
I probed upstreams and checked the lights,
When locks grew stale I stopped the race,
Collected ghosts with careful grace,
Backoff and tests keep retries right.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 64.29% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'feat(cache): CDC recovery follow-ups (GC, backoff, streaming)' directly reflects the main changes: placeholder-row garbage collection, retry backoff, and streaming fast-fail improvements as part of CDC recovery hardening.
Description check ✅ Passed The pull request description comprehensively outlines the three hardening follow-ups (placeholder-row GC, bounded retry backoff, and streaming fast-fail), references the tracked OpenSpec change and stack context, and details the test plan.
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 introduces garbage collection for unrecoverable backing-less placeholder nar_file rows during the CDC lazy-recovery sweep, adds fast-fail logic for stalled progressive chunk streaming, and implements bounded exponential backoff for transient upstream transport retries. The review feedback highlights two key improvements: first, querying all linked NarInfo records instead of just the first one to prevent premature deletion of shared nar_file rows, and second, skipping the backoff delay on the final retry attempt to avoid unnecessary latency on terminal failures.

Comment thread pkg/cache/cache.go Resolved
Comment thread pkg/cache/upstream/cache.go Resolved
@kalbasit
kalbasit force-pushed the user/wnasreddine/cdc-recovery-followups branch from b8c4734 to a82f34d Compare May 30, 2026 03:48
Base automatically changed from user/wnasreddine/more-failures to main May 30, 2026 05:52
@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels May 30, 2026
@kalbasit
kalbasit enabled auto-merge (squash) May 30, 2026 05:53
kalbasit and others added 6 commits May 30, 2026 05:53
Capture three residual follow-ups left over from the archived
fix-phantom-nar-cache-miss change (and its keyset-cursor commit) as a
ready-to-implement OpenSpec change, so they are tracked rather than lost:

- Garbage-collect provably-unrecoverable backing-less placeholder
  nar_file rows, which the recovery sweep currently skips (never clears)
  so they persist and are re-scanned forever.
- Add a dedicated regression test for the progressive-streaming
  abort/stall "never a truncated 200" behavior, currently only verified
  by inspection.
- Add bounded, context-aware backoff to upstream transient retries,
  which currently retry immediately (count-bounded only).

Proposal, design, per-capability delta specs (cdc-chunking,
upstream-fetch-resilience), and a TDD task list. openspec validate
passes. Implementation follows in subsequent commits on this branch.
doRequest retried transient transport errors (GOAWAY, http2 header
timeout, connection reset, broken pipe) immediately, count-bounded only,
which hammers a brown-out upstream. Add a capped exponential backoff
between retries via waitRetryBackoff: base defaultRetryBackoff doubling
per attempt up to defaultRetryBackoffCap, overridable per-cache with
Options.RetryBackoff (tests set a small value). The wait selects on
ctx.Done() so a cancelled request returns promptly instead of sleeping.

A genuine 404 returns a response rather than a transport error, so it
never reaches the retry/backoff path and stays non-retryable.

Implements tasks 3.1-3.4 of the cdc-recovery-followups change.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
streamProgressiveChunks only failed a stalled stream after the 30s
per-chunk timeout: a non-NULL but stale chunking_started_at (producer
died without clearing the lock, total_chunks still 0, no chunks) was not
distinguished from a live producer, so the reader blocked ~30s before
erroring. Add a stale-lock fast-fail at the initial and wait-loop record
checks — time.Since(chunking_started_at) > cdcChunkingLockTTL yields a
not-found error in ~200ms instead. The error still propagates through the
pipe so the response is a failed transfer, never a truncated 200.

Adds regression tests for both the aborted (chunking_started_at NULL,
already correct) and stalled states, pinning the
never-a-truncated-200 behavior. Implements tasks 2.1-2.3.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The CDC lazy-recovery sweep skipped backing-less placeholder nar_file
rows (no whole-file to migrate) but never cleared them, so rows for NARs
that are genuinely gone upstream accumulated and were re-scanned on every
keyset-cursor cycle forever.

Garbage-collect such rows when, and only when, they are provably gone:
- New upstream.Cache.NarInfoExistence(hash) returns a tri-state
  Existence{Present,Absent,Unknown}. It probes the narinfo path (HEAD,
  unambiguous) and — unlike HasNar/HasNarInfo — does NOT collapse a
  timeout into "absent": only a definitive 404 is Absent; timeout,
  transport error, and non-404 statuses are Unknown.
- runCDCLazyRecovery resolves the narinfo for a backing-less row and
  deletes the row only if EVERY healthy upstream reports Absent (at least
  one healthy upstream, none Present or Unknown). ON DELETE CASCADE cleans
  up narinfo_nar_files and nar_file_chunks links. A Present/Unknown probe,
  no healthy upstreams, or a row newer than the recovery cutoff all leave
  the row in place, so a transient outage or an in-flight download is
  never mistaken for genuine absence.

No schema migration. Implements tasks 1.1-1.7 of cdc-recovery-followups.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Sync the change's delta specs into the main specs and move the completed
change to the archive:
- cdc-chunking: add "Unrecoverable backing-less placeholder rows MUST be
  garbage-collected" requirement.
- upstream-fetch-resilience: new capability spec for bounded transient
  retry backoff.

All 17 tasks complete; implementation verified (/opsx:verify) with no
critical or warning issues.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@kalbasit
kalbasit force-pushed the user/wnasreddine/cdc-recovery-followups branch from a82f34d to d23383f Compare May 30, 2026 05:53
kalbasit added a commit that referenced this pull request May 30, 2026
waitRetryBackoff ran after every failed transient attempt, including the
last one (i == defaultHTTPRetries-1) which has no retry after it, just
padding the latency of an already-doomed request. Guard the wait with
i < defaultHTTPRetries-1, and flatten doRequest's retry block into guard
clauses to keep nestif complexity down. Addresses review feedback on
#1297.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
kalbasit added a commit that referenced this pull request May 30, 2026
gcOrSkipBackingLessNarFile resolved a single narinfo via First() and
deleted the nar_file if that one was absent upstream. Multiple store
paths can reference the same NAR (same URL), so a still-present narinfo
could be missed and an active NAR wrongly garbage-collected. Query all
linked narinfos and delete only when EVERY one is genuinely absent.
Addresses review feedback on #1297.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels May 30, 2026

@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

🤖 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-cdc-recovery-followups/proposal.md`:
- Around line 31-33: Update the wording to reference the actual probe contract:
replace the incorrect mention of upstream.Cache.HasNar HEAD with
upstream.NarInfoExistence (the HEAD-on-narinfo probe) and describe its tri-state
return values Present/Absent/Unknown as the determinant of upstream absence;
ensure you state that absence is only considered when NarInfoExistence returns
Absent and not when Unknown, and keep the caveat that GetNar must still be able
to re-create and download the NAR on demand.
🪄 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: 6545510c-6adf-4bf3-95e5-602501fc88b4

📥 Commits

Reviewing files that changed from the base of the PR and between a82f34d and d23383f.

📒 Files selected for processing (14)
  • openspec/changes/archive/2026-05-29-cdc-recovery-followups/.openspec.yaml
  • openspec/changes/archive/2026-05-29-cdc-recovery-followups/design.md
  • openspec/changes/archive/2026-05-29-cdc-recovery-followups/proposal.md
  • openspec/changes/archive/2026-05-29-cdc-recovery-followups/specs/cdc-chunking/spec.md
  • openspec/changes/archive/2026-05-29-cdc-recovery-followups/specs/upstream-fetch-resilience/spec.md
  • openspec/changes/archive/2026-05-29-cdc-recovery-followups/tasks.md
  • openspec/specs/cdc-chunking/spec.md
  • openspec/specs/upstream-fetch-resilience/spec.md
  • pkg/cache/cache.go
  • pkg/cache/recovery_gc_internal_test.go
  • pkg/cache/streaming_abort_internal_test.go
  • pkg/cache/upstream/backoff_test.go
  • pkg/cache/upstream/cache.go
  • pkg/cache/upstream/existence_test.go
✅ Files skipped from review due to trivial changes (5)
  • openspec/changes/archive/2026-05-29-cdc-recovery-followups/.openspec.yaml
  • openspec/changes/archive/2026-05-29-cdc-recovery-followups/tasks.md
  • openspec/changes/archive/2026-05-29-cdc-recovery-followups/specs/upstream-fetch-resilience/spec.md
  • openspec/specs/upstream-fetch-resilience/spec.md
  • openspec/changes/archive/2026-05-29-cdc-recovery-followups/design.md
🚧 Files skipped from review as they are similar to previous changes (3)
  • openspec/changes/archive/2026-05-29-cdc-recovery-followups/specs/cdc-chunking/spec.md
  • pkg/cache/upstream/cache.go
  • openspec/specs/cdc-chunking/spec.md

Comment on lines +31 to +33
e.g. confirmed genuinely absent upstream (`upstream.Cache.HasNar` HEAD returns a
definitive not-found) and/or its narinfo is gone — never when the NAR still exists
upstream (`GetNar` must still be able to re-create and download it on demand). FK

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Align upstream-absence wording with actual probe contract.

This text says absence is proven via upstream.Cache.HasNar HEAD, but the implemented contract uses upstream.NarInfoExistence (HEAD on narinfo) with tri-state semantics (Present/Absent/Unknown). Please update this section to avoid drift between spec and behavior.

Suggested wording update
-  e.g. confirmed genuinely absent upstream (`upstream.Cache.HasNar` HEAD returns a
-  definitive not-found) and/or its narinfo is gone — never when the NAR still exists
+  e.g. confirmed genuinely absent upstream (narinfo HEAD probe returns definitive
+  not-found via `upstream.NarInfoExistence == ExistenceAbsent`) — never when upstream
+  presence is `Present` or probe result is inconclusive (`Unknown`)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
e.g. confirmed genuinely absent upstream (`upstream.Cache.HasNar` HEAD returns a
definitive not-found) and/or its narinfo is gone — never when the NAR still exists
upstream (`GetNar` must still be able to re-create and download it on demand). FK
e.g. confirmed genuinely absent upstream (narinfo HEAD probe returns definitive
not-found via `upstream.NarInfoExistence == ExistenceAbsent`) — never when upstream
presence is `Present` or probe result is inconclusive (`Unknown`)
upstream (`GetNar` must still be able to re-create and download it on demand). FK
🤖 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 `@openspec/changes/archive/2026-05-29-cdc-recovery-followups/proposal.md`
around lines 31 - 33, Update the wording to reference the actual probe contract:
replace the incorrect mention of upstream.Cache.HasNar HEAD with
upstream.NarInfoExistence (the HEAD-on-narinfo probe) and describe its tri-state
return values Present/Absent/Unknown as the determinant of upstream absence;
ensure you state that absence is only considered when NarInfoExistence returns
Absent and not when Unknown, and keep the caveat that GetNar must still be able
to re-create and download the NAR on demand.

@kalbasit
kalbasit merged commit abbb7cb into main May 30, 2026
36 checks passed
@kalbasit
kalbasit deleted the user/wnasreddine/cdc-recovery-followups branch May 30, 2026 06:00
kalbasit added a commit that referenced this pull request May 30, 2026
waitRetryBackoff ran after every failed transient attempt, including the
last one (i == defaultHTTPRetries-1) which has no retry after it, just
padding the latency of an already-doomed request. Guard the wait with
i < defaultHTTPRetries-1, and flatten doRequest's retry block into guard
clauses to keep nestif complexity down. Addresses review feedback on
#1297.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
kalbasit added a commit that referenced this pull request May 30, 2026
gcOrSkipBackingLessNarFile resolved a single narinfo via First() and
deleted the nar_file if that one was absent upstream. Multiple store
paths can reference the same NAR (same URL), so a still-present narinfo
could be missed and an active NAR wrongly garbage-collected. Query all
linked narinfos and delete only when EVERY one is genuinely absent.
Addresses review feedback on #1297.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
kalbasit added a commit that referenced this pull request May 30, 2026
## 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]>
kalbasit added a commit that referenced this pull request May 30, 2026
…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]>
kalbasit added a commit that referenced this pull request May 30, 2026
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]>
kalbasit added a commit that referenced this pull request May 30, 2026
## 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]>
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