Skip to content

feat(cache): restart staging on holder death - #1357

Merged
kalbasit merged 2 commits into
mainfrom
feat-cache-restart-staging-on
Jun 8, 2026
Merged

kalbasit merged 2 commits into
mainfrom
feat-cache-restart-staging-on

Conversation

@kalbasit

@kalbasit kalbasit commented Jun 7, 2026

Copy link
Copy Markdown
Owner

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.

@dosubot dosubot Bot added the size:M This PR changes 30-99 lines, ignoring generated files. label Jun 7, 2026
@coderabbitai

coderabbitai Bot commented Jun 7, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@kalbasit, we couldn't start this review because you've reached your PR review rate limit.

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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 0a4115e7-f6ed-4d23-81b8-c98262172f44

📥 Commits

Reviewing files that changed from the base of the PR and between b7e105b and 3c211b3.

📒 Files selected for processing (3)
  • pkg/cache/cache.go
  • pkg/cache/inflight_staging_gc.go
  • pkg/cache/inflight_staging_takeover_internal_test.go
📝 Walkthrough

Walkthrough

The PR reorders lock takeover coordination in pollForDownloadOrTakeOver: when a stale lock holder is detected, the function now attempts immediate lock re-acquisition (takeover) before checking in-flight staging. Successful takeover clears stale partial staging via reclaimStaging; failed takeover falls back to serving from available staging parts. Two new tests validate that stale staging is discarded on takeover and that truncated parts trigger stream errors.

Changes

Cross-replica download takeover with staging cleanup

Layer / File(s) Summary
Lock takeover and staging reclamation
pkg/cache/cache.go
pollForDownloadOrTakeOver now first attempts non-blocking TryLock on a stale lock holder; on success, records take_over metric and invokes reclaimStaging to discard partial staging before the new download. On failure, checks and serves from available in-flight staging parts with the served_from_staging outcome.
Takeover behavior and staging cleanup tests
pkg/cache/inflight_staging_takeover_internal_test.go
TestPollTakeover_DiscardsStaleStaging verifies takeover clears staging_state and removes partial parts. TestStagingTakeover_NoTruncatedServeAcrossDeath ensures a truncated staging reader returns a stream error and that takeover removes the corrupted parts.

Sequence Diagram

sequenceDiagram
  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
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • kalbasit/ncps#1290: Modifies the same pollForDownloadOrTakeOver and takeover code path with related lock-reacquisition logic.

Suggested labels

merge-stack

Poem

🐰 A stale lock-holder falls away,
Our replica takes charge today,
We reclaim the staging dust they left,
Then serve fresh parts, precise and deft!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: reordering lock takeover before staging serve to handle holder death scenarios.
Description check ✅ Passed The description is directly related to the changeset, explaining the rationale and behavior of the holder-death takeover mechanism for in-flight staging.
Docstring Coverage ✅ Passed Docstring coverage is 100.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.


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

Comment thread pkg/cache/cache.go Resolved
@kalbasit

kalbasit commented Jun 7, 2026

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jun 7, 2026 •

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@kalbasit

kalbasit commented Jun 7, 2026

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jun 7, 2026 •

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@kalbasit

kalbasit commented Jun 7, 2026

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jun 7, 2026 •

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@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

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 | 🔴 Critical

Run/attach fmt+lint+unit-test verification before merge

Taskfile.yml expects:

  • fmt: nix fmt
  • lint: golangci-lint run
  • test: go test -race ./...

In this environment task/nix aren’t available, but:

  • gofmt checks passed.
  • golangci-lint run ./... fails with typecheck errors in pkg/database/errors.go (undefined: sqlite3.Error, sqlite3.ErrBusy, sqlite3.ErrLocked, sqlite3.ErrProtocol, sqlite3.ErrConstraint).
  • go test -race ./... can’t run here unless CGO_ENABLED=1 (race requires cgo).

Rerun task fmt, task lint, and task test in 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

📥 Commits

Reviewing files that changed from the base of the PR and between 0528185 and b7e105b.

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

Comment thread pkg/cache/cache.go Resolved
kalbasit added a commit that referenced this pull request Jun 8, 2026
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]>
@kalbasit
kalbasit force-pushed the feat-cache-reclaim-in-flight branch from 0528185 to 2fd9bb8 Compare June 8, 2026 00:11
kalbasit added a commit that referenced this pull request Jun 8, 2026
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]>
@kalbasit
kalbasit force-pushed the feat-cache-restart-staging-on branch from b7e105b to d640de5 Compare June 8, 2026 00:11
kalbasit added a commit that referenced this pull request Jun 8, 2026
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]>
@kalbasit
kalbasit force-pushed the feat-cache-reclaim-in-flight branch from 36084d7 to a9e99a9 Compare June 8, 2026 00:42
kalbasit added a commit that referenced this pull request Jun 8, 2026
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]>
@kalbasit
kalbasit force-pushed the feat-cache-restart-staging-on branch from c546455 to 66282cc Compare June 8, 2026 00:42
kalbasit added a commit that referenced this pull request Jun 8, 2026
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]>
@kalbasit
kalbasit force-pushed the feat-cache-reclaim-in-flight branch from a9e99a9 to 72d5a4c Compare June 8, 2026 00:49
kalbasit added a commit that referenced this pull request Jun 8, 2026
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]>
@kalbasit
kalbasit force-pushed the feat-cache-restart-staging-on branch from 66282cc to 2c630bd Compare June 8, 2026 00:49
kalbasit added a commit that referenced this pull request Jun 8, 2026
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]>
@kalbasit
kalbasit force-pushed the feat-cache-reclaim-in-flight branch from 72d5a4c to e762d04 Compare June 8, 2026 00:56
kalbasit added a commit that referenced this pull request Jun 8, 2026
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]>
@kalbasit
kalbasit force-pushed the feat-cache-restart-staging-on branch from 2c630bd to 74d511a Compare June 8, 2026 00:56
@kalbasit
kalbasit force-pushed the feat-cache-reclaim-in-flight branch from e762d04 to 86adc4d Compare June 8, 2026 01:04
kalbasit added a commit that referenced this pull request Jun 8, 2026
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]>
kalbasit added a commit that referenced this pull request Jun 8, 2026
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]>
@kalbasit
kalbasit force-pushed the feat-cache-restart-staging-on branch from 74d511a to dbf22de Compare June 8, 2026 01:04
Base automatically changed from feat-cache-reclaim-in-flight to main June 8, 2026 01:11
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:M This PR changes 30-99 lines, ignoring generated files. labels Jun 8, 2026
kalbasit and others added 2 commits June 8, 2026 01:11
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]>
@kalbasit
kalbasit force-pushed the feat-cache-restart-staging-on branch from dbf22de to 3c211b3 Compare June 8, 2026 01:11
@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Jun 8, 2026
@kalbasit
kalbasit enabled auto-merge (squash) June 8, 2026 01:11
@kalbasit
kalbasit merged commit 5cc82a3 into main Jun 8, 2026
38 of 39 checks passed
@kalbasit
kalbasit deleted the feat-cache-restart-staging-on branch June 8, 2026 01:18
@dosubot

dosubot Bot commented Jun 8, 2026

Copy link
Copy Markdown

Documentation Updates

1 document(s) were updated by changes in this PR:

NAR File Download and Streaming
View 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.
 

How did I do? Any feedback?  Join Discord

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request go Pull requests that update go code merge-stack size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants