Skip to content

feat(cache): stage in-flight NAR on contention - #1353

Merged
kalbasit merged 3 commits into
mainfrom
feat-cache-stage-in-flight-nar
Jun 8, 2026
Merged

kalbasit merged 3 commits into
mainfrom
feat-cache-stage-in-flight-nar

Conversation

@kalbasit

@kalbasit kalbasit commented Jun 7, 2026

Copy link
Copy Markdown
Owner

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.

@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

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 00c71bc8-0e61-4cb0-b0ea-04508e1683c1

📥 Commits

Reviewing files that changed from the base of the PR and between 693658c and 29492de.

📒 Files selected for processing (4)
  • pkg/cache/cache.go
  • pkg/cache/inflight_staging.go
  • pkg/cache/inflight_staging_internal_test.go
  • pkg/cache/inflight_staging_producer_internal_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/cache/cache.go

📝 Walkthrough

Summary by CodeRabbit

  • New Features

    • Added in-flight NAR staging to improve download distribution when distributed locking is enabled, allowing downloaded files to be staged as fixed-size parts in shared storage, enabling faster availability to waiting consumers.
  • Tests

    • Added comprehensive test coverage for in-flight staging activation, backfilling, request handling, and disabled-state scenarios.

Walkthrough

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

Changes

In-flight NAR Staging Producer

Layer / File(s) Summary
Staging state machine and imports
pkg/cache/inflight_staging.go
Imports, new stagingStatusComplete status constant, errStagingNoTempFile sentinel, and foundational types.
Request polling and detection
pkg/cache/inflight_staging.go
stageInflightNar and waitForStagingRequest implement polling with immediate checks and exit conditions when download finishes or context cancels.
Part production and completion workflow
pkg/cache/inflight_staging.go
produceStagingParts tails the temp file from offset zero in configured-size chunks, uploads each part via NarStore, advances staging_state, and markStagingComplete transitions to terminal status.
Staging orchestration / integration
pkg/cache/inflight_staging.go, pkg/cache/cache.go
stageInflightNar gates on feature enablement and is spawned from pullNarIntoStore as a background goroutine tracked by backgroundWG.
Staging producer test suite
pkg/cache/inflight_staging_producer_internal_test.go, pkg/cache/inflight_staging_internal_test.go
Helpers build completed temp downloads and reassemble parts; tests verify activation-on-request, mid-download backfill+append, no-op when no request exists, and disabled-feature behavior.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • kalbasit/ncps#1352: Introduces NarStore staging object methods (PutStagingPart/GetStagingPart/DeleteStagingParts) that the producer uses to write/read staging parts.

Poem

I hop along the temp-file trail, 🐇
Part by part I leave a trail of care.
If another pod should call and wait,
I stitch the bytes so reads are straight.
A little rabbit shares the file with flair.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title 'feat(cache): stage in-flight NAR on contention' clearly and concisely summarizes the main change: implementing in-flight NAR staging when contention is detected, which is the primary feature added across all modified files.
Description check ✅ Passed The description provides a detailed explanation of the holder-side in-flight NAR staging implementation, directly matching the changes shown in the summary (download goroutine launching staging producer, temp file tailing, part-objects creation, compression handling).
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.

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

Comment thread pkg/cache/inflight_staging.go Resolved

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

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

121-123: ⚡ Quick win

Add cleanup for file handle to prevent leak on test failure.

The temp file f is 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

📥 Commits

Reviewing files that changed from the base of the PR and between 87a504c and 6c3d013.

📒 Files selected for processing (3)
  • pkg/cache/cache.go
  • pkg/cache/inflight_staging.go
  • pkg/cache/inflight_staging_producer_internal_test.go

@kalbasit
kalbasit force-pushed the feat-storage-in-flight-staging branch from 87a504c to 08d1cec Compare June 8, 2026 00:11
kalbasit added a commit that referenced this pull request Jun 8, 2026
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]>
@kalbasit
kalbasit force-pushed the feat-cache-stage-in-flight-nar branch from 6c3d013 to 693658c Compare June 8, 2026 00:11

@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/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

📥 Commits

Reviewing files that changed from the base of the PR and between 6c3d013 and 693658c.

📒 Files selected for processing (3)
  • pkg/cache/cache.go
  • pkg/cache/inflight_staging.go
  • pkg/cache/inflight_staging_producer_internal_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/cache/cache.go

Comment thread pkg/cache/inflight_staging.go Resolved
@kalbasit
kalbasit force-pushed the feat-storage-in-flight-staging branch from 08d1cec to a989104 Compare June 8, 2026 00:19
kalbasit added a commit that referenced this pull request Jun 8, 2026
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]>
@kalbasit
kalbasit force-pushed the feat-cache-stage-in-flight-nar branch from 693658c to b9b13c8 Compare June 8, 2026 00:19
Base automatically changed from feat-storage-in-flight-staging to main June 8, 2026 00:27
kalbasit and others added 2 commits June 8, 2026 00:27
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]>
@kalbasit
kalbasit force-pushed the feat-cache-stage-in-flight-nar branch from b9b13c8 to 1f460eb Compare June 8, 2026 00:27
@kalbasit
kalbasit enabled auto-merge (squash) June 8, 2026 00:27
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]>

@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

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

29-31: ⚡ Quick win

Fix 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_state has 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

📥 Commits

Reviewing files that changed from the base of the PR and between 693658c and 29492de.

📒 Files selected for processing (4)
  • pkg/cache/cache.go
  • pkg/cache/inflight_staging.go
  • pkg/cache/inflight_staging_internal_test.go
  • pkg/cache/inflight_staging_producer_internal_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/cache/cache.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: 1

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

29-31: ⚡ Quick win

Fix 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_state has 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

📥 Commits

Reviewing files that changed from the base of the PR and between 693658c and 29492de.

📒 Files selected for processing (4)
  • pkg/cache/cache.go
  • pkg/cache/inflight_staging.go
  • pkg/cache/inflight_staging_internal_test.go
  • pkg/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 win

Return an error when the takeover reset doesn't touch a row.

Update().Save(ctx) returns 0, nil when 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, resetStagingState rewinds 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

@kalbasit
kalbasit merged commit e40ee23 into main Jun 8, 2026
44 of 56 checks passed
@kalbasit
kalbasit deleted the feat-cache-stage-in-flight-nar branch June 8, 2026 00:49
@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
@@ -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
 

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