Skip to content

feat(cache): serve cross-pod NAR from staging - #1354

Merged
kalbasit merged 2 commits into
mainfrom
feat-cache-serve-cross-pod-nar
Jun 8, 2026
Merged

kalbasit merged 2 commits into
mainfrom
feat-cache-serve-cross-pod-nar

Conversation

@kalbasit

@kalbasit kalbasit commented Jun 7, 2026

Copy link
Copy Markdown
Owner

Reader side of in-flight NAR staging (#660 / #1289, group 6). A lock-losing
waiter now records a staging request on the contended hash and, on each poll
tick in pollForDownloadOrTakeOver, checks whether the holder has begun
staging. Once parts_available > 0 it returns a serve-from-staging directive
instead of waiting for the whole download; GetNar then streams the NAR by
tailing the part-objects.

The new stagingPartReader is the cross-pod analogue of fileAvailableReader:
it drains part-objects in order, blocks until the next part is durably
advertised via staging_state.parts_available, emits a clean io.EOF only once
the terminal complete marker is set and every part is consumed, and surfaces a
stream error (never a truncated clean EOF) if the producer stalls past the
per-part wait bound or the staging state is reset mid-stream. serveNarFromStaging
transcodes on the fly when the staged compression differs from the requested
one — at parity with the same-pod path — and advertises the served compression.

Staging is gated to NAR downloads only (narinfo passes allowStaging=false) and
to the distributed-locker feature guard, so single-instance and uncontended
downloads are unaffected. Cross-pod HTTP serve is exercised end-to-end in the
group-13 Redis+S3 integration test; the reader contracts are unit-tested here.

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jun 7, 2026
@dosubot dosubot Bot added enhancement New feature or request go Pull requests that update go code labels Jun 7, 2026
@coderabbitai

coderabbitai Bot commented Jun 7, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

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

More reviews will be available in 14 minutes and 4 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 6a7b2181-0547-4b54-8098-81bed969e6f1

📥 Commits

Reviewing files that changed from the base of the PR and between 1c37969 and bf7af11.

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

Walkthrough

This PR enables cross-pod in-flight staging as a fast-path for NAR serving. When a download-lock waiter detects staging parts are ready, it signals GetNar to serve directly from staging with optional compression transcoding, avoiding the wait for full download completion.

Changes

Cross-pod in-flight staging fast-path for NAR serving

Layer / File(s) Summary
Staging serve model and readiness check
pkg/cache/cache.go, pkg/cache/inflight_staging_reader.go
stagingServeInfo tracks hash and compression; stagingServeReady detects when staging parts are available; downloadState.stagingServe carries the directive to serve from staging.
Staging part reader with polling and error handling
pkg/cache/inflight_staging_reader.go
stagingPartReader sequentially streams staging parts with fixed-cadence polling and per-part timeouts. Returns clean EOF only on completion; fails with errStagingStall if producer stops advancing within timeout bound, or errStagingReset if staging_state disappears mid-read.
NAR serving from staging with on-the-fly transcoding
pkg/cache/inflight_staging_reader.go
serveNarFromStaging wires the staging reader into NAR serving; if staged bytes are compressed but the request expects uncompressed, wraps with nar.DecompressReader and updates narURL.Compression to reflect served encoding.
GetNar fast-path for staging directive
pkg/cache/cache.go
GetNar checks ds.stagingServe and immediately serves from staging via serveNarFromStaging instead of waiting for download, updating metrics to result=staging and status=success|error.
Download coordination with staging detection
pkg/cache/cache.go
Extends coordinateDownload and pollForDownloadOrTakeOver with allowStaging flag. When enabled in the lock-losing fallback, the waiter checks stagingServeReady, sets ds.stagingServe, closes signal channels, and returns so GetNar can serve immediately. prePullNarInfo disables staging; prePullNar enables it during active download.
Staging reader and transcoding test coverage
pkg/cache/inflight_staging_reader_internal_test.go
Tests verify complete-part reassembly with clean EOF, stall detection (error not EOF when producer stalls), and on-the-fly decompression with correct encoding advertisement.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • kalbasit/ncps#1290: Both PRs modify the download-lock contention flow in pkg/cache/cache.go—specifically the lock-losing waiter path and the coordinateDownload/pollForDownloadOrTakeOver logic that controls what GetNar returns—so the staging fast-path introduced in the main PR is directly layered onto the same coordination mechanism changed in #1290.
  • kalbasit/ncps#1349: Both PRs touch the Cache.GetNar "in-flight streaming" path semantics—main PR adds stagingServe fast-path streaming (serving with unknown length -1 when not yet durably stored), and retrieved PR relaxes TestGetNarInfoOpaqueUpstreamURL to accept -1 for that same size behavior.

Suggested labels

go, size:L, merge-stack

Poem

🐰 A waiter once stood by the staging door,
Watching parts arrive, then one part more—
"Why wait for download?" thought the clever hare,
"Stream them right now through cross-pod air!"
NAR transcoding blooms where staging parts flow free,
Fast-path joy for thee and me.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main feature being implemented: serving cross-pod NAR from staging, which is the core objective of this pull request.
Description check ✅ Passed The description is detailed and directly related to the changeset, explaining the reader-side implementation of in-flight NAR staging with specific technical details about how staging requests are recorded and streamed.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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


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

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request implements cross-pod NAR streaming from in-flight staging part-objects, allowing lock-losing waiters to tail and serve NAR parts directly instead of waiting for the lock holder's download to complete. The feedback focuses on improving error handling and context propagation within the new stagingPartReader, specifically suggesting to fail fast on context cancellation in Read and to return raw context errors directly instead of wrapping them in openPart.

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_reader.go Resolved
Comment thread pkg/cache/inflight_staging_reader.go Resolved
Comment thread pkg/cache/inflight_staging_reader.go Resolved
@dosubot

dosubot Bot commented Jun 7, 2026 •

Copy link
Copy Markdown

Documentation Updates

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

NAR File Download and Streaming
View Changes
@@ -94,6 +94,26 @@
 **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.
+
+#### In-Flight NAR Staging (Waiter Side)
+
+Lock-losing waiters can serve NARs from staging parts while the holder downloads, rather than waiting for completion. When a waiter detects that another pod holds the download lock, it records a staging request and polls for available parts on each tick in `pollForDownloadOrTakeOver`.
+
+**Request signaling**: The waiter calls `markStagingRequested` to signal the holder that cross-pod staging is needed. This is an idempotent one-shot marker the holder reads on its own loop, adding no churn to the system.
+
+**Part availability detection**: On each 200ms poll tick, the waiter checks `stagingServeReady` to determine if parts are available. Once `parts_available > 0`, the function returns a staging directive (`downloadState.stagingServe`) instead of continuing to wait for the whole download.
+
+**Streaming from staging parts**: When `GetNar` receives a staging directive, it calls `serveNarFromStaging` to stream the NAR from staging part-objects rather than storage. The implementation creates a `stagingPartReader` that tails part-objects in order, polling `staging_state.parts_available` every 200ms and blocking until each part is durably available.
+
+**Transcoding support**: The reader transcodes if needed—for example, decompressing staged bytes when the client requests uncompressed data—at parity with the same-pod streaming path. The returned `narURL.Compression` advertises the compression actually served.
+
+**Clean EOF semantics**: The reader emits a clean `io.EOF` only when `status = complete` and all parts have been consumed. If the producer stalls (stops advancing `parts_available` without setting the complete marker), the reader surfaces `errStagingStall` after the per-part wait timeout. If the `staging_state` row disappears mid-stream (reset by a takeover), the reader surfaces `errStagingReset`. Context cancellation is propagated immediately. This ensures a truncated NAR is never delivered as a clean EOF.
+
+**Per-part timeout**: The per-part wait bound reuses `chunkWaitTimeout` from progressive chunk streaming for configuration parity. A steadily-advancing producer is never penalized; only a stalled one triggers the timeout.
+
+**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.
 
 #### Single-Decompression Mechanism for CDC
 

How did I do? Any feedback?  Join Discord

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@pkg/cache/cache.go`:
- Around line 6435-6436: The metric description for
downloadCoordinationFallbackTotal (ncps_download_coordination_fallback_total) is
stale and must include the new outcome value "served_from_staging"; update the
metric's enum/documentation to list all outcomes including served_from_staging
(alongside served_by_peer, take_over, give_up, caller_canceled) and ensure any
docstring/comment or Prometheus metric help text attached to
downloadCoordinationFallbackTotal is revised accordingly so dashboards/alerts
reflect the new enum.
🪄 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: 9db231bc-6a8a-4ba9-979e-9d8322a761eb

📥 Commits

Reviewing files that changed from the base of the PR and between 6c3d013 and 1c37969.

📒 Files selected for processing (3)
  • pkg/cache/cache.go
  • pkg/cache/inflight_staging_reader.go
  • pkg/cache/inflight_staging_reader_internal_test.go

Comment thread pkg/cache/cache.go Resolved
@kalbasit
kalbasit force-pushed the feat-cache-stage-in-flight-nar branch from 6c3d013 to 693658c Compare June 8, 2026 00:11
kalbasit added a commit that referenced this pull request Jun 8, 2026
Address review feedback on PR #1354:

- stagingPartReader.Read checks ctx.Err() up front so a cancelled caller
  fails fast before any part I/O (PRRT_kwDONV6tZs6Hr3Gz).
- openPart returns the raw context.Canceled / DeadlineExceeded from
  getStagingState and GetStagingPart instead of wrapping it, so callers can
  errors.Is the cancellation (PRRT_kwDONV6tZs6Hr3G0, PRRT_kwDONV6tZs6Hr3G1).
- Document the served_from_staging outcome on
  ncps_download_coordination_fallback_total so the metric enum matches the
  emitted values (PRRT_kwDONV6tZs6Hr4Zc).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@kalbasit
kalbasit force-pushed the feat-cache-serve-cross-pod-nar branch from 1c37969 to cdfc03f Compare June 8, 2026 00:11
@kalbasit
kalbasit force-pushed the feat-cache-stage-in-flight-nar branch from 693658c to b9b13c8 Compare June 8, 2026 00:19
kalbasit added a commit that referenced this pull request Jun 8, 2026
Address review feedback on PR #1354:

- stagingPartReader.Read checks ctx.Err() up front so a cancelled caller
  fails fast before any part I/O (PRRT_kwDONV6tZs6Hr3Gz).
- openPart returns the raw context.Canceled / DeadlineExceeded from
  getStagingState and GetStagingPart instead of wrapping it, so callers can
  errors.Is the cancellation (PRRT_kwDONV6tZs6Hr3G0, PRRT_kwDONV6tZs6Hr3G1).
- Document the served_from_staging outcome on
  ncps_download_coordination_fallback_total so the metric enum matches the
  emitted values (PRRT_kwDONV6tZs6Hr4Zc).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@kalbasit
kalbasit force-pushed the feat-cache-serve-cross-pod-nar branch from cdfc03f to 891de62 Compare June 8, 2026 00:19
@kalbasit
kalbasit force-pushed the feat-cache-stage-in-flight-nar branch from b9b13c8 to 1f460eb Compare June 8, 2026 00:27
kalbasit added a commit that referenced this pull request Jun 8, 2026
Address review feedback on PR #1354:

- stagingPartReader.Read checks ctx.Err() up front so a cancelled caller
  fails fast before any part I/O (PRRT_kwDONV6tZs6Hr3Gz).
- openPart returns the raw context.Canceled / DeadlineExceeded from
  getStagingState and GetStagingPart instead of wrapping it, so callers can
  errors.Is the cancellation (PRRT_kwDONV6tZs6Hr3G0, PRRT_kwDONV6tZs6Hr3G1).
- Document the served_from_staging outcome on
  ncps_download_coordination_fallback_total so the metric enum matches the
  emitted values (PRRT_kwDONV6tZs6Hr4Zc).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@kalbasit
kalbasit force-pushed the feat-cache-serve-cross-pod-nar branch from 891de62 to e9b0c73 Compare June 8, 2026 00:27
kalbasit added a commit that referenced this pull request Jun 8, 2026
Address review feedback on PR #1354:

- stagingPartReader.Read checks ctx.Err() up front so a cancelled caller
  fails fast before any part I/O (PRRT_kwDONV6tZs6Hr3Gz).
- openPart returns the raw context.Canceled / DeadlineExceeded from
  getStagingState and GetStagingPart instead of wrapping it, so callers can
  errors.Is the cancellation (PRRT_kwDONV6tZs6Hr3G0, PRRT_kwDONV6tZs6Hr3G1).
- Document the served_from_staging outcome on
  ncps_download_coordination_fallback_total so the metric enum matches the
  emitted values (PRRT_kwDONV6tZs6Hr4Zc).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@kalbasit
kalbasit force-pushed the feat-cache-serve-cross-pod-nar branch from e9b0c73 to 1926202 Compare June 8, 2026 00:42
Base automatically changed from feat-cache-stage-in-flight-nar to main June 8, 2026 00:49
@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Jun 8, 2026
kalbasit and others added 2 commits June 8, 2026 00:49
Reader side of in-flight NAR staging (#660 / #1289, group 6). A lock-losing
waiter now records a staging request on the contended hash and, on each poll
tick in pollForDownloadOrTakeOver, checks whether the holder has begun
staging. Once parts_available > 0 it returns a serve-from-staging directive
instead of waiting for the whole download; GetNar then streams the NAR by
tailing the part-objects.

The new stagingPartReader is the cross-pod analogue of fileAvailableReader:
it drains part-objects in order, blocks until the next part is durably
advertised via staging_state.parts_available, emits a clean io.EOF only once
the terminal complete marker is set and every part is consumed, and surfaces a
stream error (never a truncated clean EOF) if the producer stalls past the
per-part wait bound or the staging state is reset mid-stream. serveNarFromStaging
transcodes on the fly when the staged compression differs from the requested
one — at parity with the same-pod path — and advertises the served compression.

Staging is gated to NAR downloads only (narinfo passes allowStaging=false) and
to the distributed-locker feature guard, so single-instance and uncontended
downloads are unaffected. Cross-pod HTTP serve is exercised end-to-end in the
group-13 Redis+S3 integration test; the reader contracts are unit-tested here.
Address review feedback on PR #1354:

- stagingPartReader.Read checks ctx.Err() up front so a cancelled caller
  fails fast before any part I/O (PRRT_kwDONV6tZs6Hr3Gz).
- openPart returns the raw context.Canceled / DeadlineExceeded from
  getStagingState and GetStagingPart instead of wrapping it, so callers can
  errors.Is the cancellation (PRRT_kwDONV6tZs6Hr3G0, PRRT_kwDONV6tZs6Hr3G1).
- Document the served_from_staging outcome on
  ncps_download_coordination_fallback_total so the metric enum matches the
  emitted values (PRRT_kwDONV6tZs6Hr4Zc).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@kalbasit
kalbasit force-pushed the feat-cache-serve-cross-pod-nar branch from 1926202 to bf7af11 Compare June 8, 2026 00:49
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels Jun 8, 2026
@kalbasit
kalbasit enabled auto-merge (squash) June 8, 2026 00:49
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