Repository navigation
feat(cache): stage in-flight NAR on contention - #1353
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 (4)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughSummary by CodeRabbit
WalkthroughAdds a background in-flight staging producer: during downloads (when enabled) it polls for staging requests, tails the temp file, uploads fixed-size staging parts to shared storage, updates staging_state, and marks completion for readers. ChangesIn-flight NAR Staging Producer
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
Comment |
There was a problem hiding this comment.
Code Review
This pull request introduces in-flight staging for NAR downloads, allowing a download holder to stage bytes to shared storage as fixed-size part-objects when a cross-pod waiter is detected. This enables other replicas to serve the NAR concurrently. The changes include the background staging producer logic, state management, and comprehensive unit tests. Feedback on the implementation suggests checking for download errors before reporting a missing temporary file path to avoid confusing warnings when a download fails to start.
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.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
pkg/cache/inflight_staging_producer_internal_test.go (1)
121-123: ⚡ Quick winAdd cleanup for file handle to prevent leak on test failure.
The temp file
fis only closed on line 168 after the producer finishes. If the test fails earlier (e.g., timeout on line 164-165), the file handle will leak. Register cleanup immediately after creation to ensure the handle is closed even on test failure.🔧 Recommended fix
f, err := os.CreateTemp(dir, "src-*.nar") require.NoError(t, err) + t.Cleanup(func() { f.Close() })🤖 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_producer_internal_test.go` around lines 121 - 123, After creating the temp file with f, err := os.CreateTemp(dir, "src-*.nar") and checking require.NoError(t, err), register a test cleanup to close the file handle (e.g., t.Cleanup(func(){ _ = f.Close() })) so the file descriptor is closed even if the test fails early; reference the variable f created by CreateTemp and add the cleanup immediately after the require.NoError check.
🤖 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.
Nitpick comments:
In `@pkg/cache/inflight_staging_producer_internal_test.go`:
- Around line 121-123: After creating the temp file with f, err :=
os.CreateTemp(dir, "src-*.nar") and checking require.NoError(t, err), register a
test cleanup to close the file handle (e.g., t.Cleanup(func(){ _ = f.Close() }))
so the file descriptor is closed even if the test fails early; reference the
variable f created by CreateTemp and add the cleanup immediately after the
require.NoError check.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 59bf5430-2fea-438e-8e85-6950ffa1f17b
📒 Files selected for processing (3)
pkg/cache/cache.gopkg/cache/inflight_staging.gopkg/cache/inflight_staging_producer_internal_test.go
87a504c to
08d1cec
Compare
Address review feedback on PR #1353 (thread PRRT_kwDONV6tZs6Hr3Kj): produceStagingParts now reads ds.downloadError under the lock and returns it before the empty-assetPath check, so a download that failed to start (upstream 404, connection timeout) logs the real cause instead of the generic "no temp file path" sentinel. Co-Authored-By: Claude Opus 4.8 <[email protected]>
6c3d013 to
693658c
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@pkg/cache/inflight_staging.go`:
- Around line 171-182: The stagingRequested function currently treats any
non-nil staging_state as active; change it so it only returns true when the
returned st has Status equal to stagingStatusRequested. Locate
Cache.stagingRequested which calls getStagingState(ctx, hash) and replace the
final "return st != nil" with a check for st != nil && st.Status ==
stagingStatusRequested (preserving the existing error logging/behavior when err
!= nil).
🪄 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: 2a671583-1c35-4246-a8f1-187fd5239362
📒 Files selected for processing (3)
pkg/cache/cache.gopkg/cache/inflight_staging.gopkg/cache/inflight_staging_producer_internal_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
- pkg/cache/cache.go
08d1cec to
a989104
Compare
Address review feedback on PR #1353 (thread PRRT_kwDONV6tZs6Hr3Kj): produceStagingParts now reads ds.downloadError under the lock and returns it before the empty-assetPath check, so a download that failed to start (upstream 404, connection timeout) logs the real cause instead of the generic "no temp file path" sentinel. Co-Authored-By: Claude Opus 4.8 <[email protected]>
693658c to
b9b13c8
Compare
Holder side of in-flight NAR staging (#660 / #1289, group 5). When the feature is enabled with a distributed locker, the download goroutine now launches a staging producer that does nothing until a cross-pod waiter records a staging_state request for the hash. On activation it tails the holder's temp file via fileAvailableReader, which naturally backfills the already-written prefix from offset zero and then appends as bytes arrive, writing the NAR to shared storage as fixed-size immutable part-objects and advancing staging_state.parts_available after each part is durable. When the whole NAR is staged it publishes a terminal 'complete' status so a cross-pod reader can emit a clean EOF instead of waiting indefinitely. The producer records the temp file's native compression (ds.tempFileCompression, D9) so a cross-pod reader can transcode at parity with the same-pod path, and it is path-agnostic: the same tail-the-temp-file logic covers the eager-pipe, eager-simple, lazy and non-CDC download paths. Zero overhead until contention: no staging row read activates work unless a waiter exists, and the local (non-distributed) locker never stages at all.
Address review feedback on PR #1353 (thread PRRT_kwDONV6tZs6Hr3Kj): produceStagingParts now reads ds.downloadError under the lock and returns it before the empty-assetPath check, so a download that failed to start (upstream 404, connection timeout) logs the real cause instead of the generic "no temp file path" sentinel. Co-Authored-By: Claude Opus 4.8 <[email protected]>
b9b13c8 to
1f460eb
Compare
stagingRequested treated any existing staging_state row as a holder activation signal. A row left in a terminal/in-progress status (staging/complete) from an earlier cycle would re-activate a later holder with no active waiter, re-staging and duplicating immutable part uploads. Gate activation on Status == requested; a takeover reset (resetStagingState) rewinds the row to requested and re-arms it. Co-Authored-By: Claude Opus 4.8 <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
pkg/cache/inflight_staging.go (1)
29-31: ⚡ Quick winFix the state-machine comment to match the actual schema.
This comment still advertises an
"abandoned"terminal state, but this file only defines"requested","staging", and"complete". Leaving the extra state in the canonical status comment makes the contract look broader than it is.✏️ Suggested edit
-// 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. The "complete" +// terminal status is introduced alongside the staging completion logic that +// consumes it.Based on learnings,
staging_statehas exactly three status values:"requested","staging", and"complete".🤖 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, Update the top-of-file comment about the staging_state.status state-machine to reflect the actual schema values: replace the mention of an extra "abandoned" terminal state with the correct three statuses "requested", "staging", and "complete" so the comment matches the ent/schema/staging_state.go definition (refer to the staging_state.status description in this file).Source: Learnings
🤖 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.go`:
- Around line 297-305: The resetStagingState function currently treats a 0-rows
update as success; change its Update().Save(ctx) handling to capture the
returned rowsAffected and err from
c.dbClient.Ent().StagingState.Update().Where(stagingstate.HashEQ(hash)).SetPartsAvailable(0).SetStatus(stagingStatusRequested).Save(ctx)
and if err != nil return the wrapped error, but also if rowsAffected == 0 return
a new error indicating the reset touched no row (include the hash in the
message) so callers know the takeover reset did not re-arm staging; keep the
existing fmt.Errorf wrapping style for consistency.
---
Nitpick comments:
In `@pkg/cache/inflight_staging.go`:
- Around line 29-31: Update the top-of-file comment about the
staging_state.status state-machine to reflect the actual schema values: replace
the mention of an extra "abandoned" terminal state with the correct three
statuses "requested", "staging", and "complete" so the comment matches the
ent/schema/staging_state.go definition (refer to the staging_state.status
description in this file).
🪄 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: 00c71bc8-0e61-4cb0-b0ea-04508e1683c1
📒 Files selected for processing (4)
pkg/cache/cache.gopkg/cache/inflight_staging.gopkg/cache/inflight_staging_internal_test.gopkg/cache/inflight_staging_producer_internal_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
- pkg/cache/cache.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: 1
🧹 Nitpick comments (1)
pkg/cache/inflight_staging.go (1)
29-31: ⚡ Quick winFix the state-machine comment to match the actual schema.
This comment still advertises an
"abandoned"terminal state, but this file only defines"requested","staging", and"complete". Leaving the extra state in the canonical status comment makes the contract look broader than it is.✏️ Suggested edit
-// 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. The "complete" +// terminal status is introduced alongside the staging completion logic that +// consumes it.Based on learnings,
staging_statehas exactly three status values:"requested","staging", and"complete".🤖 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, Update the top-of-file comment about the staging_state.status state-machine to reflect the actual schema values: replace the mention of an extra "abandoned" terminal state with the correct three statuses "requested", "staging", and "complete" so the comment matches the ent/schema/staging_state.go definition (refer to the staging_state.status description in this file).Source: Learnings
🤖 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.go`:
- Around line 297-305: The resetStagingState function currently treats a 0-rows
update as success; change its Update().Save(ctx) handling to capture the
returned rowsAffected and err from
c.dbClient.Ent().StagingState.Update().Where(stagingstate.HashEQ(hash)).SetPartsAvailable(0).SetStatus(stagingStatusRequested).Save(ctx)
and if err != nil return the wrapped error, but also if rowsAffected == 0 return
a new error indicating the reset touched no row (include the hash in the
message) so callers know the takeover reset did not re-arm staging; keep the
existing fmt.Errorf wrapping style for consistency.
---
Nitpick comments:
In `@pkg/cache/inflight_staging.go`:
- Around line 29-31: Update the top-of-file comment about the
staging_state.status state-machine to reflect the actual schema values: replace
the mention of an extra "abandoned" terminal state with the correct three
statuses "requested", "staging", and "complete" so the comment matches the
ent/schema/staging_state.go definition (refer to the staging_state.status
description in this file).
🪄 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: 00c71bc8-0e61-4cb0-b0ea-04508e1683c1
📒 Files selected for processing (4)
pkg/cache/cache.gopkg/cache/inflight_staging.gopkg/cache/inflight_staging_internal_test.gopkg/cache/inflight_staging_producer_internal_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
- pkg/cache/cache.go
🛑 Comments failed to post (1)
pkg/cache/inflight_staging.go (1)
297-305:
⚠️ Potential issue | 🟠 Major | ⚡ Quick winReturn an error when the takeover reset doesn't touch a row.
Update().Save(ctx)returns0, nilwhen the hash row is missing. Treating that as success drops the activation signal silently, so a takeover holder can think it re-armed staging while cross-pod waiters are left with no"requested"row to observe.🛠️ Suggested fix
func (c *Cache) resetStagingState(ctx context.Context, hash string) error { - _, err := c.dbClient.Ent().StagingState.Update(). + n, err := c.dbClient.Ent().StagingState.Update(). Where(stagingstate.HashEQ(hash)). SetPartsAvailable(0). SetStatus(stagingStatusRequested). Save(ctx) if err != nil { return fmt.Errorf("reset staging state for %q: %w", hash, err) } + if n == 0 { + return fmt.Errorf("reset staging state for %q: %w", hash, errStagingStateMissing) + } return nil }Based on learnings,
resetStagingStaterewinds the existing row back to"requested"to re-arm a takeover holder without deleting that row.🤖 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 297 - 305, The resetStagingState function currently treats a 0-rows update as success; change its Update().Save(ctx) handling to capture the returned rowsAffected and err from c.dbClient.Ent().StagingState.Update().Where(stagingstate.HashEQ(hash)).SetPartsAvailable(0).SetStatus(stagingStatusRequested).Save(ctx) and if err != nil return the wrapped error, but also if rowsAffected == 0 return a new error indicating the reset touched no row (include the hash in the message) so callers know the takeover reset did not re-arm staging; keep the existing fmt.Errorf wrapping style for consistency.Source: Learnings
|
Documentation Updates 1 document(s) were updated by changes in this PR: NAR File Download and StreamingView Changes@@ -78,6 +78,22 @@
When CDC (Content-Defined Chunking) is enabled, the struct also tracks background CDC operations via `cdcWg`, allowing the streaming mechanism to differentiate between download completion and CDC chunking completion.
The struct includes a `compressedAssetPath` field for cleanup purposes. In the CDC download pipeline, this field remains empty since the compressed temp file was replaced with an `io.Pipe` in PR #1071.
+
+#### In-Flight NAR Staging (Holder Side)
+
+When `InflightStagingEnabled()` is true and a distributed locker is configured, the holder pod (the pod that wins the download lock and initiates the upstream NAR download) launches a background staging producer via `stageInflightNar()` to make in-flight bytes available to other pods in the cluster. This addresses the cross-pod coordination problem: once a holder begins downloading a NAR, other pods requesting the same NAR cannot serve the same-pod temp-file streaming path and must wait for the download to complete. The in-flight staging mechanism allows cross-pod readers to serve a complete NAR during the holder's download without waiting.
+
+**Activation mechanism**: The staging producer polls `staging_state` on a coarse interval (1 second, `stagingActivationPollInterval`) looking for a cross-pod waiter's "requested" status. It remains dormant until a request appears, so single-reader downloads have zero overhead—no staging occurs unless a waiter appears.
+
+**Part production process**: Once activated, `produceStagingParts()` tails the holder's temp file from offset zero using `fileAvailableReader`, which naturally backfills already-written bytes and appends new bytes as they arrive. It writes fixed-size part-objects to shared storage (default 8 MiB parts, configurable via `--cache-inflight-staging-part-size` or `defaultInflightStagingPartSize` constant). The use of `fileAvailableReader` ensures the staging producer blocks until bytes are available in the temp file and returns `io.EOF` once `ds.finalSize` is reached, allowing the staging producer to seamlessly handle both the backfill and append phases.
+
+**Progress tracking**: After each part is written to shared storage via `c.narStore.PutStagingPart()`, `advanceStagingParts()` increments `staging_state.parts_available` and records the temp file's native compression (`ds.tempFileCompression`, D9) so cross-pod readers can transcode at parity with same-pod reads. This progress tracking is transactional: the staging producer advances `parts_available` only after a part-object is durably written to shared storage, ensuring cross-pod readers never attempt to fetch parts that don't exist yet.
+
+**Completion marking**: When the download finishes (clean `io.EOF` or final short part `io.ErrUnexpectedEOF`), `markStagingComplete()` sets the status to "complete" so cross-pod readers know `parts_available` is final and can emit a clean EOF after consuming all parts. Without this terminal status, cross-pod readers would wait indefinitely at the frontier, not knowing whether more parts will appear or the download has finished.
+
+**Error handling**: If the download fails to start (e.g., upstream 404 or connection timeout), the staging producer surfaces the real download error (`ds.downloadError`) rather than staging a non-existent NAR. If staging fails mid-stream (e.g., a shared storage write error), parts are left in place for garbage collection or takeover by another holder. The staging producer logs a warning and returns without failing the holder's download: "in-flight staging producer stopped with error; staging parts left for GC/takeover".
+
+**Path-agnostic design**: The staging producer is path-agnostic and works for eager-pipe, eager-simple, lazy, and non-CDC download paths. Any download path that writes bytes to a temp file (`ds.assetPath`) can be staged, regardless of whether CDC chunking is enabled or how the upstream download is structured. The single-decompression mechanism and CDC pipeline both populate `ds.assetPath` with decompressed bytes, so the staging producer always tails uncompressed data.
#### Single-Decompression Mechanism for CDC
|
Holder side of in-flight NAR staging (#660 / #1289, group 5). When the
feature is enabled with a distributed locker, the download goroutine now
launches a staging producer that does nothing until a cross-pod waiter
records a staging_state request for the hash. On activation it tails the
holder's temp file via fileAvailableReader, which naturally backfills the
already-written prefix from offset zero and then appends as bytes arrive,
writing the NAR to shared storage as fixed-size immutable part-objects and
advancing staging_state.parts_available after each part is durable. When
the whole NAR is staged it publishes a terminal 'complete' status so a
cross-pod reader can emit a clean EOF instead of waiting indefinitely.
The producer records the temp file's native compression (ds.tempFileCompression,
D9) so a cross-pod reader can transcode at parity with the same-pod path,
and it is path-agnostic: the same tail-the-temp-file logic covers the
eager-pipe, eager-simple, lazy and non-CDC download paths. Zero overhead
until contention: no staging row read activates work unless a waiter exists,
and the local (non-distributed) locker never stages at all.