Repository navigation
feat(cache): CDC recovery follow-ups (GC, backoff, streaming) - #1297
Conversation
|
This change is part of the following stack: Change managed by git-spice. |
📝 WalkthroughSummary by CodeRabbit
WalkthroughThis PR implements three CDC recovery hardening items: provable GC for backing-less ChangesCDC Recovery and Resilience Improvements
Sequence Diagram(s)sequenceDiagram
participant ComponentA
participant ComponentB
ComponentA->>ComponentB: observable interaction
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related issues
Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
Comment |
There was a problem hiding this comment.
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.
b8c4734 to
a82f34d
Compare
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]>
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]>
a82f34d to
d23383f
Compare
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]>
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]>
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 `@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
📒 Files selected for processing (14)
openspec/changes/archive/2026-05-29-cdc-recovery-followups/.openspec.yamlopenspec/changes/archive/2026-05-29-cdc-recovery-followups/design.mdopenspec/changes/archive/2026-05-29-cdc-recovery-followups/proposal.mdopenspec/changes/archive/2026-05-29-cdc-recovery-followups/specs/cdc-chunking/spec.mdopenspec/changes/archive/2026-05-29-cdc-recovery-followups/specs/upstream-fetch-resilience/spec.mdopenspec/changes/archive/2026-05-29-cdc-recovery-followups/tasks.mdopenspec/specs/cdc-chunking/spec.mdopenspec/specs/upstream-fetch-resilience/spec.mdpkg/cache/cache.gopkg/cache/recovery_gc_internal_test.gopkg/cache/streaming_abort_internal_test.gopkg/cache/upstream/backoff_test.gopkg/cache/upstream/cache.gopkg/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
| 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 |
There was a problem hiding this comment.
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.
| 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.
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]>
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]>
## 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
Three hardening follow-ups left over from the archived
fix-phantom-nar-cache-misschange (and its keyset-cursor commit), stacked on #1296. OpenSpec change
cdc-recovery-followups(proposal/design/specs/tasks, all 17 tasks complete,/opsx:verifyclean, archived).Placeholder-row GC (
feat(cache): GC genuinely-absent placeholder rows):the CDC lazy-recovery sweep skipped backing-less
nar_fileplaceholder rows butnever cleared them, so rows for NARs genuinely gone upstream accumulated and were
re-scanned every cursor cycle. New
upstream.NarInfoExistencereturns a tri-stateExistence{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 CASCADEcleans uplinks. 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):doRequestretried transient transport errors (GOAWAY, http2 header timeout,conn reset, broken pipe) immediately. Add a capped exponential
waitRetryBackoff(base
defaultRetryBackoff, capdefaultRetryBackoffCap, overrideOptions.RetryBackoff) that respectsctxcancellation. Genuine 404 still neverretries (it returns a response, not a transport error).
Streaming fast-fail (
fix(cache): fast-fail stalled progressive streaming):streamProgressiveChunksonly failed a stalled stream after the 30s per-chunktimeout. Add a stale-lock fast-fail (
time.Since(chunking_started_at) > cdcChunkingLockTTL→ not-found in ~200ms), never closing a truncated 200.Test plan
task fmtclean; changed packages lint cleantask testgreen;pkg/cache/...(cache + upstream) under-raceTestRecoveryGC{DeletesGenuinelyAbsent,KeepsPresentUpstream,KeepsOnTransientProbe,SkipsFresh},TestNarInfoExistenceTestDoRequest_{RetriesUseBackoff,BackoffRespectsContextCancellation,GenuineNotFoundIsNotRetried}TestGetNarFromChunks_{AbortedChunkingErrorsNotShortBody,StalledChunkingFailsFast}