Repository navigation
fix(cache): address review feedback on #1296/#1297 - #1298
Conversation
|
This change is part of the following stack: Change managed by git-spice. |
📝 WalkthroughSummary by CodeRabbit
WalkthroughPersists 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. ChangesCache Recovery and Upstream Stability
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 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 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.
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
pkg/cache/upstream/cache.go (1)
375-389: ⚡ Quick winAvoid “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
📒 Files selected for processing (5)
pkg/cache/cache.gopkg/cache/recovery_cursor_internal_test.gopkg/cache/recovery_gc_multi_internal_test.gopkg/cache/upstream/backoff_guard_test.gopkg/cache/upstream/cache.go
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]>
a82f34d to
d23383f
Compare
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]>
91b0349 to
ce9ca59
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@pkg/cache/cache.go`:
- Around line 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
📒 Files selected for processing (6)
pkg/cache/cache.gopkg/cache/recovery_cursor_internal_test.gopkg/cache/recovery_gc_internal_test.gopkg/cache/recovery_gc_multi_internal_test.gopkg/cache/upstream/backoff_guard_test.gopkg/cache/upstream/cache.go
🚧 Files skipped from review as they are similar to previous changes (1)
- pkg/cache/upstream/cache.go
| id, err := strconv.Atoi(e.Value) | ||
| if err != nil || id < 0 { | ||
| return 0 | ||
| } |
There was a problem hiding this comment.
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.
| 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.
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]>
ce9ca59 to
5c7d573
Compare
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
pkg/cache/cache.go (1)
6506-6515:⚠️ Potential issue | 🟠 Major | ⚡ Quick winPersist 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
📒 Files selected for processing (6)
pkg/cache/cache.gopkg/cache/recovery_cursor_internal_test.gopkg/cache/recovery_gc_internal_test.gopkg/cache/recovery_gc_multi_internal_test.gopkg/cache/upstream/backoff_guard_test.gopkg/cache/upstream/cache.go
🚧 Files skipped from review as they are similar to previous changes (1)
- pkg/cache/upstream/cache.go
…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]>
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-recoverylock 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) vialoadRecoveryCursor/saveRecoveryCursor. Thedistributed 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, soa 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):
waitRetryBackoffranafter the last failed attempt too, padding the latency of an already-doomed request.
Guard with
i < defaultHTTPRetries-1(and flattendoRequestinto guard clauses).Test plan
task fmtclean; changed packages lint cleanpkg/cache/...(cache + upstream) pass under-race; full unit suite greenTestRunCDCLazyRecoveryCursorPersists(persists + resumes across a fresh closure)TestRecoveryGCKeepsWhenAnyLinkedNarInfoPresentTestDoRequest_NoBackoffOnFinalAttempt