Skip to content

fix(cache): route a contended CDC loser to staging, not a 404 - #1375

Merged
kalbasit merged 2 commits into
mainfrom
fix-cdc-window-nonholder-404
Jun 9, 2026
Merged

kalbasit merged 2 commits into
mainfrom
fix-cdc-window-nonholder-404

Conversation

@kalbasit

@kalbasit kalbasit commented Jun 8, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • Under eager CDC, a non-holder replica 404s a compressed NAR request: the download-coordination poll loop early-returned a "served-by-peer" state for an actively-chunking NAR because isServable conflates "finished" with "actively chunking", routing to chunk serving (which can't produce a compressed variant from decompressed chunks).
  • Split a finished-only predicate hasFinishedNar (whole-file-in-store OR total_chunks>0) out of isServable, threaded as hasFinishedAsset through coordinateDownload + pollForDownloadOrTakeOver, and restructured the per-tick decision into four states (dead-holder→takeover[D5] / finished→serve / chunking+staging→staging / chunking+no-staging→progressive).

Status: a correct, regression-free prerequisite toward closing the chunking-window cross-pod 404 (#1289). It does NOT fully close that 404 on its own — see the stack head (#1376) for the remaining root cause (a CDC lock-lifecycle design mismatch).

Test plan

  • task fmt / task lint / task test (race) pass — no regression to progressive-chunk/takeover paths
  • New hasFinishedNar unit test

@kalbasit

kalbasit commented Jun 8, 2026 •

Copy link
Copy Markdown
Owner Author

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jun 8, 2026
@dosubot dosubot Bot added bug Something isn't working go Pull requests that update go code labels Jun 8, 2026
@coderabbitai

coderabbitai Bot commented Jun 8, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

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

More reviews will be available in 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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

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

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 226ce233-8a8b-46f1-883c-e7ad1a32bf92

📥 Commits

Reviewing files that changed from the base of the PR and between 6903097 and 32f3f06.

📒 Files selected for processing (9)
  • openspec/changes/archive/2026-06-08-fix-cdc-window-nonholder-404/.openspec.yaml
  • openspec/changes/archive/2026-06-08-fix-cdc-window-nonholder-404/design.md
  • openspec/changes/archive/2026-06-08-fix-cdc-window-nonholder-404/proposal.md
  • openspec/changes/archive/2026-06-08-fix-cdc-window-nonholder-404/specs/inflight-nar-staging/spec.md
  • openspec/changes/archive/2026-06-08-fix-cdc-window-nonholder-404/tasks.md
  • openspec/specs/inflight-nar-staging/spec.md
  • pkg/cache/cache.go
  • pkg/cache/has_finished_nar_internal_test.go
  • pkg/cache/inflight_staging_takeover_internal_test.go
📝 Walkthrough

Walkthrough

This PR fixes a CDC-related HTTP 404 that occurs when non-holder replicas are routed during active chunking. It introduces a hasFinishedNar predicate to distinguish fully-materialized NARs from actively-chunking states, restructuring the coordination polling loop to serve finished assets directly while preserving staging and progressive-streaming paths for in-flight conditions.

Changes

CDC Lock-Contention 404 Fix

Layer / File(s) Summary
Problem Statement & Requirements
openspec/changes/archive/2026-06-08-fix-cdc-window-nonholder-404/{.openspec.yaml,design.md,proposal.md,specs/inflight-nar-staging/spec.md,tasks.md}, openspec/specs/inflight-nar-staging/spec.md
Design document and archived proposal describe the CDC lock-losing 404 for nar.xz during chunking, define goals (byte-identical cross-pod serving under contention), and restructure tick coordination by splitting served-by-peer into distinct states. Updated specifications clarify that cross-pod replicas must serve complete NARs from staging in all CDC modes, with transcoding and staging preference over chunk routing to avoid 404.
Finished Asset Predicate Implementation
pkg/cache/cache.go, pkg/cache/has_finished_nar_internal_test.go
Adds hasFinishedNar helper that returns true for whole-file or fully-chunked NARs (total_chunks > 0) and false for actively-chunking states (total_chunks == 0). Two unit tests validate that actively-chunking NARs are excluded from the finished state even when servable, and that fully-chunked NARs are counted as finished.
Coordination Pipeline Refactoring
pkg/cache/cache.go
Threads hasFinishedAsset parameter through coordinateDownload and pollForDownloadOrTakeOver. The polling loop's first check switches from hasAsset to hasFinishedAsset, ensuring only fully-finished NARs trigger peer-served completion; in-flight states fall through to staging or progressive-streaming paths. prePullNarInfo refactors to use named narInfoPresent predicate.
Existing Test Adaptation
pkg/cache/inflight_staging_takeover_internal_test.go
Updates two existing coordination tests to match the new hasFinishedAsset parameter signature in pollForDownloadOrTakeOver calls.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • kalbasit/ncps#1357: Modifies pollForDownloadOrTakeOver decision flow between takeover and staging behavior via coordination predicates.
  • kalbasit/ncps#1354: Refactors the same coordination and polling paths to distinguish "finished vs actively-chunking" routing for staging-based serving.
  • kalbasit/ncps#1355: Overlaps in staging-vs-progressive chunk serving behavior during eager-CDC chunking window by adding "prefer staging over progressive chunks" for total_chunks == 0.

Suggested labels

bug, go, size:M, merge-stack

Poem

🐰 A chunking-window lock fight taught us well—
When holders finish and losers must tell:
"Is this done done, or still taking its turn?"
We split the decision and let staging learn.
No more 404s in the CDC stream! 🎉

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The PR title clearly and specifically identifies the main fix: routing a contended CDC cache loser away from a 404 error toward the staging path.
Description check ✅ Passed The PR description is directly related to the changeset, explaining the root cause of the 404 issue and the fix applied via the new hasFinishedNar predicate and restructured polling logic.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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


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

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request 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.

Comment thread pkg/cache/cache.go Resolved
Comment thread pkg/cache/cache.go Resolved
Comment thread pkg/cache/cache.go Resolved
Comment thread pkg/cache/cache.go Resolved
Comment thread pkg/cache/cache.go Resolved
Comment thread pkg/cache/cache.go Resolved
Comment thread pkg/cache/cache.go Resolved
@kalbasit
kalbasit force-pushed the fix-inflight-staging-producer-temp-race branch from 02fa39f to 6005f3e Compare June 9, 2026 00:10
kalbasit added a commit that referenced this pull request Jun 9, 2026
#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.
@kalbasit
kalbasit force-pushed the fix-cdc-window-nonholder-404 branch from 6903097 to df1060c Compare June 9, 2026 00:10
@kalbasit
kalbasit force-pushed the fix-inflight-staging-producer-temp-race branch from 6005f3e to 9b3c140 Compare June 9, 2026 00:16
kalbasit added a commit that referenced this pull request Jun 9, 2026
#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.
@kalbasit
kalbasit force-pushed the fix-cdc-window-nonholder-404 branch from df1060c to c16367d Compare June 9, 2026 00:16
Base automatically changed from fix-inflight-staging-producer-temp-race to main June 9, 2026 00:26
kalbasit and others added 2 commits June 9, 2026 00:26
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.
@kalbasit
kalbasit force-pushed the fix-cdc-window-nonholder-404 branch from c16367d to 32f3f06 Compare June 9, 2026 00:26
@kalbasit
kalbasit enabled auto-merge (squash) June 9, 2026 00:26
@kalbasit
kalbasit merged commit 940021c into main Jun 9, 2026
37 checks passed
@kalbasit
kalbasit deleted the fix-cdc-window-nonholder-404 branch June 9, 2026 00:35
@dosubot

dosubot Bot commented Jun 9, 2026

Copy link
Copy Markdown

Documentation Updates

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

NAR File Download and Streaming
View 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.
 

How did I do? Any feedback?  Join Discord

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

bug Something isn't working 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.

1 participant