Repository navigation
fix(cache): hold the NAR download lock through the eager-CDC chunking window - #1379
Conversation
… 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]>
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]>
|
This change is part of the following stack: Change managed by git-spice. |
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (3)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughSummary by CodeRabbit
WalkthroughThis 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. ChangesCDC Chunking Lock Lifecycle & In-Flight Staging Coordination
Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 minutes Possibly related PRs
Suggested labels
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 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.
|
Related Knowledge 1 document with suggested updates is ready for review. kalbasit's Space NAR File Download and StreamingView 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.
|
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/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
📒 Files selected for processing (14)
CHANGELOG.mdopenspec/changes/archive/2026-06-09-fix-cdc-staging-lock-lifecycle/.openspec.yamlopenspec/changes/archive/2026-06-09-fix-cdc-staging-lock-lifecycle/design.mdopenspec/changes/archive/2026-06-09-fix-cdc-staging-lock-lifecycle/proposal.mdopenspec/changes/archive/2026-06-09-fix-cdc-staging-lock-lifecycle/specs/cdc-chunking/spec.mdopenspec/changes/archive/2026-06-09-fix-cdc-staging-lock-lifecycle/specs/inflight-nar-staging/spec.mdopenspec/changes/archive/2026-06-09-fix-cdc-staging-lock-lifecycle/tasks.mdopenspec/specs/cdc-chunking/spec.mdopenspec/specs/inflight-nar-staging/spec.mdpkg/cache/cache.gopkg/cache/coordinate_download_lock_lifetime_internal_test.gopkg/cache/inflight_staging_chunking_window_internal_test.gopkg/cache/inflight_staging_reader.gopkg/cache/inflight_staging_reader_internal_test.go
…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]>
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]>
…#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]>
Summary
ds.done, notds.storedwhich 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..nar) cross-pod request during chunking, the complete NAR is served from in-flight staging — more robust than the fragile progressive-chunk reassembly..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 narinfoFileHash/FileSize) —serveNarFromStagingnow 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 asxz.The producer + temp file already survive the chunking window (
waitForStagingRequestpolls untilds.done; the temp is removed only afterds.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
nonefor CDC NARs so.nar.xzis 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