Skip to content

fix(cache): engage in-flight staging in the eager-CDC chunking window - #1386

Merged
kalbasit merged 4 commits into
mainfrom
fix-staging-contention-e2e-race
Jun 10, 2026
Merged

kalbasit merged 4 commits into
mainfrom
fix-staging-contention-e2e-race

Conversation

@kalbasit

@kalbasit kalbasit commented Jun 10, 2026 •

Copy link
Copy Markdown
Owner

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

  • go test -race ./pkg/cache/ green; full task test green — no regression
  • New pkg/cache internal tests (red→green) for both sites + the staging-disabled / stalled-producer guards
  • task 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 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.

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]>
@kalbasit

kalbasit commented Jun 10, 2026 •

Copy link
Copy Markdown
Owner Author

This change is part of the following stack:

Change managed by git-spice.

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jun 10, 2026
@coderabbitai

coderabbitai Bot commented Jun 10, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: adc3bc9b-f5fe-4094-bfbc-ca06a5e8962f

📥 Commits

Reviewing files that changed from the base of the PR and between 3320ec3 and f583247.

📒 Files selected for processing (1)
  • nix/e2e-tests/src/phases/staging_contention.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • nix/e2e-tests/src/phases/staging_contention.py

📝 Walkthrough

Summary by CodeRabbit

  • Bug Fixes

    • Uncompressed cross-pod reads now coordinate for in-flight staging (when enabled) and wait a bounded time for staged parts before falling back to progressive streaming; raced readers now get byte-identical, complete NARs.
  • Tests

    • E2E staging-contention split into download and chunking windows with gating on in-flight state; added unit and cache-path tests for inflight classification, await/retry, hashing, coordination, and poll-loop behavior.
  • Documentation

    • Updated specs, design notes, tasks, and changelog to reflect the revised harness and staging behavior.

Walkthrough

Split 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.

Changes

Staging-contention E2E + Cache Coordination

Layer / File(s) Summary
Specification and archive documents
openspec/..., openspec/changes/archive/2026-06-09-*, CHANGELOG.md
Added and updated openspec archives, design/proposal/tasks, unified-e2e-harness and inflight-nar-staging spec text, and a changelog entry describing the two-window staging-contention requirement and eager-CDC uncompressed staging behavior.
E2E helpers, harness refactor, README & tests
nix/e2e-tests/src/phases/staging_contention.py, nix/e2e-tests/tests/test_staging_contention.py, nix/e2e-tests/README.md
Added _hash_from_nar_url, _inflight_state, _await_inflight, _prime, _assert_race_content, _run_download_window, _run_chunking_window, unit tests for helpers, and README updates documenting download vs chunking windows and gating behavior.
Cache routing and poll-loop changes
pkg/cache/cache.go
Added Cache.shouldCoordinateInflight and updated GetNar to route actively-chunking uncompressed reads into download coordination when in-flight staging is enabled; added a bounded staging-wait in pollForDownloadOrTakeOver to prefer staged parts before falling back to progressive chunks.
Cache unit tests
pkg/cache/engage_staging_uncompressed_internal_test.go
Added tests verifying uncompressed reads require staging to coordinate when staging is enabled, compressed reads always coordinate, that D-state waits for staging parts when appropriate, and that the poll loop falls back within a bounded time when staging stalls.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • kalbasit/ncps#1290: Overlaps changes to pkg/cache/cache.go poll behavior under distributed lock contention.
  • kalbasit/ncps#1355: Overlaps read-path changes to prefer in-flight staging parts during eager-CDC chunking-window.
  • kalbasit/ncps#1353: Implements related in-flight staging producer/serve-from-staging behavior that pairs with these coordination changes.

Suggested labels

bug, go, merge-stack

Poem

🐰 I hopped between windows, two at play,
One for download, one chunking the way.
Waiters contend, staging wakes to serve,
Bytes line up true — no truncated swerve.
Tests hum, changelog gleams — carrot preserve.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 53.85% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main change: engaging in-flight staging in the eager-CDC chunking window, which is the core fix.
Description check ✅ Passed The description is comprehensive and directly related to the changeset, explaining the root causes, fixes, verification steps, and impact on the harness and documentation.
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.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

Warning

Review ran into problems

🔥 Problems

Stopped 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 @coderabbit review after the pipeline has finished.


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 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
nix/e2e-tests/src/phases/staging_contention.py (1)

91-119: ⚡ Quick win

Rename hash to nar_hash in both helpers.

Lines 91 and 108 shadow Python's builtin hash, and Ruff is already flagging A002 here. nar_hash is 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

📥 Commits

Reviewing files that changed from the base of the PR and between 9e10af8 and de27454.

📒 Files selected for processing (9)
  • nix/e2e-tests/README.md
  • nix/e2e-tests/src/phases/staging_contention.py
  • nix/e2e-tests/tests/test_staging_contention.py
  • openspec/changes/archive/2026-06-09-fix-staging-contention-e2e-race/.openspec.yaml
  • openspec/changes/archive/2026-06-09-fix-staging-contention-e2e-race/design.md
  • openspec/changes/archive/2026-06-09-fix-staging-contention-e2e-race/proposal.md
  • openspec/changes/archive/2026-06-09-fix-staging-contention-e2e-race/specs/unified-e2e-harness/spec.md
  • openspec/changes/archive/2026-06-09-fix-staging-contention-e2e-race/tasks.md
  • openspec/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]>
@kalbasit kalbasit changed the title test(e2e): fix staging-contention chunking window fix(cache): engage in-flight staging in the eager-CDC chunking window Jun 10, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

📥 Commits

Reviewing files that changed from the base of the PR and between de27454 and e3bb9b3.

📒 Files selected for processing (13)
  • CHANGELOG.md
  • nix/e2e-tests/README.md
  • nix/e2e-tests/src/phases/staging_contention.py
  • openspec/changes/archive/2026-06-09-engage-staging-eager-cdc-uncompressed/.openspec.yaml
  • openspec/changes/archive/2026-06-09-engage-staging-eager-cdc-uncompressed/design.md
  • openspec/changes/archive/2026-06-09-engage-staging-eager-cdc-uncompressed/proposal.md
  • openspec/changes/archive/2026-06-09-engage-staging-eager-cdc-uncompressed/specs/inflight-nar-staging/spec.md
  • openspec/changes/archive/2026-06-09-engage-staging-eager-cdc-uncompressed/specs/unified-e2e-harness/spec.md
  • openspec/changes/archive/2026-06-09-engage-staging-eager-cdc-uncompressed/tasks.md
  • openspec/specs/inflight-nar-staging/spec.md
  • openspec/specs/unified-e2e-harness/spec.md
  • pkg/cache/cache.go
  • pkg/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

@kalbasit

Copy link
Copy Markdown
Owner Author

/gemini review

@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 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]>
@kalbasit

Copy link
Copy Markdown
Owner Author

/gemini review

@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 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]>
@kalbasit
kalbasit merged commit 0f03901 into main Jun 10, 2026
40 checks passed
@kalbasit
kalbasit deleted the fix-staging-contention-e2e-race branch June 10, 2026 04:15
@dosubot

dosubot Bot commented Jun 10, 2026

Copy link
Copy Markdown

📄 Knowledge review

✏️ Documentation updates

1 page was updated by changes in this PR.

Page Library Status
NAR File Download and Streaming kalbasit's Space ✅ Updated
📝 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.
 

How did I do? Any feedback?  Join Discord

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants