Skip to content

feat(cache): reclaim in-flight staging artifacts - #1356

Merged
kalbasit merged 2 commits into
mainfrom
feat-cache-reclaim-in-flight
Jun 8, 2026
Merged

kalbasit merged 2 commits into
mainfrom
feat-cache-reclaim-in-flight

Conversation

@kalbasit

@kalbasit kalbasit commented Jun 7, 2026

Copy link
Copy Markdown
Owner

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

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jun 7, 2026
@coderabbitai

coderabbitai Bot commented Jun 7, 2026 •

Copy link
Copy Markdown

Review Change Stack

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 600780e8-8573-4663-a598-c65aed807b52

📥 Commits

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

📒 Files selected for processing (5)
  • pkg/cache/cache.go
  • pkg/cache/inflight_staging.go
  • pkg/cache/inflight_staging_gc.go
  • pkg/cache/inflight_staging_gc_internal_test.go
  • pkg/ncps/serve.go

📝 Walkthrough

Summary by CodeRabbit

  • New Features
    • Added automatic garbage collection for in-flight staging artifacts, reclaiming storage after retention periods
    • Improved detection and cleanup of orphaned staging artifacts
    • Enhanced shutdown mechanism to ensure proper completion of background cleanup operations

Walkthrough

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

Changes

In-flight Staging Garbage Collection

Layer / File(s) Summary
Shutdown signal infrastructure
pkg/cache/cache.go
Cache gains shutdownCh and shutdownOnce, initialized in New() and closed once in Close() so background GC timers can be interrupted.
In-flight staging GC core
pkg/cache/inflight_staging_gc.go
reclaimStaging deletes staging parts and the staging_state record; scheduleStagingReclaim waits the retention-grace (shutdown-interruptible) then calls reclaim; sweepStagingGC enumerates staging_state rows, computes staleness from updated_at/created_at, and reclaims due records; stagingOrphanAge computes orphan threshold.
Cron registration and integration
pkg/cache/inflight_staging_gc.go, pkg/cache/inflight_staging.go, pkg/ncps/serve.go
AddInflightStagingGCCronJob registers the periodic sweep; runStagingGC skips when disabled and uses a shutdown-bound context; stageInflightNar schedules reclaim after producing parts; cache creation conditionally registers the GC cron job when inflight staging is enabled and lock backend is Redis.
GC test coverage
pkg/cache/inflight_staging_gc_internal_test.go
Three tests: reclaim deletes parts+record, scheduled reclaim runs after grace, and sweep reclaims orphans/stale completes while preserving fresh records. Includes helpers to force updated_at and assert record/part presence or absence.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • kalbasit/ncps#1352: Related to staging-part storage APIs used by GC to delete per-hash parts.
  • kalbasit/ncps#1353: Modifies in-flight staging flow and staging_state writes/read patterns that GC relies on.
  • kalbasit/ncps#1354: Adds cross-pod reader/serving behavior that interacts with staging_state and part availability GC must respect.

Poem

🐰 I waited by the staging gate,

Timers set to sweep and sate,
Shutdown bell rings once, not twice,
I tidy parts and roll the dice,
Clean fields of artifacts and fate.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'feat(cache): reclaim in-flight staging artifacts' directly and clearly summarizes the main change: implementing garbage collection and retention for in-flight NAR staging artifacts.
Description check ✅ Passed The description provides detailed context on the two reclaim paths (event-driven and periodic sweep) and explains the design decisions, directly relating to the changesets across all modified files.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

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

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

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request 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.

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (2)
pkg/cache/inflight_staging_gc_internal_test.go (2)

128-131: ⚡ Quick win

Consider verifying parts are preserved for non-reclaimed cases.

The test verifies that staging state records are preserved for completeNew and orphanFresh via assertStagingPresent, 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 via assertStagingAbsent. While reclaimStaging deletes 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 assertStagingPresent to 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 value

Consider renaming orphanFresh for clarity.

The variable name orphanFresh is 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 like inProgressFresh or activeStaging to 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

📥 Commits

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

📒 Files selected for processing (5)
  • pkg/cache/cache.go
  • pkg/cache/inflight_staging.go
  • pkg/cache/inflight_staging_gc.go
  • pkg/cache/inflight_staging_gc_internal_test.go
  • pkg/ncps/serve.go

Comment thread pkg/cache/inflight_staging_gc.go Resolved
Comment thread pkg/cache/inflight_staging_gc.go Resolved
@kalbasit
kalbasit force-pushed the feat-cache-prefer-staging-over branch from 4428ac9 to e313438 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 0528185 to 2fd9bb8 Compare June 8, 2026 00:11
@kalbasit
kalbasit force-pushed the feat-cache-prefer-staging-over branch from e313438 to f51b255 Compare June 8, 2026 00:19
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 2fd9bb8 to 666e716 Compare June 8, 2026 00:19
@kalbasit
kalbasit force-pushed the feat-cache-prefer-staging-over branch from f51b255 to 2761b54 Compare June 8, 2026 00:27
@kalbasit
kalbasit force-pushed the feat-cache-reclaim-in-flight branch from 666e716 to 36084d7 Compare June 8, 2026 00:27
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-prefer-staging-over branch from 2761b54 to b09e53e 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 36084d7 to a9e99a9 Compare June 8, 2026 00:42
@kalbasit
kalbasit force-pushed the feat-cache-prefer-staging-over branch from b09e53e to 1d3c1d2 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 a9e99a9 to 72d5a4c Compare June 8, 2026 00:49
@kalbasit
kalbasit force-pushed the feat-cache-prefer-staging-over branch from 1d3c1d2 to 1fb88f8 Compare June 8, 2026 00:56
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
Base automatically changed from feat-cache-prefer-staging-over to main June 8, 2026 01:04
kalbasit and others added 2 commits June 8, 2026 01:04
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]>
@kalbasit
kalbasit force-pushed the feat-cache-reclaim-in-flight branch from e762d04 to 86adc4d Compare June 8, 2026 01:04
@kalbasit
kalbasit enabled auto-merge (squash) June 8, 2026 01:04

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

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

45-132: ⚡ Quick win

Add coverage for shutdown-interrupted scheduled reclaim.

Current tests cover grace-expiry reclaim and sweep behavior, but not the shutdown-short-circuit path (scheduleStagingReclaim exiting 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 /tdd rule."

🤖 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

📥 Commits

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

📒 Files selected for processing (5)
  • pkg/cache/cache.go
  • pkg/cache/inflight_staging.go
  • pkg/cache/inflight_staging_gc.go
  • pkg/cache/inflight_staging_gc_internal_test.go
  • pkg/ncps/serve.go

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

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 win

Add coverage for shutdown-interrupted scheduled reclaim.

Current tests cover grace-expiry reclaim and sweep behavior, but not the shutdown-short-circuit path (scheduleStagingReclaim exiting 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 /tdd rule."

🤖 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

📥 Commits

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

📒 Files selected for processing (5)
  • pkg/cache/cache.go
  • pkg/cache/inflight_staging.go
  • pkg/cache/inflight_staging_gc.go
  • pkg/cache/inflight_staging_gc_internal_test.go
  • pkg/ncps/serve.go
🛑 Comments failed to post (2)
pkg/cache/inflight_staging_gc.go (1)

71-72: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Update the shutdown-safety comment to match the actual reclaim path.

This comment references resetStagingState, but the reclaim path here deletes state via deleteStagingState.

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 win

Align 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, the staging_state row 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

@kalbasit
kalbasit merged commit 87a07ba into main Jun 8, 2026
37 checks passed
@kalbasit
kalbasit deleted the feat-cache-reclaim-in-flight branch June 8, 2026 01:11
@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
@@ -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
 

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:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants