Skip to content

fix(cache): address review feedback on #1296/#1297 - #1298

Merged
kalbasit merged 5 commits into
mainfrom
user/wnasreddine/cdc-recovery-review-fixes
May 30, 2026
Merged

kalbasit merged 5 commits into
mainfrom
user/wnasreddine/cdc-recovery-review-fixes

Conversation

@kalbasit

Copy link
Copy Markdown
Owner

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, fix(cache): harden NAR cache-miss recovery & retry #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, feat(cache): CDC recovery follow-ups (GC, backoff, streaming) #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, feat(cache): CDC recovery follow-ups (GC, backoff, streaming) #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

  • task fmt clean; changed packages lint clean
  • pkg/cache/... (cache + upstream) pass under -race; full unit suite green
  • Cursor: TestRunCDCLazyRecoveryCursorPersists (persists + resumes across a fresh closure)
  • GC: TestRecoveryGCKeepsWhenAnyLinkedNarInfoPresent
  • Backoff: TestDoRequest_NoBackoffOnFinalAttempt
  • CI cohorts 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. 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

  • Improvements

    • CDC lazy-recovery cursor now persists in the database so recovery can resume across restarts.
    • Placeholder file GC now checks all linked metadata before deleting; orphaned placeholders are removed, others retained for recovery.
    • Upstream request retries skip backoff on the final attempt to avoid unnecessary delay.
  • Tests

    • Added tests covering cursor persistence, link-aware GC behavior, and final-attempt backoff behavior.

Walkthrough

Persists and resumes the CDC lazy-recovery keyset cursor; GC now checks every narinfo linked to a backing-less nar_file before deleting (deletes outright when no links); upstream retry loop skips backoff on the final attempt. Tests added for cursor persistence, multi-narinfo GC, and final-attempt backoff behavior.

Changes

Cache Recovery and Upstream Stability

Layer / File(s) Summary
CDC Recovery Cursor Persistence
pkg/cache/cache.go, pkg/cache/recovery_cursor_internal_test.go
Adds cdc_lazy_recovery_cursor persistence via Cache.loadRecoveryCursor / Cache.saveRecoveryCursor using the configentry table; runCDCLazyRecovery loads the cursor at start and saves it after batch advances or when no rows (wrap-to-0). Includes tests validating persistence and wrap behavior.
Recovery GC Multi-Narinfo Verification
pkg/cache/cache.go, pkg/cache/recovery_gc_internal_test.go, pkg/cache/recovery_gc_multi_internal_test.go
Rewrites gcOrSkipBackingLessNarFile to enumerate all narinfo rows linked through narinfo_nar_files, delete the placeholder only when every linked narinfo is absent upstream, delete placeholders with zero links outright, and include narinfo_count in deletion logs. Tests updated/added to cover linked/unlinked cases.
Upstream Request Retry Backoff Optimization
pkg/cache/upstream/cache.go, pkg/cache/upstream/backoff_guard_test.go
Refactors doRequest to early-return on success/non-retriable errors, classify retriable transport errors, and skip the exponential backoff wait on the final retry attempt. Adds test ensuring no final-attempt backoff delay.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • kalbasit/ncps#1204: Refactors the Ent-based stuck-file query in runCDCLazyRecovery that this PR builds upon for cursor persistence.

Suggested labels

bug, size:L

"I hop the DB to save the trail,
A tiny cursor in a row of pale,
I count the links before I prune,
And skip one last nap when retries tune,
A rabbit's cheer — persisted and hale."

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main objective of the PR—addressing review feedback on two prior changes with three specific fixes.
Description check ✅ Passed The description clearly relates to the changeset by explaining the three fixes (cursor persistence, GC improvement, and backoff skip), test plan, and context within the stacked PR series.
Docstring Coverage ✅ Passed Docstring coverage is 80.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

Comment @coderabbitai help to get the list of available commands and usage tips.

@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 improves the CDC lazy recovery process by persisting the keyset cursor in the database to survive restarts and lock handoffs, ensuring backing-less placeholders are only garbage-collected if all linked narinfos are absent upstream, and optimizing upstream HTTP retries by skipping backoff on the final attempt. The review feedback highlights two key improvement opportunities: first, to avoid silently resetting the recovery cursor to 0 on transient database query failures (which could cause starvation), and second, to immediately garbage-collect orphaned nar_file entries with no linked narinfos instead of skipping them.

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

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

375-389: ⚡ Quick win

Avoid “retrying request” on the terminal attempt.

At Line 375, the log message says retrying for every retriable error, but Line 384 skips backoff/retry on the last attempt. That makes terminal failures look like another retry was scheduled.

Suggested adjustment
-		zerolog.Ctx(ctx).Warn().
-			Err(err).
-			Int("attempt", i+1).
-			Int("max_retries", defaultHTTPRetries).
-			Msg("transient transport error from upstream, retrying request")
-
 		// Back off before retrying so a brown-out upstream is not hammered, aborting
 		// promptly if the context is cancelled. Skip the wait on the final attempt —
 		// no retry follows it, so a backoff would only add latency.
 		if i < defaultHTTPRetries-1 {
+			zerolog.Ctx(ctx).Warn().
+				Err(err).
+				Int("attempt", i+1).
+				Int("max_retries", defaultHTTPRetries).
+				Msg("transient transport error from upstream, retrying request")
 			if waitErr := c.waitRetryBackoff(ctx, i); waitErr != nil {
 				return nil, waitErr
 			}
+		} else {
+			zerolog.Ctx(ctx).Warn().
+				Err(err).
+				Int("attempt", i+1).
+				Int("max_retries", defaultHTTPRetries).
+				Msg("transient transport error from upstream, retries exhausted")
 		}
🤖 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/upstream/cache.go` around lines 375 - 389, The warning log
currently always says "retrying request" even on the terminal attempt; update
the zerolog warning in the retry loop (the block that calls
zerolog.Ctx(ctx).Warn().Err(err).Int("attempt", i+1).Int("max_retries",
defaultHTTPRetries)) so the message reflects whether another retry will occur:
if i < defaultHTTPRetries-1 log "transient transport error from upstream, will
retry request" (or similar), otherwise log "transient transport error from
upstream, no more retries" (or remove "retrying") to match the logic that skips
waitRetryBackoff(ctx, i) on the final attempt. Ensure the change references
defaultHTTPRetries and the waitRetryBackoff call so the log message and control
flow stay consistent.
🤖 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 6619-6622: The code currently calls
c.dbClient.Ent().NarInfo.Query().Where(entnarinfo.URL(narURL.String())).All(ctx),
which only matches NarInfo by URL and can miss NarInfo rows linked via the
nar_info_nar_files relation; change the lookup to use the relation instead
(e.g., query NarInfo by its linked NarFiles or start from NarFile and traverse
to NarInfo) so all linked NarInfos are returned before GC — for example, replace
the entnarinfo.URL(...) predicate with a relation-based predicate such as
entnarinfo.HasNarFilesWith(entnarfile.URL(narURL.String())) or use
NarFile.Query().Where(...).QueryNarInfo().All(ctx) so the code considers
nar_info_nar_files links when deciding to keep placeholders.

In `@pkg/cache/upstream/backoff_guard_test.go`:
- Around line 44-55: The test currently only checks elapsed time but may miss
"no-retry" regressions; modify the test that calls c.GetNarInfo in
backoff_guard_test.go to record and assert the actual retry/attempt count:
increment a counter inside the fake upstream/mock used by the test (or wrap the
upstream handler used by GetNarInfo) on each request and after the call assert
the counter equals the expected attempts (3 for base + 2 retries), keeping the
existing timing assertion intact.

---

Nitpick comments:
In `@pkg/cache/upstream/cache.go`:
- Around line 375-389: The warning log currently always says "retrying request"
even on the terminal attempt; update the zerolog warning in the retry loop (the
block that calls zerolog.Ctx(ctx).Warn().Err(err).Int("attempt",
i+1).Int("max_retries", defaultHTTPRetries)) so the message reflects whether
another retry will occur: if i < defaultHTTPRetries-1 log "transient transport
error from upstream, will retry request" (or similar), otherwise log "transient
transport error from upstream, no more retries" (or remove "retrying") to match
the logic that skips waitRetryBackoff(ctx, i) on the final attempt. Ensure the
change references defaultHTTPRetries and the waitRetryBackoff call so the log
message and control flow stay consistent.
🪄 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: c06f9fe0-6e59-4cab-b750-494455660ae4

📥 Commits

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

📒 Files selected for processing (5)
  • pkg/cache/cache.go
  • pkg/cache/recovery_cursor_internal_test.go
  • pkg/cache/recovery_gc_multi_internal_test.go
  • pkg/cache/upstream/backoff_guard_test.go
  • pkg/cache/upstream/cache.go

Comment thread pkg/cache/cache.go Resolved
kalbasit added a commit that referenced this pull request May 30, 2026
Addresses review feedback on #1298:

- gcOrSkipBackingLessNarFile resolves linked narinfos via the
  narinfo_nar_files relation instead of URL equality, which is narrower
  and could miss links and wrongly delete a placeholder
  (thread PRRT_kwDONV6tZs6F1u6o).
- A nar_file with no linked narinfo is an orphan that can never be
  served, so garbage-collect it outright instead of re-scanning it every
  sweep forever (thread PRRT_kwDONV6tZs6F1tmB).
- loadRecoveryCursor logs a warning on non-not-found DB errors rather
  than silently resetting the scan to 0, which could revive the low-id
  starvation the cursor prevents (thread PRRT_kwDONV6tZs6F1tl_).

GC test fixtures now link narinfos via narinfo_nar_files; adds an
orphan-GC regression test.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
kalbasit added a commit that referenced this pull request May 30, 2026
Add an explicit attempt-count assertion (3 == defaultHTTPRetries) so the
timing-only check cannot pass if retries are accidentally skipped.
Addresses review feedback on #1298 (thread PRRT_kwDONV6tZs6F1u6u).

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
Addresses review feedback on #1298:

- gcOrSkipBackingLessNarFile resolves linked narinfos via the
  narinfo_nar_files relation instead of URL equality, which is narrower
  and could miss links and wrongly delete a placeholder
  (thread PRRT_kwDONV6tZs6F1u6o).
- A nar_file with no linked narinfo is an orphan that can never be
  served, so garbage-collect it outright instead of re-scanning it every
  sweep forever (thread PRRT_kwDONV6tZs6F1tmB).
- loadRecoveryCursor logs a warning on non-not-found DB errors rather
  than silently resetting the scan to 0, which could revive the low-id
  starvation the cursor prevents (thread PRRT_kwDONV6tZs6F1tl_).

GC test fixtures now link narinfos via narinfo_nar_files; adds an
orphan-GC regression test.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
kalbasit added a commit that referenced this pull request May 30, 2026
Add an explicit attempt-count assertion (3 == defaultHTTPRetries) so the
timing-only check cannot pass if retries are accidentally skipped.
Addresses review feedback on #1298 (thread PRRT_kwDONV6tZs6F1u6u).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@kalbasit
kalbasit force-pushed the user/wnasreddine/cdc-recovery-review-fixes branch from 91b0349 to ce9ca59 Compare May 30, 2026 05:53

@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 6589-6592: When a persisted cursor value fails to parse or is
negative, log the malformed value and error before returning 0: detect the
failure around the strconv.Atoi(e.Value) check (using variables id, err and
e.Value), write a clear debug/error log entry that includes e.Value and err (or
note negative id) via the package's existing logger (or log.Printf if none),
then continue to return 0 as before.
🪄 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: 57dd7477-3d9b-4577-8713-3ed64f132208

📥 Commits

Reviewing files that changed from the base of the PR and between 0feb89e and ce9ca59.

📒 Files selected for processing (6)
  • pkg/cache/cache.go
  • pkg/cache/recovery_cursor_internal_test.go
  • pkg/cache/recovery_gc_internal_test.go
  • pkg/cache/recovery_gc_multi_internal_test.go
  • pkg/cache/upstream/backoff_guard_test.go
  • pkg/cache/upstream/cache.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/cache/upstream/cache.go

Comment thread pkg/cache/cache.go
Comment on lines +6589 to +6592
id, err := strconv.Atoi(e.Value)
if err != nil || id < 0 {
return 0
}

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

Log malformed persisted cursor values before resetting to 0.

A malformed/negative DB cursor currently falls back silently, which makes starvation regressions harder to diagnose in production.

Suggested patch
 	id, err := strconv.Atoi(e.Value)
 	if err != nil || id < 0 {
+		zerolog.Ctx(ctx).Warn().
+			Str("value", e.Value).
+			Msg("invalid CDC lazy-recovery cursor value; resuming from 0")
 		return 0
 	}
📝 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
id, err := strconv.Atoi(e.Value)
if err != nil || id < 0 {
return 0
}
id, err := strconv.Atoi(e.Value)
if err != nil || id < 0 {
zerolog.Ctx(ctx).Warn().
Str("value", e.Value).
Msg("invalid CDC lazy-recovery cursor value; resuming from 0")
return 0
}
🤖 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 6589 - 6592, When a persisted cursor value
fails to parse or is negative, log the malformed value and error before
returning 0: detect the failure around the strconv.Atoi(e.Value) check (using
variables id, err and e.Value), write a clear debug/error log entry that
includes e.Value and err (or note negative id) via the package's existing logger
(or log.Printf if none), then continue to return 0 as before.

Base automatically changed from user/wnasreddine/cdc-recovery-followups to main May 30, 2026 06:00
@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 and others added 5 commits May 30, 2026 06:00
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]>
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]>
Addresses review feedback on #1298:

- gcOrSkipBackingLessNarFile resolves linked narinfos via the
  narinfo_nar_files relation instead of URL equality, which is narrower
  and could miss links and wrongly delete a placeholder
  (thread PRRT_kwDONV6tZs6F1u6o).
- A nar_file with no linked narinfo is an orphan that can never be
  served, so garbage-collect it outright instead of re-scanning it every
  sweep forever (thread PRRT_kwDONV6tZs6F1tmB).
- loadRecoveryCursor logs a warning on non-not-found DB errors rather
  than silently resetting the scan to 0, which could revive the low-id
  starvation the cursor prevents (thread PRRT_kwDONV6tZs6F1tl_).

GC test fixtures now link narinfos via narinfo_nar_files; adds an
orphan-GC regression test.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Add an explicit attempt-count assertion (3 == defaultHTTPRetries) so the
timing-only check cannot pass if retries are accidentally skipped.
Addresses review feedback on #1298 (thread PRRT_kwDONV6tZs6F1u6u).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@kalbasit
kalbasit force-pushed the user/wnasreddine/cdc-recovery-review-fixes branch from ce9ca59 to 5c7d573 Compare May 30, 2026 06:00
@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
@kalbasit
kalbasit enabled auto-merge (squash) May 30, 2026 06:01

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

6506-6515: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Persist the recovery cursor after processing the selected batch.

Saving the cursor at Line 6514 before processing makes this path at-most-once on crash: a restart can skip unprocessed rows until wrap-around.

💡 Proposed change
-			cursorID = stuckFiles[len(stuckFiles)-1].ID
-			if len(stuckFiles) < batchSize {
-				cursorID = 0
-			}
-
-			c.saveRecoveryCursor(ctx, cursorID)
+			nextCursorID := stuckFiles[len(stuckFiles)-1].ID
+			if len(stuckFiles) < batchSize {
+				nextCursorID = 0
+			}
@@
 			for _, stuckFile := range stuckFiles {
 				// ... process rows ...
 			}
+
+			c.saveRecoveryCursor(ctx, nextCursorID)
🤖 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 6506 - 6515, The recovery cursor is being
persisted before the batch is processed which makes recovery at-most-once; move
the call to c.saveRecoveryCursor(ctx, cursorID) so it runs after the selected
batch has been fully processed (i.e., after handling stuckFiles for the current
iteration), ensuring cursorID (computed from stuckFiles[len(stuckFiles)-1].ID or
0 when len(stuckFiles)<batchSize) is saved only once processing completes.
🤖 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 6506-6515: The recovery cursor is being persisted before the batch
is processed which makes recovery at-most-once; move the call to
c.saveRecoveryCursor(ctx, cursorID) so it runs after the selected batch has been
fully processed (i.e., after handling stuckFiles for the current iteration),
ensuring cursorID (computed from stuckFiles[len(stuckFiles)-1].ID or 0 when
len(stuckFiles)<batchSize) is saved only once processing completes.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 027786e7-6461-4c75-9969-88e4438c6eea

📥 Commits

Reviewing files that changed from the base of the PR and between ce9ca59 and 5c7d573.

📒 Files selected for processing (6)
  • pkg/cache/cache.go
  • pkg/cache/recovery_cursor_internal_test.go
  • pkg/cache/recovery_gc_internal_test.go
  • pkg/cache/recovery_gc_multi_internal_test.go
  • pkg/cache/upstream/backoff_guard_test.go
  • pkg/cache/upstream/cache.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/cache/upstream/cache.go

@kalbasit
kalbasit merged commit 7d071cf into main May 30, 2026
36 checks passed
@kalbasit
kalbasit deleted the user/wnasreddine/cdc-recovery-review-fixes branch May 30, 2026 06:08
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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