Repository navigation
feat(cache): restart staging on holder death - #1357
Conversation
|
This change is part of the following stack:
Change managed by git-spice. |
|
Warning Review limit reached
More reviews will be available in 21 minutes and 41 seconds. Learn how PR review limits work. Your organization has run out of usage credits. Purchase more in the billing tab. ⌛ How to resolve this issue?After more reviews become available, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available. Please see our Fair Usage Limits Policy for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (3)
📝 WalkthroughWalkthroughThe PR reorders lock takeover coordination in ChangesCross-replica download takeover with staging cleanup
Sequence DiagramsequenceDiagram
participant Replica
participant LockHolder as Lock (Stale)
participant Staging
Replica->>LockHolder: TryLock (takeover attempt)
alt Takeover successful
LockHolder-->>Replica: lock acquired
Replica->>Staging: reclaimStaging (discard partial)
Replica->>Replica: record take_over outcome
else Takeover failed (peer holds lock)
LockHolder-->>Replica: lock not acquired
Replica->>Staging: check stagingServeReady
alt Staging available
Staging-->>Replica: ready parts
Replica->>Replica: record served_from_staging outcome
end
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Comment |
There was a problem hiding this comment.
Code Review
This pull request restructures the download coordination logic in pollForDownloadOrTakeOver to attempt lock acquisition (takeover) before serving from staging, ensuring that any partial staging left by a dead holder is discarded to prevent serving truncated data. It also adds unit tests to verify this behavior. The feedback suggests a minor improvement to reuse the already-detached ctx directly instead of wrapping coordCtx with context.WithoutCancel when reclaiming staging.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
|
@coderabbitai review |
✅ Action performedReview finished.
|
|
@coderabbitai review |
✅ Action performedReview finished.
|
|
@coderabbitai review |
✅ Action performedReview finished.
|
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
pkg/cache/inflight_staging_takeover_internal_test.go (1)
1-108:⚠️ Potential issue | 🔴 CriticalRun/attach fmt+lint+unit-test verification before merge
Taskfile.ymlexpects:
fmt:nix fmtlint:golangci-lint runtest:go test -race ./...In this environment
task/nixaren’t available, but:
gofmtchecks passed.golangci-lint run ./...fails with typecheck errors inpkg/database/errors.go(undefined: sqlite3.Error,sqlite3.ErrBusy,sqlite3.ErrLocked,sqlite3.ErrProtocol,sqlite3.ErrConstraint).go test -race ./...can’t run here unlessCGO_ENABLED=1(race requires cgo).Rerun
task fmt,task lint, andtask testin a proper dev/Nix shell and attach outputs.🤖 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/inflight_staging_takeover_internal_test.go` around lines 1 - 108, The CI/lint/tests step fails because Taskfile.yml expects running "task fmt/lint/test" but golangci-lint reports undefined sqlite3 symbols in pkg/database/errors.go (references to sqlite3.Error, sqlite3.ErrBusy, sqlite3.ErrLocked, sqlite3.ErrProtocol, sqlite3.ErrConstraint) and the race tests require CGO; fix by updating pkg/database/errors.go to avoid unconditional references to the cgo-only mattn/go-sqlite3 symbols (either wrap those references behind a build tag file that imports "github.com/mattn/go-sqlite3" only when CGO is enabled, or replace use with driver-level error checks or errno-mapped constants that don’t require the sqlite3 package), ensure Taskfile.yml commands are runnable in dev (document that tests with -race need CGO_ENABLED=1), and re-run task fmt, task lint (golangci-lint run ./...) and task test (go test -race ./...) in the proper Nix/dev shell to confirm the errors are resolved.Source: Coding guidelines
🤖 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 6452-6466: After TryLock succeeds (the call to
c.downloadLocker.TryLock inside the download takeover path), ensure the lock
refresher is running before calling reclaimStaging: either start the lock
refresher (via the lock's StartRefresher or c.downloadLocker.StartRefresher
helper) immediately after acquisition and use a child context tied to that
refresher for reclaimStaging, or run reclaimStaging under a temporary refresher
that refreshes until a bounded cleanup context completes; update the takeover
path in coordinateDownload so reclaimStaging is moved to after StartRefresher is
active (or wrapped by a temporary refresher) to prevent the lock from expiring
during the storage/DB cleanup.
---
Outside diff comments:
In `@pkg/cache/inflight_staging_takeover_internal_test.go`:
- Around line 1-108: The CI/lint/tests step fails because Taskfile.yml expects
running "task fmt/lint/test" but golangci-lint reports undefined sqlite3 symbols
in pkg/database/errors.go (references to sqlite3.Error, sqlite3.ErrBusy,
sqlite3.ErrLocked, sqlite3.ErrProtocol, sqlite3.ErrConstraint) and the race
tests require CGO; fix by updating pkg/database/errors.go to avoid unconditional
references to the cgo-only mattn/go-sqlite3 symbols (either wrap those
references behind a build tag file that imports "github.com/mattn/go-sqlite3"
only when CGO is enabled, or replace use with driver-level error checks or
errno-mapped constants that don’t require the sqlite3 package), ensure
Taskfile.yml commands are runnable in dev (document that tests with -race need
CGO_ENABLED=1), and re-run task fmt, task lint (golangci-lint run ./...) and
task test (go test -race ./...) in the proper Nix/dev shell to confirm the
errors are resolved.
🪄 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: ab29721b-d2c5-4ccb-a2c9-8a6c4d86ad71
📒 Files selected for processing (2)
pkg/cache/cache.gopkg/cache/inflight_staging_takeover_internal_test.go
Address review feedback on PR #1356: - Add a shutdownContext helper that ties a context to the cache's shutdownCh, and use it for both the retention-grace wait and the reclaim itself in scheduleStagingReclaim, so a stalled DeleteStagingParts/delete cannot keep Close() blocked on backgroundWG; context.Canceled is treated as a normal exit (PRRT_kwDONV6tZs6Hr3ky, PRRT_kwDONV6tZs6HsBRe). - AddInflightStagingGCCronJob now binds only the logger, not the registration context; each sweep derives a fresh shutdownContext, so a request/startup scoped ctx being cancelled can no longer silently disable later GC sweeps (PRRT_kwDONV6tZs6HsBRi). - reclaimStaging now deletes the staging_state row (via deleteStagingState) rather than resetting it: GC/post-completion reclaim is terminal, so resetting to "requested" would make the sweep resurrect the row forever. resetStagingState (reset) is reserved for the takeover path (#1357). Co-Authored-By: Claude Opus 4.8 <[email protected]>
0528185 to
2fd9bb8
Compare
Address review feedback on PR #1357: - Move the takeover staging cleanup out of pollForDownloadOrTakeOver into coordinateDownload, AFTER lock.StartRefresher is running. Previously the storage+DB cleanup ran in the window before the refresher started, so a slow cleanup could outlive downloadLockTTL and let another replica take the same hash mid-cleanup (PRRT_kwDONV6tZs6HsFwN). - Use the detached background ctx for the cleanup rather than re-wrapping coordCtx in context.WithoutCancel (PRRT_kwDONV6tZs6Hr25g). - The takeover now calls resetStagingForTakeover (discard truncated parts + reset staging_state to "requested") instead of reclaimStaging, so the fresh download re-stages from zero and a persisting cross-pod waiter is re-served rather than stranded (completes the #1351 reset-not-delete fix). Co-Authored-By: Claude Opus 4.8 <[email protected]>
b7e105b to
d640de5
Compare
Address review feedback on PR #1356: - Add a shutdownContext helper that ties a context to the cache's shutdownCh, and use it for both the retention-grace wait and the reclaim itself in scheduleStagingReclaim, so a stalled DeleteStagingParts/delete cannot keep Close() blocked on backgroundWG; context.Canceled is treated as a normal exit (PRRT_kwDONV6tZs6Hr3ky, PRRT_kwDONV6tZs6HsBRe). - AddInflightStagingGCCronJob now binds only the logger, not the registration context; each sweep derives a fresh shutdownContext, so a request/startup scoped ctx being cancelled can no longer silently disable later GC sweeps (PRRT_kwDONV6tZs6HsBRi). - reclaimStaging now deletes the staging_state row (via deleteStagingState) rather than resetting it: GC/post-completion reclaim is terminal, so resetting to "requested" would make the sweep resurrect the row forever. resetStagingState (reset) is reserved for the takeover path (#1357). Co-Authored-By: Claude Opus 4.8 <[email protected]>
36084d7 to
a9e99a9
Compare
Address review feedback on PR #1357: - Move the takeover staging cleanup out of pollForDownloadOrTakeOver into coordinateDownload, AFTER lock.StartRefresher is running. Previously the storage+DB cleanup ran in the window before the refresher started, so a slow cleanup could outlive downloadLockTTL and let another replica take the same hash mid-cleanup (PRRT_kwDONV6tZs6HsFwN). - Use the detached background ctx for the cleanup rather than re-wrapping coordCtx in context.WithoutCancel (PRRT_kwDONV6tZs6Hr25g). - The takeover now calls resetStagingForTakeover (discard truncated parts + reset staging_state to "requested") instead of reclaimStaging, so the fresh download re-stages from zero and a persisting cross-pod waiter is re-served rather than stranded (completes the #1351 reset-not-delete fix). Co-Authored-By: Claude Opus 4.8 <[email protected]>
c546455 to
66282cc
Compare
Address review feedback on PR #1356: - Add a shutdownContext helper that ties a context to the cache's shutdownCh, and use it for both the retention-grace wait and the reclaim itself in scheduleStagingReclaim, so a stalled DeleteStagingParts/delete cannot keep Close() blocked on backgroundWG; context.Canceled is treated as a normal exit (PRRT_kwDONV6tZs6Hr3ky, PRRT_kwDONV6tZs6HsBRe). - AddInflightStagingGCCronJob now binds only the logger, not the registration context; each sweep derives a fresh shutdownContext, so a request/startup scoped ctx being cancelled can no longer silently disable later GC sweeps (PRRT_kwDONV6tZs6HsBRi). - reclaimStaging now deletes the staging_state row (via deleteStagingState) rather than resetting it: GC/post-completion reclaim is terminal, so resetting to "requested" would make the sweep resurrect the row forever. resetStagingState (reset) is reserved for the takeover path (#1357). Co-Authored-By: Claude Opus 4.8 <[email protected]>
a9e99a9 to
72d5a4c
Compare
Address review feedback on PR #1357: - Move the takeover staging cleanup out of pollForDownloadOrTakeOver into coordinateDownload, AFTER lock.StartRefresher is running. Previously the storage+DB cleanup ran in the window before the refresher started, so a slow cleanup could outlive downloadLockTTL and let another replica take the same hash mid-cleanup (PRRT_kwDONV6tZs6HsFwN). - Use the detached background ctx for the cleanup rather than re-wrapping coordCtx in context.WithoutCancel (PRRT_kwDONV6tZs6Hr25g). - The takeover now calls resetStagingForTakeover (discard truncated parts + reset staging_state to "requested") instead of reclaimStaging, so the fresh download re-stages from zero and a persisting cross-pod waiter is re-served rather than stranded (completes the #1351 reset-not-delete fix). Co-Authored-By: Claude Opus 4.8 <[email protected]>
66282cc to
2c630bd
Compare
Address review feedback on PR #1356: - Add a shutdownContext helper that ties a context to the cache's shutdownCh, and use it for both the retention-grace wait and the reclaim itself in scheduleStagingReclaim, so a stalled DeleteStagingParts/delete cannot keep Close() blocked on backgroundWG; context.Canceled is treated as a normal exit (PRRT_kwDONV6tZs6Hr3ky, PRRT_kwDONV6tZs6HsBRe). - AddInflightStagingGCCronJob now binds only the logger, not the registration context; each sweep derives a fresh shutdownContext, so a request/startup scoped ctx being cancelled can no longer silently disable later GC sweeps (PRRT_kwDONV6tZs6HsBRi). - reclaimStaging now deletes the staging_state row (via deleteStagingState) rather than resetting it: GC/post-completion reclaim is terminal, so resetting to "requested" would make the sweep resurrect the row forever. resetStagingState (reset) is reserved for the takeover path (#1357). Co-Authored-By: Claude Opus 4.8 <[email protected]>
72d5a4c to
e762d04
Compare
Address review feedback on PR #1357: - Move the takeover staging cleanup out of pollForDownloadOrTakeOver into coordinateDownload, AFTER lock.StartRefresher is running. Previously the storage+DB cleanup ran in the window before the refresher started, so a slow cleanup could outlive downloadLockTTL and let another replica take the same hash mid-cleanup (PRRT_kwDONV6tZs6HsFwN). - Use the detached background ctx for the cleanup rather than re-wrapping coordCtx in context.WithoutCancel (PRRT_kwDONV6tZs6Hr25g). - The takeover now calls resetStagingForTakeover (discard truncated parts + reset staging_state to "requested") instead of reclaimStaging, so the fresh download re-stages from zero and a persisting cross-pod waiter is re-served rather than stranded (completes the #1351 reset-not-delete fix). Co-Authored-By: Claude Opus 4.8 <[email protected]>
2c630bd to
74d511a
Compare
e762d04 to
86adc4d
Compare
Address review feedback on PR #1356: - Add a shutdownContext helper that ties a context to the cache's shutdownCh, and use it for both the retention-grace wait and the reclaim itself in scheduleStagingReclaim, so a stalled DeleteStagingParts/delete cannot keep Close() blocked on backgroundWG; context.Canceled is treated as a normal exit (PRRT_kwDONV6tZs6Hr3ky, PRRT_kwDONV6tZs6HsBRe). - AddInflightStagingGCCronJob now binds only the logger, not the registration context; each sweep derives a fresh shutdownContext, so a request/startup scoped ctx being cancelled can no longer silently disable later GC sweeps (PRRT_kwDONV6tZs6HsBRi). - reclaimStaging now deletes the staging_state row (via deleteStagingState) rather than resetting it: GC/post-completion reclaim is terminal, so resetting to "requested" would make the sweep resurrect the row forever. resetStagingState (reset) is reserved for the takeover path (#1357). Co-Authored-By: Claude Opus 4.8 <[email protected]>
Address review feedback on PR #1357: - Move the takeover staging cleanup out of pollForDownloadOrTakeOver into coordinateDownload, AFTER lock.StartRefresher is running. Previously the storage+DB cleanup ran in the window before the refresher started, so a slow cleanup could outlive downloadLockTTL and let another replica take the same hash mid-cleanup (PRRT_kwDONV6tZs6HsFwN). - Use the detached background ctx for the cleanup rather than re-wrapping coordCtx in context.WithoutCancel (PRRT_kwDONV6tZs6Hr25g). - The takeover now calls resetStagingForTakeover (discard truncated parts + reset staging_state to "requested") instead of reclaimStaging, so the fresh download re-stages from zero and a persisting cross-pod waiter is re-served rather than stranded (completes the #1351 reset-not-delete fix). Co-Authored-By: Claude Opus 4.8 <[email protected]>
74d511a to
dbf22de
Compare
Holder-death takeover for in-flight staging (D5, group 9). In pollForDownloadOrTakeOver the lock re-acquisition (takeover) is now attempted BEFORE serving from staging: an acquirable lock means the holder is gone (died or failed), so its staging parts are at best a truncated prefix. On takeover the new owner discards the dead holder's partial part-objects and resets staging_state, then restarts the download from zero via the existing post-lock path and re-stages cleanly if contention persists. Reordering takeover ahead of the staging-serve branch also guarantees the correctness contract across a death+takeover transition: a reader tailing a never-completed staging set surfaces a stream error (the part-tailing reader's stall handling), never a clean EOF at a truncated length, and the orphaned parts are reclaimed by the takeover rather than tailed as if complete.
Address review feedback on PR #1357: - Move the takeover staging cleanup out of pollForDownloadOrTakeOver into coordinateDownload, AFTER lock.StartRefresher is running. Previously the storage+DB cleanup ran in the window before the refresher started, so a slow cleanup could outlive downloadLockTTL and let another replica take the same hash mid-cleanup (PRRT_kwDONV6tZs6HsFwN). - Use the detached background ctx for the cleanup rather than re-wrapping coordCtx in context.WithoutCancel (PRRT_kwDONV6tZs6Hr25g). - The takeover now calls resetStagingForTakeover (discard truncated parts + reset staging_state to "requested") instead of reclaimStaging, so the fresh download re-stages from zero and a persisting cross-pod waiter is re-served rather than stranded (completes the #1351 reset-not-delete fix). Co-Authored-By: Claude Opus 4.8 <[email protected]>
dbf22de to
3c211b3
Compare
|
Documentation Updates 1 document(s) were updated by changes in this PR: NAR File Download and StreamingView Changes@@ -101,7 +101,9 @@
**Request signaling**: The waiter calls `markStagingRequested` to signal the holder that cross-pod staging is needed. This is an idempotent one-shot marker the holder reads on its own loop, adding no churn to the system.
-**Part availability detection**: On each 200ms poll tick, the waiter checks `stagingServeReady` to determine if parts are available. Once `parts_available > 0`, the function returns a staging directive (`downloadState.stagingServe`) instead of continuing to wait for the whole download.
+**Takeover-before-serve ordering**: On each 200ms poll tick, the waiter FIRST attempts to re-acquire the lock (`TryLock`) to detect if the holder has died or failed. If the lock can be acquired (the holder is gone), the waiter takes over as the new download holder. The new holder will discard any partial staging parts left by the dead holder (via `resetStagingForTakeover`) and restart the download from scratch. This prevents serving truncated/incomplete staging parts from a holder that will never complete.
+
+**Part availability detection**: Only if the lock is still held (holder is alive) does the waiter then check `stagingServeReady` to determine if parts are available. Once `parts_available > 0`, the function returns a staging directive (`downloadState.stagingServe`) instead of continuing to wait for the whole download. This ensures staging parts are only served when the producer is still alive and will complete the download.
**Streaming from staging parts**: When `GetNar` receives a staging directive, it calls `serveNarFromStaging` to stream the NAR from staging part-objects rather than storage. The implementation creates a `stagingPartReader` that tails part-objects in order, polling `staging_state.parts_available` every 200ms and blocking until each part is durably available.
@@ -110,6 +112,8 @@
**Transcoding support**: The reader transcodes if needed—for example, decompressing staged bytes when the client requests uncompressed data—at parity with the same-pod streaming path. The returned `narURL.Compression` advertises the compression actually served.
**Clean EOF semantics**: The reader emits a clean `io.EOF` only when `status = complete` and all parts have been consumed. If the producer stalls (stops advancing `parts_available` without setting the complete marker), the reader surfaces `errStagingStall` after the per-part wait timeout. If the `staging_state` row disappears mid-stream (reset by a takeover), the reader surfaces `errStagingReset`. Context cancellation is propagated immediately. This ensures a truncated NAR is never delivered as a clean EOF.
+
+**Takeover cleanup**: The `resetStagingForTakeover` function cleans up the dead holder's partial staging parts and resets the staging state to "requested", allowing the new holder to re-stage from zero if contention persists. This function preserves the `staging_state` row (unlike `reclaimStaging` which deletes it) to maintain the waiter's request marker, ensuring the waiter is re-served once the new holder completes staging.
**Per-part timeout**: The per-part wait bound reuses `chunkWaitTimeout` from progressive chunk streaming for configuration parity. A steadily-advancing producer is never penalized; only a stalled one triggers the timeout.
|
Holder-death takeover for in-flight staging (D5, group 9). In
pollForDownloadOrTakeOver the lock re-acquisition (takeover) is now attempted
BEFORE serving from staging: an acquirable lock means the holder is gone
(died or failed), so its staging parts are at best a truncated prefix. On
takeover the new owner discards the dead holder's partial part-objects and
resets staging_state, then restarts the download from zero via the existing
post-lock path and re-stages cleanly if contention persists.
Reordering takeover ahead of the staging-serve branch also guarantees the
correctness contract across a death+takeover transition: a reader tailing a
never-completed staging set surfaces a stream error (the part-tailing reader's
stall handling), never a clean EOF at a truncated length, and the orphaned
parts are reclaimed by the takeover rather than tailed as if complete.