Repository navigation
fix(cache): route a contended CDC loser to staging, not a 404 - #1375
Conversation
|
This change is part of the following stack: Change managed by git-spice. |
|
Warning Review limit reached
More reviews will be available in 32 minutes and 47 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 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 configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (9)
📝 WalkthroughWalkthroughThis PR fixes a CDC-related HTTP 404 that occurs when non-holder replicas are routed during active chunking. It introduces a ChangesCDC Lock-Contention 404 Fix
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 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. Comment |
There was a problem hiding this comment.
Code Review
This pull request resolves an issue where lock-losing replicas return HTTP 404 for compressed NAR requests under CDC by distinguishing between finished and actively-chunking states in the download coordination loop. This ensures actively-chunking assets can fall back to in-flight staging or progressive chunk streaming instead of prematurely routing to chunk serving. The review feedback highlights a performance inefficiency in the polling loop, where sequential calls to hasFinishedAsset and hasAsset double the database queries and storage I/O per tick under contention. The reviewer suggests refactoring these checks into a single combined checkAsset function returning both states, providing comprehensive code suggestions across all affected files and tests to address this redundancy.
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.
02fa39f to
6005f3e
Compare
#1375) The coordination poll loop called hasFinishedAsset then hasAsset on every 200ms tick, each repeating HasNarInStore (a storage stat / S3 HEAD) and the nar_file lookup — redundant I/O and DB load under contention. Extract one oracle, narServability(ctx, narURL) (servable, finished, err), and have isServable and hasFinishedNar both delegate to it (preserving the single-source-of-truth that prevents the divergent-check regressions #1255/#1263/#1279/#1290). Collapse coordinateDownload / pollForDownloadOrTakeOver from two predicate closures to one checkAsset(ctx) (servable, finished); the tick now computes both states in a single call. Behavior is unchanged (full -race suite green). Resolves threads PRRT_kwDONV6tZs6H_WfI, _WfM, _WfP, _WfR, _WfW, _Wfa, _Wfc, _Wfn, _Wfo.
6903097 to
df1060c
Compare
6005f3e to
9b3c140
Compare
#1375) The coordination poll loop called hasFinishedAsset then hasAsset on every 200ms tick, each repeating HasNarInStore (a storage stat / S3 HEAD) and the nar_file lookup — redundant I/O and DB load under contention. Extract one oracle, narServability(ctx, narURL) (servable, finished, err), and have isServable and hasFinishedNar both delegate to it (preserving the single-source-of-truth that prevents the divergent-check regressions #1255/#1263/#1279/#1290). Collapse coordinateDownload / pollForDownloadOrTakeOver from two predicate closures to one checkAsset(ctx) (servable, finished); the tick now computes both states in a single call. Behavior is unchanged (full -race suite green). Resolves threads PRRT_kwDONV6tZs6H_WfI, _WfM, _WfP, _WfR, _WfW, _Wfa, _Wfc, _Wfn, _Wfo.
df1060c to
c16367d
Compare
The contention e2e showed that under CDC a lock-losing replica returns HTTP 404 for /nar/<hash>.nar.xz while the holder serves 200. Root cause in the download-coordination poll loop: hasAsset (isServable) returns true for an actively-chunking NAR, so the loser early-returns a "served-by-peer" state and routes to chunk serving, which 404s a compressed request because chunks are stored decompressed. The transcoding in-flight-staging path is never reached. Split a finished-only predicate, hasFinishedNar (whole file in store OR total_chunks > 0), out of isServable, and thread it through coordinateDownload + pollForDownloadOrTakeOver. Restructure the per-tick decision into four states: dead holder (lock acquirable) -> takeover (kept first, preserving the D5 truncated-prefix invariant); finished -> serve; actively-chunking + staging-ready -> serve from staging (transcoding); actively-chunking + no-staging -> progressive chunk streaming (unchanged). isServable is left intact for the progressive path; only the served-by-peer decision now distinguishes finished from in-flight. This is Layer 1 of the fix: when staging parts exist, a contended CDC loser now serves them instead of 404-ing, and the no-staging progressive path is byte-for-byte unchanged (full -race suite green; new hasFinishedNar unit test). It is NOT sufficient on its own: the CDC holder does not yet produce staging parts during chunking, so the user-visible chunking-window 404 persists end-to-end until that is wired (Layer 2, a separate change that owns the chunking-window e2e green). Co-Authored-By: Claude Opus 4.8 <[email protected]>
#1375) The coordination poll loop called hasFinishedAsset then hasAsset on every 200ms tick, each repeating HasNarInStore (a storage stat / S3 HEAD) and the nar_file lookup — redundant I/O and DB load under contention. Extract one oracle, narServability(ctx, narURL) (servable, finished, err), and have isServable and hasFinishedNar both delegate to it (preserving the single-source-of-truth that prevents the divergent-check regressions #1255/#1263/#1279/#1290). Collapse coordinateDownload / pollForDownloadOrTakeOver from two predicate closures to one checkAsset(ctx) (servable, finished); the tick now computes both states in a single call. Behavior is unchanged (full -race suite green). Resolves threads PRRT_kwDONV6tZs6H_WfI, _WfM, _WfP, _WfR, _WfW, _Wfa, _Wfc, _Wfn, _Wfo.
c16367d to
32f3f06
Compare
|
Documentation Updates 1 document(s) were updated by changes in this PR: NAR File Download and StreamingView Changes@@ -101,9 +101,15 @@
**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.
-**Takeover-before-serve ordering**: On each 200ms poll tick, the waiter FIRST attempts to re-acquire the lock (`TryLock`) to detect if the holder has died or failed. If the lock can be acquired (the holder is gone), the waiter takes over as the new download holder. The new holder will discard any partial staging parts left by the dead holder (via `resetStagingForTakeover`) and restart the download from scratch. This prevents serving truncated/incomplete staging parts from a holder that will never complete.
-
-**Part availability detection**: Only if the lock is still held (holder is alive) does the waiter then check `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. This ensures staging parts are only served when the producer is still alive and will complete the download.
+**Four-state per-tick decision**: On each 200ms poll tick, `pollForDownloadOrTakeOver` evaluates four possible routing states in strict priority order:
+
+1. **Takeover-before-serve ordering**: FIRST attempts to re-acquire the lock (`TryLock`) to detect if the holder has died or failed. If the lock can be acquired (the holder is gone), the waiter takes over as the new download holder. The new holder will discard any partial staging parts left by the dead holder (via `resetStagingForTakeover`) and restart the download from scratch. This prevents serving truncated/incomplete staging parts from a holder that will never complete.
+
+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.
+
+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.
|
…#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
isServableconflates "finished" with "actively chunking", routing to chunk serving (which can't produce a compressed variant from decompressed chunks).hasFinishedNar(whole-file-in-store ORtotal_chunks>0) out ofisServable, threaded ashasFinishedAssetthroughcoordinateDownload+pollForDownloadOrTakeOver, and restructured the per-tick decision into four states (dead-holder→takeover[D5] / finished→serve / chunking+staging→staging / chunking+no-staging→progressive).Test plan
task fmt/task lint/task test(race) pass — no regression to progressive-chunk/takeover pathshasFinishedNarunit test