Repository navigation
fix(cache): engage in-flight staging in the eager-CDC chunking window - #1386
Conversation
The chunking-window run always FAILed asserting in-flight staging activates. Live investigation showed eager-CDC cross-pod reads of the uncompressed .nar are served progressively from the holder's committed chunks (#1289), never via in-flight staging — which is a download-window mechanism. The test asserted the wrong mechanism, and it raced readers only after the narinfo prime had already fully materialized (downloaded+chunked) the NAR. Split the scenario by window: - download (CDC off): keep asserting in-flight staging activates. - chunking (eager CDC): gate the race on an observed in-flight state (nar_files row with total_chunks == 0, or no row yet) so readers overlap the holder's production, then assert every reader gets a byte-identical NAR AND the NAR is chunked by exactly one replica — i.e. cross-pod readers served from the shared chunk set with no re-download or re-chunk. Adds unit tests for the in-flight classification and URL-hash helpers; updates the unified-e2e-harness spec and README. Verified locally: both windows PASS across two runs. Harness-only; no ncps production change. 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 (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughSummary by CodeRabbit
WalkthroughSplit the staging-contention e2e into two separately-scored windows and updated cache routing: download window (CDC off) asserts staging activation; chunking window (eager CDC) gates on in-flight state and requires byte-identical NAR delivery. Cache now routes uncompressed active-chunk reads to download coordination when staging is enabled and waits boundedly for staging parts. ChangesStaging-contention E2E + Cache Coordination
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 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. ✨ Finishing Touches📝 Generate docstrings
Warning Review ran into problems🔥 ProblemsStopped waiting for pipeline failures after 30000ms. One of your pipelines takes longer than our 30000ms fetch window to run, so review may not consider pipeline-failure results for inline comments if any failures occurred after the fetch window. Increase the timeout if you want to wait longer or run a Comment |
There was a problem hiding this comment.
Code Review
This pull request refactors the staging-contention end-to-end test scenario by splitting it into two correctly-scoped windows: a download window (CDC off) that asserts in-flight staging activation, and a chunking window (eager CDC) that asserts progressive chunk-serving from a single replica with no re-download or re-chunk. It introduces helper functions to gate the chunking-window race on an observed in-flight state, along with corresponding unit tests and updated specifications. The review feedback suggests removing an outdated comment block regarding bounded retries and renaming the hash parameter in helper functions to avoid shadowing the Python built-in hash() function.
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: 1
🧹 Nitpick comments (1)
nix/e2e-tests/src/phases/staging_contention.py (1)
91-119: ⚡ Quick winRename
hashtonar_hashin both helpers.Lines 91 and 108 shadow Python's builtin
hash, and Ruff is already flagging A002 here.nar_hashis clearer at the query/call sites too.Small cleanup
-def _inflight_state(db, hash: str) -> str: +def _inflight_state(db, nar_hash: str) -> str: ... - rows = db.query("SELECT total_chunks FROM nar_files WHERE hash = ?", (hash,)) + rows = db.query("SELECT total_chunks FROM nar_files WHERE hash = ?", (nar_hash,)) ... -def _await_inflight(db, hash) -> str: +def _await_inflight(db, nar_hash: str) -> str: ... - return "missed" if _inflight_state(db, hash) == "done" else "inflight" + return "missed" if _inflight_state(db, nar_hash) == "done" else "inflight"🤖 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 `@nix/e2e-tests/src/phases/staging_contention.py` around lines 91 - 119, Rename the parameter named "hash" to "nar_hash" in both helper functions _inflight_state and _await_inflight to avoid shadowing the built-in hash and to improve clarity; update all uses inside each function (the DB query call in _inflight_state and the call to _inflight_state inside _await_inflight) and any external call sites that pass the argument so they use the new nar_hash identifier.Source: Linters/SAST tools
🤖 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 `@nix/e2e-tests/src/phases/staging_contention.py`:
- Around line 229-236: The current handling of _await_inflight(deployment.db(),
h) == "missed" merely logs and continues, which lets later digest and
migration:{h} checks falsely validate a fully-materialized chunk set; modify the
flow around _await_inflight in staging_contention.py to perform a bounded retry
loop (e.g., up to N attempts) when it returns "missed", sleeping/reinitializing
as appropriate between attempts, and if all N attempts still return "missed"
raise/exit with an explicit failure; apply the same retry/fail logic to the
analogous block around lines handling the second _await_inflight call (the
257-262 region) so both places retry a limited number of times before failing.
---
Nitpick comments:
In `@nix/e2e-tests/src/phases/staging_contention.py`:
- Around line 91-119: Rename the parameter named "hash" to "nar_hash" in both
helper functions _inflight_state and _await_inflight to avoid shadowing the
built-in hash and to improve clarity; update all uses inside each function (the
DB query call in _inflight_state and the call to _inflight_state inside
_await_inflight) and any external call sites that pass the argument so they use
the new nar_hash identifier.
🪄 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: cac340b8-6baf-40b1-906d-ae751b63422e
📒 Files selected for processing (9)
nix/e2e-tests/README.mdnix/e2e-tests/src/phases/staging_contention.pynix/e2e-tests/tests/test_staging_contention.pyopenspec/changes/archive/2026-06-09-fix-staging-contention-e2e-race/.openspec.yamlopenspec/changes/archive/2026-06-09-fix-staging-contention-e2e-race/design.mdopenspec/changes/archive/2026-06-09-fix-staging-contention-e2e-race/proposal.mdopenspec/changes/archive/2026-06-09-fix-staging-contention-e2e-race/specs/unified-e2e-harness/spec.mdopenspec/changes/archive/2026-06-09-fix-staging-contention-e2e-race/tasks.mdopenspec/specs/unified-e2e-harness/spec.md
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]>
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/engage_staging_uncompressed_internal_test.go`:
- Around line 87-98: The call to markStagingRequested currently ignores its
error; change the goroutine to capture its returned error from
c.markStagingRequested(ctx, hash) and, if non-nil, send that error on the staged
channel and return (just like the checks for c.advanceStagingParts and
c.markStagingComplete do). Locate the anonymous goroutine that calls
markStagingRequested, advanceStagingParts, and markStagingComplete and add the
error check for markStagingRequested (using variables c, ctx, hash, staged) to
propagate failures to staged.
🪄 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: ecd4d386-f4a1-4f10-a440-83f3265ed120
📒 Files selected for processing (13)
CHANGELOG.mdnix/e2e-tests/README.mdnix/e2e-tests/src/phases/staging_contention.pyopenspec/changes/archive/2026-06-09-engage-staging-eager-cdc-uncompressed/.openspec.yamlopenspec/changes/archive/2026-06-09-engage-staging-eager-cdc-uncompressed/design.mdopenspec/changes/archive/2026-06-09-engage-staging-eager-cdc-uncompressed/proposal.mdopenspec/changes/archive/2026-06-09-engage-staging-eager-cdc-uncompressed/specs/inflight-nar-staging/spec.mdopenspec/changes/archive/2026-06-09-engage-staging-eager-cdc-uncompressed/specs/unified-e2e-harness/spec.mdopenspec/changes/archive/2026-06-09-engage-staging-eager-cdc-uncompressed/tasks.mdopenspec/specs/inflight-nar-staging/spec.mdopenspec/specs/unified-e2e-harness/spec.mdpkg/cache/cache.gopkg/cache/engage_staging_uncompressed_internal_test.go
✅ Files skipped from review due to trivial changes (4)
- openspec/changes/archive/2026-06-09-engage-staging-eager-cdc-uncompressed/.openspec.yaml
- openspec/changes/archive/2026-06-09-engage-staging-eager-cdc-uncompressed/proposal.md
- CHANGELOG.md
- openspec/changes/archive/2026-06-09-engage-staging-eager-cdc-uncompressed/design.md
🚧 Files skipped from review as they are similar to previous changes (1)
- openspec/specs/unified-e2e-harness/spec.md
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request ensures that eager-CDC uncompressed cross-pod reads correctly engage in-flight staging instead of short-circuiting to progressive chunk serving. The changes route uncompressed actively-chunking reads to download coordination when staging is enabled, and introduce a bounded wait in the poll loop for staging parts to appear. Additionally, the staging-contention e2e test is updated to assert staging activation in both windows with bounded retries. The reviewer suggested a valuable optimization to immediately restart and retry the e2e test if the in-flight window is missed, rather than executing the slow concurrent race.
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.
Address CodeRabbit review: the staging-wait test's producer goroutine ignored markStagingRequested's error, which could mask a setup failure behind a misleading staging assertion. Propagate it to the staged channel like the other staging calls. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request ensures that eager-CDC uncompressed cross-pod reads correctly engage in-flight staging. It updates the read path to route uncompressed actively-chunking reads through download coordination when staging is enabled, and introduces a bounded wait in the polling loop for staging parts to appear before falling back to progressive chunks. Additionally, the staging-contention end-to-end test harness was updated to assert staging activation in both windows with bounded retries, supported by new unit tests and updated specifications. The feedback suggests optimizing the test harness by skipping the client race and immediately retrying if the in-flight window is already closed, which would save time and resources.
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.
Address Gemini review: when the in-flight window is already closed (_await_inflight == "missed"), racing is guaranteed not to engage staging, so skip the slow/heavy reader race and clean-restart + retry immediately instead of wasting it on a discarded result. Co-Authored-By: Claude Opus 4.8 <[email protected]>
📄 Knowledge review✏️ Documentation updates1 page was updated by changes in this PR.
📝 NAR File Download and Streaming — changes@@ -85,7 +85,7 @@
**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.
-**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).
+**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. When in-flight staging is enabled, both compressed and uncompressed cross-pod NAR requests entering during the chunking window are routed through download coordination (rather than short-circuiting to chunk-based serving). The waiter waits, bounded, for the holder's staging producer to make parts available and then serves from staging, with progressive chunk streaming remaining the fallback only when staging is disabled or staging parts do not materialize within the wait bound (e.g., a stalled or errored producer).
**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.
@@ -111,11 +111,11 @@
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. Under eager CDC, clients request `.nar` due to the predictive narinfo normalization (see "GetNarInfo Narinfo Normalization"), avoiding compressed-variant requests that would return not-found.
-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).
+4. **Actively-chunking without staging**: When the holder is alive and actively chunking, but no staging parts are available yet, the waiter waits for a bounded number of ticks (15 ticks, 3 seconds at 200ms intervals) to allow the holder's staging producer to publish in-flight parts before falling back to progressive chunk streaming. This bounded wait ensures staging wins the common eager-CDC chunking-window case instead of being pre-empted by an early tick. Once the bound is reached (indicating a stalled or errored producer) or when staging is disabled, returns a completed "served-by-peer" state so `GetNar` routes to progressive chunk streaming (`streamProgressiveChunks`). Progressive serving remains the safety net for stalled producers and 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 cross-pod request handling**: Under eager CDC, the predictive narinfo normalization (documented in "GetNarInfo Narinfo Normalization") steers cross-pod readers to request the uncompressed `.nar` variant during the chunking window. The uncompressed request is satisfied from staging (or progressive chunks) per the existing in-flight staging mechanism. The compressed-variant upstream fallback (e.g., `.nar.xz` returning not-found) remains only as a defensive backstop for directly-constructed compressed requests, such as a client holding a stale `xz` narinfo. Under eager CDC, the common cross-pod path does not exercise the compressed fallback because clients request `.nar`.
+**Eager-CDC cross-pod request handling**: Under eager CDC, the predictive narinfo normalization (documented in "GetNarInfo Narinfo Normalization") steers cross-pod readers to request the uncompressed `.nar` variant during the chunking window. When in-flight staging is enabled, the uncompressed request enters download coordination, contends for the holder's download lock, records a staging request, and serves from in-flight staging once parts are available—avoiding the fragile progressive chunk reassembly. With staging disabled, the uncompressed request serves progressively from chunks. The compressed-variant upstream fallback (e.g., `.nar.xz` returning not-found) remains only as a defensive backstop for directly-constructed compressed requests, such as a client holding a stale `xz` narinfo. Under eager CDC, the common cross-pod path does not exercise the compressed fallback because clients request `.nar`.
**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.
|
Summary
The
staging-contentione2e'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.narrequest, 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
GetNarrouting (cache.go:~1320): the fall-through to download coordination (the only path that records a staging request) was gatedCompression != none, so the uncompressed read short-circuited to progressive chunk serving and never contended.pollForDownloadOrTakeOverstate (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())shouldCoordinateInflightpredicate) so they record a staging request and serve from staging.maxStagingWaitTicks), for staging parts so the staging serve wins, before falling back to progressive chunks (safety net for a stalled producer).Harness + docs
staging-contentionchunking window now asserts staging activation (with a bounded clean-restart retry — addresses the earlier CodeRabbit review), reverting the interim progressive-chunk assertion.inflight-nar-staging+unified-e2e-harnessspecs.Verification
go test -race ./pkg/cache/green; fulltask testgreen — no regressionpkg/cacheinternal tests (red→green) for both sites + the staging-disabled / stalled-producer guardstask test:e2e ... staging-contention: both windows activate in-flight staging, twice (determinism). Chunking-window race 143s → 4.5s as staging replaces progressive reassembly.task fmt/task lintclean;openspec validate --all41/0