Skip to content

fix(cache): hold the NAR download lock through the eager-CDC chunking window - #1379

Merged
kalbasit merged 7 commits into
mainfrom
fix-cdc-staging-lock-lifecycle
Jun 9, 2026
Merged

kalbasit merged 7 commits into
mainfrom
fix-cdc-staging-lock-lifecycle

Conversation

@kalbasit

@kalbasit kalbasit commented Jun 9, 2026

Copy link
Copy Markdown
Owner

Summary

  • Hold the per-hash NAR download lock through the eager-CDC chunking window (release on ds.done, not ds.stored which closes at chunk start). A cross-pod reader arriving mid-chunking now contends and engages in-flight staging via the already-tested download-window contention path, instead of acquiring the now-free lock and bypassing staging.
  • For an uncompressed (.nar) cross-pod request during chunking, the complete NAR is served from in-flight staging — more robust than the fragile progressive-chunk reassembly.
  • For a compressed (.nar.xz) request during chunking — which cannot be reconstructed from the decompressed eager-CDC in-flight bytes (ncps has no NAR compressor, and a re-compressed file would not match the narinfo FileHash/FileSize) — serveNarFromStaging now returns not-found so the client falls back to an upstream that has the original compressed file, rather than being served the uncompressed bytes mislabeled as xz.
  • Non-CDC and lazy-CDC download-lock timing is unchanged; holder death during chunking is still recovered via the lock TTL. No new flags, schema, or migrations — behavior-only, behind the existing (default-off) inflight-staging flag.

The producer + temp file already survive the chunking window (waitForStagingRequest polls until ds.done; the temp is removed only after ds.cdcWg), so no producer-liveness code was needed — verified by test rather than added.

Scope / honest caveat

This is the lock-lifetime + safe-fallback fix. The cross-pod "served from staging during chunking" behavior is unit-verified (lock held through chunking; producer stages a mid-chunk request; compressed→fallback) but has no green end-to-end run yet: the contention e2e's chunking-window expectation (serve compressed from staging) is itself unachievable for eager CDC and needs redesigning. The root fix — advertise narinfo none for CDC NARs so .nar.xz is never requested (which also subsumes a pre-existing same-pod corruption of the same shape) — is deferred to a follow-up. So this PR does not fully close #1289 on its own; it removes the regression path and the corruption, and serves the uncompressed cross-pod case from staging.

Refs #1289.

Test plan

  • `task fmt`, `task lint` (0 issues), unit `task test` green under `-race`
  • New unit tests: lock held through chunking (red→green); producer stages a request recorded mid-chunking; compressed-request-from-uncompressed-staging → fallback
  • Cross-pod chunking-window e2e — deferred (needs redesign to assert the uncompressed staging path / compressed→fallback)

kalbasit and others added 5 commits June 8, 2026 18:28
… window

Under CDC + HA (replicas > 1), a cross-pod reader requesting a compressed NAR
(e.g. .nar.xz) while a peer was still chunking it could 404. coordinateDownload
released the download:nar lock as soon as the raw bytes were stored (ds.stored,
which closes at chunk start via onNarFileReady), so the reader acquired the
now-free lock mid-chunking, hit the post-lock servability check, and
short-circuited to chunk-based serving — which cannot reconstruct a compressed
variant from decompressed chunks.

Hold the lock until ds.done instead. For eager CDC, ds.done closes only after
chunking completes, so the lock is held through the whole chunking window and a
cross-pod reader arriving mid-chunking contends for it, entering
pollForDownloadOrTakeOver -> markStagingRequested and serving from in-flight
staging (the already-tested download-window contention path, #1374/#1375). For
non-CDC and lazy CDC, ds.done closes together with ds.stored, so release timing
is unchanged. Holder death during chunking is still recovered via the lock TTL.

The holder's staging producer already stays alive until ds.done and the eager
temp file persists until post-chunking cleanup, so a mid-chunking staging
request is observed and staged with no producer change.

Tests:
- TestCoordinateDownload_HoldsNARLockThroughChunking: lock held after ds.stored,
  released after ds.done (red against the old ds.stored release).
- TestStageInflightNar_ActivatesDuringChunkingWindow: a request recorded after
  ds.stored is still staged from the temp file (producer liveness).

Refs #1289

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…aging

The lock-lifetime fix routes a cross-pod compressed request mid-chunking into
in-flight staging. For eager CDC the staged bytes are decompressed (the temp is
decompressed for chunking), and ncps cannot reconstruct a compressed variant: it
has no NAR compressor, and a re-compressed file would not match the narinfo's
FileHash/FileSize. Serving the uncompressed bytes for a .nar.xz request produced a
corrupt HTTP 200 (the served body fails xz decompression) — caught by the
inflight-staging contention e2e.

serveNarFromStaging now takes the compression the client originally requested
(which the CDC serve path normalizes away on narURL) and returns
storage.ErrNotFound when a compressed variant is requested but only uncompressed
staging exists. The client then falls back to an upstream that has the real
compressed file — the same outcome as before the lock-fix, but without corruption.
Uncompressed (.nar) cross-pod requests during the chunking window continue to be
served from staging.

Refs #1289

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…lback

The e2e (inflight-staging contention, --window chunking) proved that an eager-CDC
compressed request cannot be served from staging (in-flight bytes are decompressed;
ncps has no NAR compressor and a re-compressed file would not match the narinfo
FileHash/FileSize). Correct the CHANGELOG, design.md and the cdc-chunking /
inflight-nar-staging spec deltas to the true contract: an uncompressed cross-pod
request mid-chunking is served from staging; a compressed request returns not-found
so the client falls back to upstream (Guard A). Record the deferred narinfo-none
root fix (memory project_cdc_narinfo_none_root_fix) and the still-red e2e + the
pre-existing same-pod corruption as follow-ups.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Move the change to openspec/changes/archive/ and sync its delta specs into the
main specs: cdc-chunking gains the "NAR download lock held through the eager-CDC
chunking window" requirement; inflight-nar-staging's cross-pod serve + activation
requirements are updated to the true contract (uncompressed served from staging,
compressed mid-chunking falls back to upstream).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@kalbasit

kalbasit commented Jun 9, 2026 •

Copy link
Copy Markdown
Owner Author

This change is part of the following stack:

Change managed by git-spice.

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. go Pull requests that update go code labels Jun 9, 2026
@coderabbitai

coderabbitai Bot commented Jun 9, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 42e33b4d-508b-4c8f-a169-c33789c6a756

📥 Commits

Reviewing files that changed from the base of the PR and between 532439c and 7f91f18.

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

📝 Walkthrough

Summary by CodeRabbit

  • Bug Fixes
    • Held NAR download lock through the entire CDC chunking window in HA setups to prevent mid-chunk lock release and reader-induced integrity issues.
    • During the chunking window, uncompressed NAR requests are served from in‑flight staging; compressed variant requests now return not‑found so clients reliably fall back to upstream originals, avoiding mislabelled/corrupt compressed responses.

Walkthrough

This PR holds the NAR download lock through eager-CDC chunking, threads the client-requested compression into staging serves to detect unsupported compressed requests (returning not-found), and adds tests and spec/docs to validate lock timing and staging producer liveness during the chunking window.

Changes

CDC Chunking Lock Lifecycle & In-Flight Staging Coordination

Layer / File(s) Summary
Design and Architecture Specifications
openspec/changes/archive/2026-06-09-fix-cdc-staging-lock-lifecycle/proposal.md, openspec/changes/archive/2026-06-09-fix-cdc-staging-lock-lifecycle/design.md, openspec/changes/archive/2026-06-09-fix-cdc-staging-lock-lifecycle/specs/cdc-chunking/spec.md, openspec/changes/archive/2026-06-09-fix-cdc-staging-lock-lifecycle/specs/inflight-nar-staging/spec.md, openspec/specs/...
Design, proposal, and spec updates document the eager-CDC lock-lifecycle mismatch and the chosen solution: hold the download lock through ds.done, activate staging only on cross-pod contention, and define uncompressed vs compressed request semantics during chunking.
Lock Lifecycle Through Chunking Window
pkg/cache/cache.go, pkg/cache/coordinate_download_lock_lifetime_internal_test.go
coordinateDownload now holds the per-hash NAR download lock until ds.done (for waitForStorage=false NAR downloads), preventing mid-chunk free-lock acquisition by other replicas. New test asserts the lock is held during the chunking window and released after completion.
Requested Compression Parameter & Fallback Logic
pkg/cache/cache.go, pkg/cache/inflight_staging_reader.go, pkg/cache/inflight_staging_reader_internal_test.go
GetNar captures the requested compression and passes it to serveNarFromStaging; serveNarFromStaging now detects compressed requests that cannot be satisfied from staging (e.g., only uncompressed parts present) and returns storage.ErrNotFound to force upstream fallback. New helper and tests validate the fallback matrix and ensure no mislabeled compressed serving.
Producer Liveness During Chunking Window
pkg/cache/inflight_staging_chunking_window_internal_test.go
Test verifies the in-flight staging producer remains alive and completes staging when a cross-pod request arrives after ds.stored but before chunking finishes, asserting parts, compression label, and readable staged content.
Implementation Tasks and Project Documentation
openspec/changes/archive/2026-06-09-fix-cdc-staging-lock-lifecycle/tasks.md, CHANGELOG.md, openspec/changes/archive/2026-06-09-fix-cdc-staging-lock-lifecycle/.openspec.yaml
Task checklist records the implementation plan and tests; changelog entry documents the fix; archive metadata added.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

  • kalbasit/ncps#1355: Modifies eager-CDC chunking-window read path to prefer serving from in-flight staging parts over progressive chunk reassembly, complementary to this PR's lock-hold change.
  • kalbasit/ncps#1353: Adds core in-flight staging coordination; this PR builds on that by adjusting lock lifetime and compression-handling in the staging serve path.
  • kalbasit/ncps#1290: Reworks lock-loss poll/reacquire behavior in coordinateDownload, related to distributed coordination and contention handling addressed here.

Suggested labels

bug, merge-stack

Poem

🐰 A little rabbit hops to say,
The lock now holds the chunking way.
Staged bytes flow uncompressed and clear,
Compressed requests go find upstream gear.
Cross-pods now contend, no data fear.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically identifies the main change: holding the NAR download lock through the eager-CDC chunking window, which is the primary focus of the PR.
Description check ✅ Passed The description is detailed and directly related to the changeset, explaining the lock-lifetime fix, safe fallback behavior for compressed requests, and the reasoning behind the changes.
Linked Issues check ✅ Passed The PR addresses the core requirements from #1289: it implements safe serving of NARs during chunking by holding the download lock and engaging in-flight staging for uncompressed requests, with fallback for compressed requests that cannot be reconstructed.
Out of Scope Changes check ✅ Passed All changes are directly within scope of the linked issue #1289: lock-lifetime management, in-flight staging coordination, and safe fallback behavior. No unrelated changes detected.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ 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 addresses a 404/corruption issue during the eager-CDC chunking window in HA setups by holding the NAR download lock until chunking completes (ds.done). This forces cross-pod readers arriving mid-chunking to contend for the lock and utilize in-flight staging. Uncompressed requests are served from staging, while compressed requests cleanly return a not-found error to trigger an upstream fallback. The reviewer pointed out a high-severity issue in compressedRequestNeedsUpstreamFallback: it should also trigger an upstream fallback if the requested compression is not none and does not exactly match the available compression (e.g., requesting xz when zstd is available), as the system cannot transcode between different compressed formats.

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

dosubot Bot commented Jun 9, 2026

Copy link
Copy Markdown

Related Knowledge

1 document with suggested updates is ready for review.

kalbasit's Space

NAR File Download and Streaming
View Suggested Changes
@@ -85,7 +85,9 @@
 
 **Activation mechanism**: The staging producer polls `staging_state` on a tight interval (200ms, `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. The short interval ensures the holder observes the request while the download is still in flight; otherwise a fast download finishes first and staging never engages (the temp file is gone before the producer can tail it). The 200ms interval matches the waiter's own poll interval.
 
-**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. If the staging request is observed after the download has already completed (the temp file has been removed by the post-completion cleanup), the producer treats this as a clean no-op: the NAR is already committed to shared storage and cross-pod waiters serve it from there, so staging is unnecessary. This prevents spurious errors when a fast download finishes before the staging producer can engage.
+**Eager-CDC chunking window**: For eager-CDC NARs (chunked progressively during download), the in-flight window extends beyond the byte download through the entire chunking operation. The holder keeps its staging producer alive for the duration of that chunking window (until `ds.done`, which closes only after chunking completes) so that a waiter whose staging request arrives after byte download but before chunking completes is still staged and served. The download lock is held through the entire eager-CDC chunking window to cause cross-pod readers arriving mid-chunking to contend for the lock and engage in-flight staging, rather than acquiring a free lock and short-circuiting to chunk-based serving (which would 404 a compressed request).
+
+**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. The holder treats a staging request as a clean no-op only when the NAR is genuinely fully materialized in shared storage—a committed whole-file copy, or a finished chunk set (`total_chunks > 0`). An actively-chunking eager-CDC NAR (`total_chunks == 0` with a live chunker and no whole-file copy in shared storage) is NOT such a case and is still staged. This prevents spurious errors when a fast download finishes before the staging producer can engage.
 
 **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.
 
@@ -107,15 +109,17 @@
 
 2. **Finished-asset detection**: Checks whether the NAR is fully materialized—either a whole file in the store OR a fully-chunked nar_file (`total_chunks > 0`). This check uses `hasFinishedNar` (not `isServable`), which deliberately excludes actively-chunking NARs (`total_chunks = 0` with live chunker). If the asset is finished, returns a completed "served-by-peer" state so `GetNar` serves it directly. An actively-chunking NAR is NOT treated as finished and falls through to states (3) or (4) to avoid routing to chunk-based serving, which would 404 a compressed request.
 
-3. **Actively-chunking with staging**: When the holder is alive and actively chunking a NAR (`total_chunks = 0`, `nar_file` exists, chunker live), AND staging is enabled and parts are available (`stagingServeReady`), the waiter serves from staging parts instead of routing to chunk-based serving. This prevents HTTP 404 errors that would occur if the system tried to serve a compressed NAR variant (e.g., `.nar.xz`) from decompressed chunks. The staging path transcodes to the requested compression at parity with the same-pod streaming path. This state was added to fix the eager-CDC cross-pod 404 under contention.
+3. **Actively-chunking with staging**: When the holder is alive and actively chunking a NAR (`total_chunks = 0`, `nar_file` exists, chunker live), AND staging is enabled and parts are available (`stagingServeReady`), the waiter serves from staging parts instead of routing to chunk-based serving. For an eager-CDC NAR being chunked, the staged bytes are uncompressed (the temp is decompressed for chunking), so uncompressed (`none`) requests are served the complete NAR from staging, while compressed variant requests (e.g. `.nar.xz`) return not-found so the client falls back to an upstream that has the original compressed file.
 
 4. **Actively-chunking without staging**: When the holder is alive and actively chunking, but no staging parts are available, returns a completed "served-by-peer" state so `GetNar` routes to progressive chunk streaming (`streamProgressiveChunks`). This preserves the no-staging CDC path but only serves decompressed data (compressed requests would 404 in this scenario without staging).
 
 **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.
 
+**Eager-CDC compressed request handling**: For an eager-CDC NAR being chunked, the staged bytes are uncompressed (the temp is decompressed for chunking). Uncompressed (`none`) requests are served the complete NAR from staging. Compressed variant requests (e.g. `.nar.xz`) cannot be reconstructed from uncompressed staged bytes (ncps has no NAR compressor, and a re-compressed file would not match the narinfo `FileHash`/`FileSize`), so the staging serve returns not-found and the client falls back to an upstream that has the original compressed file—never the uncompressed bytes mislabeled as the requested compression.
+
 **Precedence during the chunking window**: When `total_chunks == 0` (actively chunking state), `getNarFromChunks` first checks for in-flight staging parts if staging is enabled. If staging parts are available, it serves the complete NAR from them instead of entering the progressive chunk streaming path (`streamProgressiveChunks`). This precedence improves reliability: staged whole-NAR parts are a complete, ordered representation, so serving from them avoids the fragile progressive reassembly that can truncate. This precedence is strictly scoped to the chunking window—when `total_chunks > 0` (steady-state chunk serving), the new branch is not reached and behavior is unchanged. When serving from staging in this path, the `TransparentZstd` flag is cleared because `serveNarFromStaging` sets the compression based on what's actually in staging. If no staging parts are available, the system falls back to the progressive-chunk path as before.
 
-**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.
+**Transcoding support**: The reader decompresses staged bytes when the client requests uncompressed data—for example, staged compressed bytes served as uncompressed—at parity with the same-pod streaming path. A request for a compressed variant backed only by uncompressed staged bytes (the eager-CDC chunking window) returns not-found so the client falls back to upstream. 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.
 
@@ -316,6 +320,8 @@
 For distributed locks in HA deployments, locks are automatically refreshed during long-running NAR downloads to prevent expiration. The download lock has a default TTL of 5 minutes (`downloadLockTTL`). If a NAR download exceeds this duration, the lock could expire mid-download, allowing other pods to re-acquire the lock and start duplicate downloads. This previously resulted in errors such as "failed to release distributed lock (will expire via TTL)" with "redsync: failed to unlock, lock was already expired".
 
 The system implements an automatic lock TTL refresh mechanism using a background refresher goroutine. When the download lock is acquired in `coordinateDownload`, the refresher starts immediately and periodically extends the lock TTL at intervals of `ttl*2/3` (e.g., every 3 minutes 20 seconds for a 5-minute TTL). This ensures the lock remains valid for the entire duration of the download, regardless of how long it takes. The refresher stops automatically when the download completes or when the lock is released.
+
+For NAR downloads (not narinfo), the download lock is released once the asset is fully materialized (`ds.done`), not merely stored (`ds.stored`). For eager-CDC NARs, `ds.stored` closes at chunk start while `ds.done` closes only after chunking completes, so the lock is held through the entire chunking window. This causes a cross-pod reader arriving mid-chunking to contend for the held lock and engage in-flight staging instead of acquiring a free lock and short-circuiting to chunk-based serving (which would 404 a compressed request). For non-CDC and lazy-CDC downloads, `ds.done` closes together with `ds.stored`, so the release timing is unchanged. Holder death during the chunking window is still recovered through download-lock TTL expiry and takeover.
 
 For local locks (single-instance mode), the `Extend` operation is a no-op since in-process locks don't expire. This improvement significantly increases reliability in high-availability deployments, especially for large NAR files that take longer than the default TTL to download.
 

[Accept] [Edit] [Decline]

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/coordinate_download_lock_lifetime_internal_test.go`:
- Around line 15-18: The test helper currently swallows TryLock errors by
returning false when `c.downloadLocker.TryLock(...)` returns an `err`, which
masks backend failures; change the helper so it does not mask errors—either make
it return (bool, error) and propagate the `err` (return `acquired, err`) to
callers, or make it fail the test immediately (e.g., call the test helper's
failure helper) when `err != nil`; in other words, stop treating `err` as a "not
acquired" case and surface the actual `err` from `TryLock` instead of returning
false.
🪄 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: 762e4eb7-c5f1-464d-92c9-f703c48a3aea

📥 Commits

Reviewing files that changed from the base of the PR and between 32a653a and 532439c.

📒 Files selected for processing (14)
  • CHANGELOG.md
  • openspec/changes/archive/2026-06-09-fix-cdc-staging-lock-lifecycle/.openspec.yaml
  • openspec/changes/archive/2026-06-09-fix-cdc-staging-lock-lifecycle/design.md
  • openspec/changes/archive/2026-06-09-fix-cdc-staging-lock-lifecycle/proposal.md
  • openspec/changes/archive/2026-06-09-fix-cdc-staging-lock-lifecycle/specs/cdc-chunking/spec.md
  • openspec/changes/archive/2026-06-09-fix-cdc-staging-lock-lifecycle/specs/inflight-nar-staging/spec.md
  • openspec/changes/archive/2026-06-09-fix-cdc-staging-lock-lifecycle/tasks.md
  • openspec/specs/cdc-chunking/spec.md
  • openspec/specs/inflight-nar-staging/spec.md
  • pkg/cache/cache.go
  • pkg/cache/coordinate_download_lock_lifetime_internal_test.go
  • pkg/cache/inflight_staging_chunking_window_internal_test.go
  • pkg/cache/inflight_staging_reader.go
  • pkg/cache/inflight_staging_reader_internal_test.go

kalbasit and others added 2 commits June 8, 2026 21:26
…equest

compressedRequestNeedsUpstreamFallback only flagged compressed requests
backed by uncompressed staging. A compressed request backed by a
*different* compressed format (e.g. xz requested, zstd staged) slipped
through and would serve mislabeled bytes, breaking the narinfo
FileHash/FileSize on the Nix client. ncps has no NAR compressor, so the
only cross-compression transform it can do is decompression; any other
non-exact compressed request must 404 and fall back upstream.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
downloadLockFree returned false on a TryLock error, which let a
lock-held assertion pass even when the locker backend is unhealthy,
hiding regressions. Surface the error as a test failure via assert
(goroutine-safe for the assert.Eventually/assert.Never poll loops, where
FailNow must not be called) by threading t into the helper.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@kalbasit
kalbasit enabled auto-merge (squash) June 9, 2026 04:28
@kalbasit
kalbasit merged commit 14e9cd2 into main Jun 9, 2026
37 checks passed
@kalbasit
kalbasit deleted the fix-cdc-staging-lock-lifecycle branch June 9, 2026 04:33
kalbasit added a commit that referenced this pull request Jun 10, 2026
Holding the download lock through chunking (#1379) was the lock-lifetime
groundwork, but the read path still short-circuited the UNCOMPRESSED .nar
request — the only request clients make once eager-CDC narinfos advertise
Compression: none — directly to progressive chunk serving. It never
contended, so in-flight staging never engaged and the fragile progressive
reassembly it was meant to supersede remained the path taken. A new e2e
proved it: the chunking-window cross-pod read served via progressive
chunks with zero contention and zero staging.

Two read-path sites are fixed, both gated on InflightStagingEnabled():

- GetNar routing (cache.go:~1320): an uncompressed actively-chunking
  cross-pod read now falls through to download coordination (via the new
  shouldCoordinateInflight predicate) so it records a staging request and
  serves from staging, instead of serving directly from chunks.
- pollForDownloadOrTakeOver state (D) (cache.go:~6815): when staging is
  active it now waits, bounded (maxStagingWaitTicks), for staging parts to
  appear so the staging serve wins, before falling back to progressive
  chunks (the safety net for a stalled/errored producer).

With staging disabled, lazy CDC, single-replica/same-pod, and finished
NARs, behavior is unchanged.

Also flips the staging-contention e2e chunking window to assert staging
activation (with a bounded clean-restart retry, per review), corrects the
CHANGELOG, and syncs the unified-e2e-harness + inflight-nar-staging specs.

Proven: pkg/cache -race green; staging-contention e2e activates staging in
BOTH windows across two runs (chunking-window race 143s -> 4.5s as staging
replaces progressive reassembly).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
kalbasit added a commit that referenced this pull request Jun 10, 2026
…#1386)

## Summary

The `staging-contention` e2e's chunking window surfaced a real ncps gap:
in-flight NAR staging — documented (#1355/#1374/#1375/#1379, CHANGELOG)
as serving cross-pod reads during the eager-CDC chunking window and
*"superseding the fragile progressive-chunk reassembly"* — **never
actually engaged** for the **uncompressed `.nar`** request, which (since
predictive-`none`, #1380) is the *only* request clients make in that
window. The cross-pod reader served progressive chunks with zero
contention and zero staging. #1379 itself flagged this as unit-verified
but with "no green end-to-end run yet."

This PR closes the gap (ncps fix), then makes the e2e assert the
now-correct behavior.

### Root cause — two read-path sites

- **`GetNar` routing (`cache.go:~1320`):** the fall-through to download
coordination (the only path that records a staging request) was gated
`Compression != none`, so the uncompressed read short-circuited to
progressive chunk serving and never contended.
- **`pollForDownloadOrTakeOver` state (D) (`cache.go:~6815`):** even
once coordinating, an actively-chunking NAR with no staging parts *yet*
immediately returned "served-by-peer → progressive," pre-empting staging
on an early tick.

### Fix (both gated on `InflightStagingEnabled()`)

- Route uncompressed actively-chunking cross-pod reads through
coordination (new `shouldCoordinateInflight` predicate) so they record a
staging request and serve from staging.
- State (D) now waits, bounded (`maxStagingWaitTicks`), for staging
parts so the staging serve wins, before falling back to progressive
chunks (safety net for a stalled producer).
- Unchanged for: staging disabled, lazy CDC, single-replica/same-pod,
finished NARs.

### Harness + docs

- `staging-contention` chunking window now asserts **staging
activation** (with a bounded clean-restart retry — addresses the earlier
CodeRabbit review), reverting the interim progressive-chunk assertion.
- Corrected the CHANGELOG (the prior entry described
intended-but-unverified behavior) and synced the `inflight-nar-staging`
+ `unified-e2e-harness` specs.

## Verification

- [x] `go test -race ./pkg/cache/` green; full `task test` green — no
regression
- [x] New `pkg/cache` internal tests (red→green) for both sites + the
staging-disabled / stalled-producer guards
- [x] `task test:e2e ... staging-contention`: **both** windows activate
in-flight staging, twice (determinism). Chunking-window race **143s →
4.5s** as staging replaces progressive reassembly.
- [x] `task fmt` / `task lint` clean; `openspec validate --all` 41/0

> Note: the first commit on this branch was the interim harness-only
change; this PR's net diff is the ncps fix + the staging-activation
assertion.

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

go Pull requests that update go code size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

CDC: serve whole NAR from shared storage during chunking (+ GC after grace) instead of progressive chunk stream

2 participants