Skip to content

fix(cache): harden NAR cache-miss recovery & retry - #1296

Merged
kalbasit merged 8 commits into
mainfrom
user/wnasreddine/more-failures
May 30, 2026
Merged

kalbasit merged 8 commits into
mainfrom
user/wnasreddine/more-failures

Conversation

@kalbasit

Copy link
Copy Markdown
Owner

Summary

Closes the remaining gaps behind the "phantom nar_file" defect — permanent
error: file 'nar/<hash>.nar.xz' does not exist 404s for paths whose narinfo
was just served. A backing-less nar_file row (total_chunks=0,
chunking_started_at=NULL) left by a failed background download was treated as
servable and short-circuited GET /nar to a terminal 404. Prior PRs
(#1255–#1290) fixed the core read path; this hardens the edges and prevents the
recurring regression.

  • Upstream retry (D5): extend 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.
  • Single source of truth (D1): unify the duplicated, drift-prone
    servability checks in GetNar and prePullNar's hasAsset behind one
    isServable() predicate (+ narFileServable()), so a placeholder row is
    never servable and the regression can't return via divergent checks.
    Behavior-preserving.
  • Recovery sweep: runCDCLazyRecovery now skips backing-less stuck rows.
    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.

No schema migration. OpenSpec change fix-phantom-nar-cache-miss archived and
its delta specs synced into openspec/specs/.

Test plan

  • task fmt clean; changed packages lint clean
  • task test green (all packages; pkg/cache + pkg/cache/upstream under -race)
  • phantom_recovery_test.go — reproduces narinfo 200 → failed download → recovery on next request, plus the genuine-404 path
  • transient_retry_test.go — new retriable errors retried; genuine 404 not retried
  • recovery_skip_internal_test.go — sweep skips backing-less rows, re-drives store-present ones (RED→GREEN verified)

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]>
@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. bug Something isn't working 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

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Treat backing-less nar_file rows as cache misses, centralize servability via isServable, expand transient upstream retry detection, skip backing-less rows in CDC lazy recovery, and add integration tests and specs enforcing streaming and recovery behavior.

Changes

Phantom NAR Cache Miss Fix

Layer / File(s) Summary
Specification & Design
openspec/changes/archive/2026-05-29-fix-phantom-nar-cache-miss/(.openspec.yaml, design.md, proposal.md, specs/*), openspec/specs/(cdc-chunking/spec.md, nar-cache-miss-recovery/spec.md, nar-concurrent-streaming/spec.md)
Design, proposal, task notes, and formal specs that require placeholder nar_file rows be non-servable, define GetNar re-download/retry semantics, mandate streaming integrity, and document migration/rollout considerations.
Upstream Transport Resilience
pkg/cache/upstream/cache.go, pkg/cache/upstream/transient_retry_test.go
Adds isRetriableTransportError and expands retry conditions for transient transport failures; tests ensure transient errors retry while real 404s are not retried.
Servability Predicate & Cache Read-Path Integration
pkg/cache/cache.go (GetNar, prePullNar, servability helpers)
Introduces narFileServable and Cache.isServable, updates GetNar and prePullNar to use isServable, and re-checks chunk availability when local downloads are active to avoid treating placeholders as servable.
CDC Lazy Recovery & Tests
pkg/cache/cache.go (runCDCLazyRecovery cursor and candidate filtering), pkg/cache/(phantom_recovery_test.go, recovery_skip_internal_test.go, cdc_test.go)
Adds a persistent keyset cursorID for recovery scans, skips re-driving backing-less stuck rows by checking HasNarInStore before scheduling chunking, and adds tests covering transient-failure recovery, genuine-404 behavior, and lazy-recovery skip/advance behavior with a counting store wrapper.
Migrations Test Serialization
migrations/equivalence_test.go
Serializes Ent/Atlas replay + named-diff across dialect subtests using a package mutex and adjusts error capture/assertion to avoid holding the lock during assertions.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related issues

Possibly related PRs

Suggested labels

merge-stack

🐰 I dug through phantom rows in the night,
Marked placeholders false and set retries right.
With isServable clear and CDC on guard,
Empty ghosts no longer answer hard.
Cache sleeps safe now — hop, code! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 54.55% 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 'fix(cache): harden NAR cache-miss recovery & retry' directly and clearly summarizes the main changes: hardening NAR cache-miss recovery and expanding retry logic for transport failures.
Description check ✅ Passed The description is comprehensive and directly related to the changeset, detailing upstream retry improvements, servability unification, recovery sweep changes, and test coverage for the phantom nar_file defect fixes.
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.


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

Comment thread pkg/cache/cache.go Resolved

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

📥 Commits

Reviewing files that changed from the base of the PR and between f3ce8ac and 1f1eb0b.

📒 Files selected for processing (16)
  • openspec/changes/archive/2026-05-29-fix-phantom-nar-cache-miss/.openspec.yaml
  • openspec/changes/archive/2026-05-29-fix-phantom-nar-cache-miss/design.md
  • openspec/changes/archive/2026-05-29-fix-phantom-nar-cache-miss/proposal.md
  • openspec/changes/archive/2026-05-29-fix-phantom-nar-cache-miss/specs/cdc-chunking/spec.md
  • openspec/changes/archive/2026-05-29-fix-phantom-nar-cache-miss/specs/nar-cache-miss-recovery/spec.md
  • openspec/changes/archive/2026-05-29-fix-phantom-nar-cache-miss/specs/nar-concurrent-streaming/spec.md
  • openspec/changes/archive/2026-05-29-fix-phantom-nar-cache-miss/tasks.md
  • openspec/specs/cdc-chunking/spec.md
  • openspec/specs/nar-cache-miss-recovery/spec.md
  • openspec/specs/nar-concurrent-streaming/spec.md
  • pkg/cache/cache.go
  • pkg/cache/cdc_test.go
  • pkg/cache/phantom_recovery_test.go
  • pkg/cache/recovery_skip_internal_test.go
  • pkg/cache/upstream/cache.go
  • pkg/cache/upstream/transient_retry_test.go

kalbasit and others added 3 commits May 29, 2026 19:39
"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]>
@kalbasit
kalbasit enabled auto-merge (squash) May 30, 2026 02:43
kalbasit and others added 2 commits May 29, 2026 19:57
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]>
@kalbasit
kalbasit disabled auto-merge May 30, 2026 03:08
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]>

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

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 50476b6f-0e97-410b-8d19-463c87a9b281

📥 Commits

Reviewing files that changed from the base of the PR and between 4abcdee and a78a6ec.

📒 Files selected for processing (1)
  • pkg/cache/cache.go

Comment thread pkg/cache/cache.go Resolved
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]>

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

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 lift

Persist the lazy-recovery cursor outside process memory.

cursorID only lives in this closure. After a pod restart—or whenever another instance wins the cdc-lazy-recovery lock—the scan starts over at 0, 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.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: bb71d67c-dd99-4eba-92b8-a0843067791f

📥 Commits

Reviewing files that changed from the base of the PR and between a78a6ec and d351afd.

📒 Files selected for processing (1)
  • pkg/cache/cache.go

@kalbasit
kalbasit merged commit 61a0717 into main May 30, 2026
41 of 54 checks passed
@kalbasit
kalbasit deleted the user/wnasreddine/more-failures branch May 30, 2026 05:52
kalbasit added a commit that referenced this pull request May 30, 2026
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

codecov Bot commented May 30, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 0.00%. Comparing base (f3ce8ac) to head (d351afd).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@     Coverage Diff      @@
##   main   #1296   +/-   ##
============================
============================

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

kalbasit added a commit that referenced this pull request May 30, 2026
## 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]>
kalbasit added a commit that referenced this pull request May 30, 2026
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]>
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]>
@coderabbitai coderabbitai Bot mentioned this pull request May 31, 2026
8 tasks done
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 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