Repository navigation
feat(cache): reclaim in-flight staging artifacts - #1356
Conversation
|
This change is part of the following stack:
Change managed by git-spice. |
ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (5)
📝 WalkthroughSummary by CodeRabbit
WalkthroughAdds shutdown-bound signaling to Cache and implements in-flight staging GC: reclaimStaging, scheduleStagingReclaim (timer, shutdown-aware), sweepStagingGC (periodic backstop), cron wiring, integration in staging flow, and tests covering reclaim and sweep behaviors. ChangesIn-flight Staging Garbage Collection
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 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 introduces a garbage collection mechanism for in-flight staging artifacts. It adds a shutdown channel (shutdownCh) to the Cache struct to interrupt background retention sleeps during shutdown, and implements both an event-driven reclaim path and a periodic cron job sweep to clean up completed or orphaned staging records. Unit tests are also added to verify these behaviors. The review feedback points out that if shutdownCh is nil (e.g., in some test contexts), selecting on it will block indefinitely, and suggests guarding the select statement to handle a nil channel safely.
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.
|
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (2)
pkg/cache/inflight_staging_gc_internal_test.go (2)
128-131: ⚡ Quick winConsider verifying parts are preserved for non-reclaimed cases.
The test verifies that staging state records are preserved for
completeNewandorphanFreshviaassertStagingPresent, but it doesn't verify that the part-objects themselves still exist. This creates an asymmetry with the reclaim checks (lines 128-129) which verify both state and parts viaassertStagingAbsent. WhilereclaimStagingdeletes both atomically, explicitly verifying parts exist would make the test more thorough and catch potential bugs where parts are deleted but state is preserved.🧪 Suggested enhancement to verify parts are preserved
Option 1: Enhance
assertStagingPresentto also check parts exist:func assertStagingPresent(t *testing.T, c *Cache, store storage.NarStore, hash string) { t.Helper() st, err := c.getStagingState(context.Background(), hash) require.NoError(t, err) require.NotNil(t, st, "staging_state for %q must be preserved", hash) _, err = store.GetStagingPart(context.Background(), hash, 0) require.NoError(t, err, "part-objects for %q must be preserved", hash) }Option 2: Add explicit part checks in the test after the existing assertions:
assertStagingPresent(t, c, completeNew) assertStagingPresent(t, c, orphanFresh) // Verify parts are preserved _, err = store.GetStagingPart(ctx, completeNew, 0) require.NoError(t, err, "parts for completeNew must be preserved") _, err = store.GetStagingPart(ctx, orphanFresh, 0) require.NoError(t, err, "parts for orphanFresh must be preserved")🤖 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_gc_internal_test.go` around lines 128 - 131, The test currently uses assertStagingPresent(t, c, completeNew) and assertStagingPresent(t, c, orphanFresh) to verify staging state only, but does not ensure the underlying part-objects still exist; update the test so non-reclaimed cases also verify parts are preserved by either enhancing assertStagingPresent to call store.GetStagingPart(ctx, hash, 0) (and/or verifying c.getStagingState still returns non-nil) or by adding explicit calls to storage.NarStore.GetStagingPart for completeNew and orphanFresh and asserting no error, mirroring how assertStagingAbsent covers both state and parts after reclaimStaging.
95-95: 💤 Low valueConsider renaming
orphanFreshfor clarity.The variable name
orphanFreshis confusing because "orphan" typically implies the holder died, but the comment on line 119 clarifies this represents "a live holder mid-staging". Consider renaming to something likeinProgressFreshoractiveStagingto better convey that this is not actually an orphaned record.📝 Suggested naming improvement
const ( orphan = "33333333333333333333333333330000" // non-complete, stale -> reclaim completeOld = "44444444444444444444444444441111" // complete, stale > retention -> reclaim completeNew = "55555555555555555555555555552222" // complete, fresh -> keep - orphanFresh = "66666666666666666666666666663333" // non-complete, fresh -> keep + inProgressFresh = "66666666666666666666666666663333" // non-complete, fresh -> keep retentionArg = time.Hour orphanArg = time.Minute )And update the references on lines 120-122 and 131.
🤖 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_gc_internal_test.go` at line 95, Rename the test variable orphanFresh to a clearer name (e.g., inProgressFresh or activeStaging) to reflect that it represents a live holder mid-staging; update the variable declaration (orphanFresh) and all references to it in the test (the occurrences noted near the comment usages) and adjust the inline comment to say "non-complete, in-progress/staging -> keep" so the variable name and comment are 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/inflight_staging_gc.go`:
- Around line 52-56: The reclaimStaging call is using context.Background() which
ignores shutdown; change the call site to pass the cache's lifecycle/shutdown
context (the same context used to drive Close()/backgroundWG) into
reclaimStaging instead of context.Background(), and update reclaimStaging to
return/handle context.Canceled as a normal/expected exit (log at Debug/Info
rather than Warn) so that if DeleteStagingParts or resetStagingState blocks
during shutdown Close() can complete. Ensure callers and reclaimStaging
signatures use the shutdown-bound context and preserve existing error handling
for non-cancellation errors.
- Around line 129-145: The cron job currently closes over the caller's ctx in
AddInflightStagingGCCronJob -> runStagingGC, so if that ctx is
startup/request-scoped later sweeps run with context.Canceled; instead capture
the logger from zerolog.Ctx(ctx) at registration but do NOT capture the caller
ctx—change runStagingGC to accept the logger (or have
AddInflightStagingGCCronJob register a job that creates a fresh context inside
the closure using context.Background()/a cache-lifecycle context) and inside the
returned func create a new ctx (e.g., context.Background() or c lifecycle ctx)
and pass that fresh ctx to sweepStagingGC and other Ent calls; update calls to
runStagingGC and sweepStagingGC accordingly (refer to
AddInflightStagingGCCronJob, runStagingGC, sweepStagingGC).
---
Nitpick comments:
In `@pkg/cache/inflight_staging_gc_internal_test.go`:
- Around line 128-131: The test currently uses assertStagingPresent(t, c,
completeNew) and assertStagingPresent(t, c, orphanFresh) to verify staging state
only, but does not ensure the underlying part-objects still exist; update the
test so non-reclaimed cases also verify parts are preserved by either enhancing
assertStagingPresent to call store.GetStagingPart(ctx, hash, 0) (and/or
verifying c.getStagingState still returns non-nil) or by adding explicit calls
to storage.NarStore.GetStagingPart for completeNew and orphanFresh and asserting
no error, mirroring how assertStagingAbsent covers both state and parts after
reclaimStaging.
- Line 95: Rename the test variable orphanFresh to a clearer name (e.g.,
inProgressFresh or activeStaging) to reflect that it represents a live holder
mid-staging; update the variable declaration (orphanFresh) and all references to
it in the test (the occurrences noted near the comment usages) and adjust the
inline comment to say "non-complete, in-progress/staging -> keep" so the
variable name and comment are 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: 8a1b8d15-a1fe-4bca-9f99-665b29a3692d
📒 Files selected for processing (5)
pkg/cache/cache.gopkg/cache/inflight_staging.gopkg/cache/inflight_staging_gc.gopkg/cache/inflight_staging_gc_internal_test.gopkg/ncps/serve.go
4428ac9 to
e313438
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]>
0528185 to
2fd9bb8
Compare
e313438 to
f51b255
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]>
2fd9bb8 to
666e716
Compare
f51b255 to
2761b54
Compare
666e716 to
36084d7
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]>
2761b54 to
b09e53e
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
b09e53e to
1d3c1d2
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
1d3c1d2 to
1fb88f8
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
GC / retention for in-flight NAR staging (group 8). Two reclaim paths: - Event-driven: once the holder finishes staging (the final representation is now committed), scheduleStagingReclaim deletes the staging part-objects and staging_state record after the configurable retention grace, letting cross-pod readers drain first. The grace wait is interrupted by a new Cache shutdown channel so Close() is never blocked for the full grace; anything skipped on shutdown is caught by the sweep. - Periodic sweep: a cron job (registered when staging is enabled with a distributed locker) reclaims completed staging past its retention grace and orphaned staging whose holder died. Liveness is detected by updated_at staleness exceeding a generous orphan age (a live holder advances parts_available, and thus updated_at, while staging) rather than treating created_at age as a death proxy — the #1230 lesson; created_at is the fallback only when a bare request marker was never updated.
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]>
e762d04 to
86adc4d
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
pkg/cache/inflight_staging_gc_internal_test.go (1)
45-132: ⚡ Quick winAdd coverage for shutdown-interrupted scheduled reclaim.
Current tests cover grace-expiry reclaim and sweep behavior, but not the shutdown-short-circuit path (
scheduleStagingReclaimexiting early on cache shutdown). Adding that test would protect the key shutdown-safety guarantee introduced in this PR.As per coding guidelines: "
pkg/**/*.go: All production changes must use TDD (test-driven development). See/tddrule."🤖 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_gc_internal_test.go` around lines 45 - 132, Add a test that verifies scheduleStagingReclaim short-circuits when the cache is shut down: create a cache with inflight staging enabled via SetInflightStaging (use small grace), put staging parts, call markStagingRequested/advanceStagingParts/markStagingComplete for a hash, call c.scheduleStagingReclaim(hash) and immediately trigger cache shutdown (call the cache shutdown method, e.g. Shutdown or Close on the cache instance), then assert that the staging state and parts remain present (i.e., not reclaimed) and that scheduleStagingReclaim returned/exited due to shutdown; reference scheduleStagingReclaim, SetInflightStaging, markStagingComplete, markStagingRequested, advanceStagingParts, and the cache shutdown method to locate the code to test.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/inflight_staging_gc.go`:
- Around line 71-72: Update the shutdown-safety comment so it accurately
describes the reclaim path: replace the incorrect reference to resetStagingState
with the actual delete path deleteStagingState (and/or DeleteStagingParts where
relevant) and ensure the sentence explains that deleteStagingState (not
resetStagingState) is used to reclaim state so Close() won't be blocked on
backgroundWG; adjust wording around Close() and backgroundWG to reflect the real
behavior.
In `@pkg/cache/inflight_staging.go`:
- Around line 29-31: The comment above inflight_staging.go incorrectly mentions
an "abandoned" terminal status that doesn't exist; update the documentation
comment referencing staging_state.status (used by functions in this file) to
list only the actual statuses "requested", "staging", and "complete" so it
matches the code and ent/schema/staging_state.go and avoid misleading readers.
---
Nitpick comments:
In `@pkg/cache/inflight_staging_gc_internal_test.go`:
- Around line 45-132: Add a test that verifies scheduleStagingReclaim
short-circuits when the cache is shut down: create a cache with inflight staging
enabled via SetInflightStaging (use small grace), put staging parts, call
markStagingRequested/advanceStagingParts/markStagingComplete for a hash, call
c.scheduleStagingReclaim(hash) and immediately trigger cache shutdown (call the
cache shutdown method, e.g. Shutdown or Close on the cache instance), then
assert that the staging state and parts remain present (i.e., not reclaimed) and
that scheduleStagingReclaim returned/exited due to shutdown; reference
scheduleStagingReclaim, SetInflightStaging, markStagingComplete,
markStagingRequested, advanceStagingParts, and the cache shutdown method to
locate the code to test.
🪄 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: 600780e8-8573-4663-a598-c65aed807b52
📒 Files selected for processing (5)
pkg/cache/cache.gopkg/cache/inflight_staging.gopkg/cache/inflight_staging_gc.gopkg/cache/inflight_staging_gc_internal_test.gopkg/ncps/serve.go
There was a problem hiding this comment.
Caution
Inline review comments failed to post. This is likely due to GitHub's internal server error or limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.
Actionable comments posted: 2
🧹 Nitpick comments (1)
pkg/cache/inflight_staging_gc_internal_test.go (1)
45-132: ⚡ Quick winAdd coverage for shutdown-interrupted scheduled reclaim.
Current tests cover grace-expiry reclaim and sweep behavior, but not the shutdown-short-circuit path (
scheduleStagingReclaimexiting early on cache shutdown). Adding that test would protect the key shutdown-safety guarantee introduced in this PR.As per coding guidelines: "
pkg/**/*.go: All production changes must use TDD (test-driven development). See/tddrule."🤖 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_gc_internal_test.go` around lines 45 - 132, Add a test that verifies scheduleStagingReclaim short-circuits when the cache is shut down: create a cache with inflight staging enabled via SetInflightStaging (use small grace), put staging parts, call markStagingRequested/advanceStagingParts/markStagingComplete for a hash, call c.scheduleStagingReclaim(hash) and immediately trigger cache shutdown (call the cache shutdown method, e.g. Shutdown or Close on the cache instance), then assert that the staging state and parts remain present (i.e., not reclaimed) and that scheduleStagingReclaim returned/exited due to shutdown; reference scheduleStagingReclaim, SetInflightStaging, markStagingComplete, markStagingRequested, advanceStagingParts, and the cache shutdown method to locate the code to test.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/inflight_staging_gc.go`:
- Around line 71-72: Update the shutdown-safety comment so it accurately
describes the reclaim path: replace the incorrect reference to resetStagingState
with the actual delete path deleteStagingState (and/or DeleteStagingParts where
relevant) and ensure the sentence explains that deleteStagingState (not
resetStagingState) is used to reclaim state so Close() won't be blocked on
backgroundWG; adjust wording around Close() and backgroundWG to reflect the real
behavior.
In `@pkg/cache/inflight_staging.go`:
- Around line 29-31: The comment above inflight_staging.go incorrectly mentions
an "abandoned" terminal status that doesn't exist; update the documentation
comment referencing staging_state.status (used by functions in this file) to
list only the actual statuses "requested", "staging", and "complete" so it
matches the code and ent/schema/staging_state.go and avoid misleading readers.
---
Nitpick comments:
In `@pkg/cache/inflight_staging_gc_internal_test.go`:
- Around line 45-132: Add a test that verifies scheduleStagingReclaim
short-circuits when the cache is shut down: create a cache with inflight staging
enabled via SetInflightStaging (use small grace), put staging parts, call
markStagingRequested/advanceStagingParts/markStagingComplete for a hash, call
c.scheduleStagingReclaim(hash) and immediately trigger cache shutdown (call the
cache shutdown method, e.g. Shutdown or Close on the cache instance), then
assert that the staging state and parts remain present (i.e., not reclaimed) and
that scheduleStagingReclaim returned/exited due to shutdown; reference
scheduleStagingReclaim, SetInflightStaging, markStagingComplete,
markStagingRequested, advanceStagingParts, and the cache shutdown method to
locate the code to test.
🪄 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: 600780e8-8573-4663-a598-c65aed807b52
📒 Files selected for processing (5)
pkg/cache/cache.gopkg/cache/inflight_staging.gopkg/cache/inflight_staging_gc.gopkg/cache/inflight_staging_gc_internal_test.gopkg/ncps/serve.go
🛑 Comments failed to post (2)
pkg/cache/inflight_staging_gc.go (1)
71-72:
⚠️ Potential issue | 🟡 Minor | ⚡ Quick winUpdate the shutdown-safety comment to match the actual reclaim path.
This comment references
resetStagingState, but the reclaim path here deletes state viadeleteStagingState.Suggested diff
- // itself, so a stalled DeleteStagingParts/resetStagingState cannot keep + // itself, so a stalled DeleteStagingParts/deleteStagingState cannot keep📝 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.// itself, so a stalled DeleteStagingParts/deleteStagingState cannot keep // Close() blocked on backgroundWG.🤖 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_gc.go` around lines 71 - 72, Update the shutdown-safety comment so it accurately describes the reclaim path: replace the incorrect reference to resetStagingState with the actual delete path deleteStagingState (and/or DeleteStagingParts where relevant) and ensure the sentence explains that deleteStagingState (not resetStagingState) is used to reclaim state so Close() won't be blocked on backgroundWG; adjust wording around Close() and backgroundWG to reflect the real behavior.pkg/cache/inflight_staging.go (1)
29-31:
⚠️ Potential issue | 🟡 Minor | ⚡ Quick winAlign status documentation with the actual state set.
The comment says
"abandoned"is a terminal status, but this file only uses"requested","staging", and"complete".Suggested diff
-// staging_state.status values. See ent/schema/staging_state.go. The "complete" -// and "abandoned" terminal statuses are introduced alongside the staging -// completion / GC logic that consumes them. +// staging_state.status values. See ent/schema/staging_state.go.Based on learnings: In
pkg/cache/inflight_staging.go, thestaging_staterow has exactly three status values:"requested","staging", and"complete"; there is no"abandoned"status in this codebase.📝 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.// staging_state.status values. See ent/schema/staging_state.go.🤖 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.go` around lines 29 - 31, The comment above inflight_staging.go incorrectly mentions an "abandoned" terminal status that doesn't exist; update the documentation comment referencing staging_state.status (used by functions in this file) to list only the actual statuses "requested", "staging", and "complete" so it matches the code and ent/schema/staging_state.go and avoid misleading readers.Source: Learnings
|
Documentation Updates 1 document(s) were updated by changes in this PR: NAR File Download and StreamingView Changes@@ -116,6 +116,20 @@
**Metrics**: A successful staging serve increments the `ncps_download_coordination_fallback_total` metric with outcome `served_from_staging`.
**Scope**: Staging applies only to NAR downloads, not narinfo. The `allowStaging` parameter in `coordinateDownload` is set to `true` for NAR jobs and `false` for narinfo jobs.
+
+#### In-Flight Staging Lifecycle and Cleanup
+
+Once the holder completes staging (the final NAR representation is committed), the staging artifacts must be reclaimed to prevent unbounded accumulation. The system implements two complementary cleanup paths that handle both successful completions and holder failures:
+
+**Event-driven reclaim (`scheduleStagingReclaim`)**: After the holder finishes staging successfully, `scheduleStagingReclaim` schedules cleanup of the staging part-objects and `staging_state` record after a configurable retention grace period (set via `--cache-inflight-staging-retention` flag). This grace period allows any in-flight cross-pod readers to drain before the staging artifacts are deleted—cross-pod readers that joined during staging need time to complete their reads before the parts disappear. The grace wait is interrupted by Cache shutdown (via `shutdownCh`), so `Close()` never blocks for the full grace duration. Anything skipped on shutdown is caught by the periodic sweep. The event-driven path is the primary cleanup mechanism for the happy path: when a holder completes staging without crashing, this reclaim runs exactly once per NAR after the retention grace.
+
+**Periodic sweep (`sweepStagingGC`)**: A cron job runs every minute (when staging is enabled with a distributed locker) to reclaim staging records that the event-driven path missed. The sweep handles two cases:
+
+- **Completed staging past retention grace**: A defensive backstop for the event-driven reclaim. If `scheduleStagingReclaim` was skipped (e.g., the holder crashed after marking staging complete but before scheduling reclaim, or the reclaim was interrupted by shutdown), the sweep detects completed staging whose `updated_at` staleness exceeds the retention grace and reclaims it.
+
+- **Orphaned staging**: Detects staging whose holder died and was never taken over. A live holder advances `parts_available`—and thus `updated_at`—as it stages, so `updated_at` staleness is the liveness signal rather than `created_at` age (following the #1230 lesson on age-as-death proxies). When `updated_at` staleness exceeds the orphan age threshold, the staging is presumed abandoned and reclaimed. The orphan age is calculated as `max(downloadLockTTL, downloadPollTimeout) + InflightStagingRetention`, which is generous enough to exceed the whole window during which a live holder could still be refreshing its download lock and advancing parts, plus the retention grace.
+
+Both reclaim operations use a shutdown-bound context that is cancelled when `Cache.Close()` runs, so background cleanup cannot outlive shutdown and block `Close()` indefinitely. The `reclaimStaging` function is idempotent: deleting absent parts or `staging_state` records is a no-op, so redundant reclaim (e.g., event-driven plus sweep) is safe.
#### Single-Decompression Mechanism for CDC
|
GC / retention for in-flight NAR staging (group 8). Two reclaim paths:
now committed), scheduleStagingReclaim deletes the staging part-objects and
staging_state record after the configurable retention grace, letting cross-pod
readers drain first. The grace wait is interrupted by a new Cache shutdown
channel so Close() is never blocked for the full grace; anything skipped on
shutdown is caught by the sweep.
distributed locker) reclaims completed staging past its retention grace and
orphaned staging whose holder died. Liveness is detected by updated_at
staleness exceeding a generous orphan age (a live holder advances
parts_available, and thus updated_at, while staging) rather than treating
created_at age as a death proxy — the CDC: async chunking can leave orphan state if server is killed mid-chunking #1230 lesson; created_at is the fallback
only when a bare request marker was never updated.