Repository navigation
fix(cache): engage in-flight staging under real contention - #1374
Conversation
|
This change is part of the following stack: Change managed by git-spice. |
|
Warning Review limit reached
More reviews will be available in 42 minutes and 30 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)
📝 WalkthroughWalkthroughReduce stagingActivationPollInterval from 1s to 200ms and make produceStagingParts treat a missing temp file as a clean no-op; add spec/design/docs, a unit test validating the no-op, and e2e harness updates (larger default package, upstream override, URL redaction, clearer failure hint). ChangesInflight NAR Staging Race Fix
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~22 minutes Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Comment |
|
Documentation Updates 1 document(s) were updated by changes in this PR: NAR File Download and StreamingView Changes@@ -83,9 +83,9 @@
When `InflightStagingEnabled()` is true and a distributed locker is configured, the holder pod (the pod that wins the download lock and initiates the upstream NAR download) launches a background staging producer via `stageInflightNar()` to make in-flight bytes available to other pods in the cluster. This addresses the cross-pod coordination problem: once a holder begins downloading a NAR, other pods requesting the same NAR cannot serve the same-pod temp-file streaming path and must wait for the download to complete. The in-flight staging mechanism allows cross-pod readers to serve a complete NAR during the holder's download without waiting.
-**Activation mechanism**: The staging producer polls `staging_state` on a coarse interval (1 second, `stagingActivationPollInterval`) looking for a cross-pod waiter's "requested" status. It remains dormant until a request appears, so single-reader downloads have zero overhead—no staging occurs unless a waiter appears.
-
-**Part production process**: Once activated, `produceStagingParts()` tails the holder's temp file from offset zero using `fileAvailableReader`, which naturally backfills already-written bytes and appends new bytes as they arrive. It writes fixed-size part-objects to shared storage (default 8 MiB parts, configurable via `--cache-inflight-staging-part-size` or `defaultInflightStagingPartSize` constant). The use of `fileAvailableReader` ensures the staging producer blocks until bytes are available in the temp file and returns `io.EOF` once `ds.finalSize` is reached, allowing the staging producer to seamlessly handle both the backfill and append phases.
+**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.
**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.
|
There was a problem hiding this comment.
Code Review
This pull request resolves a race condition and activation delay in the in-flight NAR staging feature. It shortens the staging activation poll interval to 200ms and ensures that if a download completes before staging begins, the producer gracefully no-ops instead of logging a warning error. Additionally, the end-to-end test script is updated to use a larger default package and support upstream overrides. The review feedback suggests minor improvements: using os.ErrNotExist to avoid an extra import, simplifying the unit test's non-existent file setup, and adding a warning log in the Python script for partially configured upstream environment variables.
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.
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 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 `@dev-scripts/test-inflight-staging-contention-e2e.py`:
- Around line 158-161: The current logic reads NCPS_E2E_UPSTREAM_URL into
upstream_url and NCPS_E2E_UPSTREAM_KEY into upstream_key and silently ignores a
partial override; update the block that builds args (where upstream_url,
upstream_key, and args are used) to validate both env vars together and fail
fast when only one is present: if exactly one of upstream_url or upstream_key is
set, print/log a clear error and exit (raise SystemExit) so the script fails
deterministically; otherwise, when both are set, append ["--cache-url",
upstream_url, "--cache-public-key", upstream_key] to args as before.
- Around line 164-165: The log builds a string that includes upstream_url
verbatim (see the f-string using variables upstream_url and upstream_key) which
can leak secrets; instead parse and sanitize upstream_url before including it in
the logged string — remove userinfo (username:password@) and strip or redact the
query/component containing credentials, then use the sanitized value in the
f-string (or replace with a fixed placeholder like "<redacted_upstream>") when
constructing the message that includes "upstream={...}". Ensure the sanitization
logic is applied where the f-string is composed so only non-sensitive parts are
logged.
🪄 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: eba78154-79cc-4100-80ba-25629174ffdb
📒 Files selected for processing (9)
dev-scripts/test-inflight-staging-contention-e2e.pyopenspec/changes/archive/2026-06-08-fix-inflight-staging-producer-temp-race/.openspec.yamlopenspec/changes/archive/2026-06-08-fix-inflight-staging-producer-temp-race/design.mdopenspec/changes/archive/2026-06-08-fix-inflight-staging-producer-temp-race/proposal.mdopenspec/changes/archive/2026-06-08-fix-inflight-staging-producer-temp-race/specs/inflight-nar-staging/spec.mdopenspec/changes/archive/2026-06-08-fix-inflight-staging-producer-temp-race/tasks.mdopenspec/specs/inflight-nar-staging/spec.mdpkg/cache/inflight_staging.gopkg/cache/inflight_staging_producer_internal_test.go
Address review feedback: - Use os.ErrNotExist instead of fs.ErrNotExist in produceStagingParts, dropping the io/fs import (os is already imported). (threads PRRT_kwDONV6tZs6H_VzW, _Vze) - Simplify the no-op test: point ds.assetPath at a never-created path under the temp dir instead of creating then deleting a temp file. (thread PRRT_kwDONV6tZs6H_Vzi) - Contention driver: warn loudly when only one of NCPS_E2E_UPSTREAM_URL / NCPS_E2E_UPSTREAM_KEY is set (partial override is silently ignored), and redact any userinfo/query from the upstream URL before logging it. (threads PRRT_kwDONV6tZs6H_Vzl, _X7W, _X7k)
02fa39f to
6005f3e
Compare
There was a problem hiding this comment.
♻️ Duplicate comments (1)
dev-scripts/test-inflight-staging-contention-e2e.py (1)
175-183:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winFail fast on partial upstream override instead of warning and continuing.
If only one of
NCPS_E2E_UPSTREAM_URL/NCPS_E2E_UPSTREAM_KEYis set, continuing with defaults can mask config mistakes and produce non-deterministic runs. Exit immediately (raise SystemExit(...)) when the pair is incomplete.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@dev-scripts/test-inflight-staging-contention-e2e.py` around lines 175 - 183, The current check that warns when only one of upstream_url/upstream_key is set should instead fail fast: inside the bool(upstream_url) != bool(upstream_key) branch (where log(...) and Y are used), raise SystemExit with a clear error message describing that both NCPS_E2E_UPSTREAM_URL and NCPS_E2E_UPSTREAM_KEY must be provided together; remove or replace the existing log-only behavior so the script exits immediately on a partial upstream override.
🤖 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.
Duplicate comments:
In `@dev-scripts/test-inflight-staging-contention-e2e.py`:
- Around line 175-183: The current check that warns when only one of
upstream_url/upstream_key is set should instead fail fast: inside the
bool(upstream_url) != bool(upstream_key) branch (where log(...) and Y are used),
raise SystemExit with a clear error message describing that both
NCPS_E2E_UPSTREAM_URL and NCPS_E2E_UPSTREAM_KEY must be provided together;
remove or replace the existing log-only behavior so the script exits immediately
on a partial upstream override.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 3ee1d8ff-b046-4422-9029-d92b9927e492
📒 Files selected for processing (9)
dev-scripts/test-inflight-staging-contention-e2e.pyopenspec/changes/archive/2026-06-08-fix-inflight-staging-producer-temp-race/.openspec.yamlopenspec/changes/archive/2026-06-08-fix-inflight-staging-producer-temp-race/design.mdopenspec/changes/archive/2026-06-08-fix-inflight-staging-producer-temp-race/proposal.mdopenspec/changes/archive/2026-06-08-fix-inflight-staging-producer-temp-race/specs/inflight-nar-staging/spec.mdopenspec/changes/archive/2026-06-08-fix-inflight-staging-producer-temp-race/tasks.mdopenspec/specs/inflight-nar-staging/spec.mdpkg/cache/inflight_staging.gopkg/cache/inflight_staging_producer_internal_test.go
✅ Files skipped from review due to trivial changes (4)
- openspec/changes/archive/2026-06-08-fix-inflight-staging-producer-temp-race/proposal.md
- openspec/changes/archive/2026-06-08-fix-inflight-staging-producer-temp-race/design.md
- openspec/changes/archive/2026-06-08-fix-inflight-staging-producer-temp-race/.openspec.yaml
- openspec/changes/archive/2026-06-08-fix-inflight-staging-producer-temp-race/tasks.md
🚧 Files skipped from review as they are similar to previous changes (2)
- openspec/specs/inflight-nar-staging/spec.md
- pkg/cache/inflight_staging_producer_internal_test.go
The contention e2e (test-inflight-staging-contention) proved in-flight NAR staging never served on real downloads, due to two coupled defects in the staging holder path: 1. The producer opened ds.assetPath unconditionally. When a cross-pod waiter's staging request was observed only at download completion (the <-ds.done branch of waitForStagingRequest), the holder's temp file had already been removed by the post-completion cleanup, so the open failed with ENOENT and the producer logged a WARN error instead of staging anything. produceStagingParts now treats fs.ErrNotExist as a clean no-op: the temp file is only ever removed after the download completes and the NAR is committed to shared storage, so cross-pod waiters serve the finished NAR from storage. Any other open error still propagates. 2. stagingActivationPollInterval was 1s, but staging requests are recorded only by cross-pod waiters (markStagingRequested is called solely from pollForDownloadOrTakeOver) and the holder learns of them only by this poll. A download finishing within one tick never had staging engage. Lowered to 200ms to match the waiter's own pollInterval so the holder observes the request while the download is still in flight. No in-process signal is possible: same-node waiters share the downloadState and never record a request. Proven green via the e2e in the download window across local and s3 (gcc-unwrapped, ~277MB NAR): staging activates on the non-holder replica and every reader gets a complete, byte-identical NAR, with no producer WARN. The chunking window surfaced a separate CDC serve-route 404 (the non-downloading replica 404s the NAR), distinct from this fix and deferred to its own change. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Address review feedback: - Use os.ErrNotExist instead of fs.ErrNotExist in produceStagingParts, dropping the io/fs import (os is already imported). (threads PRRT_kwDONV6tZs6H_VzW, _Vze) - Simplify the no-op test: point ds.assetPath at a never-created path under the temp dir instead of creating then deleting a temp file. (thread PRRT_kwDONV6tZs6H_Vzi) - Contention driver: warn loudly when only one of NCPS_E2E_UPSTREAM_URL / NCPS_E2E_UPSTREAM_KEY is set (partial override is silently ignored), and redact any userinfo/query from the upstream URL before logging it. (threads PRRT_kwDONV6tZs6H_Vzl, _X7W, _X7k)
6005f3e to
9b3c140
Compare
…#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
produceStagingPartsnow treatsfs.ErrNotExistas a clean no-op (the NAR is already committed to storage; waiters serve from there).stagingActivationPollIntervallowered 1s → 200ms to match the waiter's cadence, so the holder observes a request while the download is still in flight.Proven green via the contention e2e in the download window across local and s3 (staging activates on the non-holder; byte-identical NARs; no producer WARN).
Test plan
task fmt/task lint/task test(race) passpkg/cacheunit test (red→green)