Repository navigation
fix(cache): stop returning HTTP 500 on download-lock contention - #1290
Conversation
When canStream=true, ds.wg.Add(1) is called before the select that waits for ds.start. Two early-return paths never called ds.wg.Done(): 1. ctx.Done() fires before ds.start closes — GetNar returns ctx.Err() without launching the streaming goroutine whose defer does the Done. 2. ds.getError() returns non-nil after ds.start closes — same issue. Both paths leave ds.wg permanently > 0, causing the cleanup goroutine (pullNarIntoStore.func3, tracked by backgroundWG) to block forever at ds.wg.Wait(), which in turn blocks c.Close() indefinitely. On slower aarch64 runners the race is reliably triggered by the stress test (cancelA fires before ds.start closes), explaining the 20-minute timeout seen in CI.
When canStream=true, ds.wg.Add(1) is called so the cleanup goroutine in pullNarIntoStore can wait for all readers via ds.wg.Wait(). Two early-return paths in GetNar never called ds.wg.Done(): 1. case <-ctx.Done(): returned ctx.Err() without decrementing 2. ds.getError() != nil: returned the error without decrementing This left the cleanup goroutine blocked at ds.wg.Wait() forever, causing c.Close() → backgroundWG.Wait() to hang indefinitely. Root cause of TestConcurrentDownloadCancelStress timeouts in CI on aarch64-linux ncps-postgres-tests. Fix: add ds.wg.Done() before each early return. A new deterministic regression test pre-cancels the client context, lets the server respond normally so the cleanup goroutine is started, then verifies c.Close() completes without hanging.
A replica that failed to acquire the distributed download lock fell into a poll-only loop that watched solely for the asset to appear. When the lock holder's download failed (e.g. an upstream HTTP/2 reset) or ran past the fixed poll timeout, the waiter timed out and returned the coordination error, which the server mapped to HTTP 500. Nix treats 500 as a hard error and retries it up to 5x, amplifying load during the concurrent-pull bursts that coalescing exists to smooth. Rework the cross-pod fallback in coordinateDownload into a poll-or-reacquire loop (extracted to pollForDownloadOrTakeOver): each tick checks for the asset AND re-attempts lock acquisition. If the asset appears the holder succeeded and we serve it; if we re-acquire the lock the previous holder finished or failed without producing the asset, so we take over as the sole downloader (the upstreamJobs map and the lock keep downloads serialized, so the concurrent-CDC path is never exercised). Wait up to max(downloadLockTTL, downloadPollTimeout) so a legitimately slow holder is not abandoned, then give up with a clean cache miss (storage.ErrNotFound -> HTTP 404) instead of a 500 so Nix falls back to another substituter. Caller cancellation still surfaces as a context error. Add a ncps_download_coordination_fallback_total counter (outcome: served_by_peer, take_over, give_up, caller_canceled) and structured logs so operators can observe how contention resolves. Cover the behavior with deterministic mock-locker tests plus the existing Redis-backed distributed suite. 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
WalkthroughImplements a bounded poll-or-reacquire fallback for distributed download coordination so lock-losing replicas either serve the produced asset, re-acquire the lock and take over, or map terminal give-up to storage.ErrNotFound (HTTP 404); adds metrics, logging, and regression tests for takeover, not-found, and cancellation hang scenarios. ChangesDownload Coordination 500 Fix
Sequence Diagram(s)sequenceDiagram
participant ComponentA
participant ComponentB
ComponentA->>ComponentB: observable interaction
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
Comment |
There was a problem hiding this comment.
Code Review
This pull request addresses a critical issue where download lock contention across replicas results in HTTP 500 errors. The fix replaces the dead-end polling loop with a poll-or-reacquire mechanism (pollForDownloadOrTakeOver) that allows waiters to either serve the downloaded asset, take over the download if the lock is released, or gracefully return a 404 cache miss on timeout. It also resolves a hang during cache shutdown caused by a sync.WaitGroup imbalance when a context is cancelled early. The reviewer identified a high-severity issue in the new polling loop: using the blocking Lock method inside the ticker case can block the goroutine, preventing it from polling or responding to context cancellation. It is recommended to use TryLock instead to keep the loop non-blocking and responsive.
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (2)
pkg/cache/coordination_internal_test.go (1)
179-183: ⚡ Quick winReplace fixed sleeps with deterministic synchronization in coordination tests.
These sleeps can release the lock before the waiter has actually entered fallback, which can make the tests pass without validating the intended path. Prefer gating on an observed failed lock attempt (or
require.Eventuallyover a locker attempt counter).Also applies to: 216-218
🤖 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 `@pkg/cache/coordination_internal_test.go` around lines 179 - 183, The test currently uses time.Sleep before calling locker.release(narKey), which is flaky; instead, make the waiter deterministically reach the poll-and-reacquire fallback before releasing the lock by observing the failed lock attempt (or the locker attempt counter) from GetNar's acquisition logic; e.g., wait (using require.Eventually or a channel/cond) until the locker shows a failed acquisition attempt for narKey or the attempt counter increments, then call locker.release(narKey); apply the same change to the other occurrence around the lines that reference locker.release and the initial Sleep (also the occurrence at the later block).openspec/changes/archive/2026-05-29-fix-download-coordination-500/design.md (1)
96-101: ⚡ Quick winAlign the timeout-bound formula across sections.
Decision 3 describes a
min(...)-style bound, while the resolved implementation statesmax(downloadLockTTL, downloadPollTimeout). Please unify the wording so the design has one authoritative formula.Also applies to: 152-156
🤖 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 `@openspec/changes/archive/2026-05-29-fix-download-coordination-500/design.md` around lines 96 - 101, Decision text and the resolved implementation disagree on the timeout formula (Decision 3 uses a min(...) bound while the implementation uses max(downloadLockTTL, downloadPollTimeout)); pick one authoritative formula and update both places to match: use min(coordCtx deadline, downloadLockTTL) (i.e., wait up to the lesser of the coordination context deadline and the holder's lock TTL) and remove the max(...) wording and any references to downloadPollTimeout as the dominating bound; ensure all occurrences (including the resolved implementation and Decision 3) consistently mention the same min(...) expression and the preference to take over immediately when the lock frees.
🤖 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/cache.go`:
- Around line 390-392: The added panic(err) in pkg/cache/cache.go introduces a
new crash path; change this initialization to return the error instead of
panicking: update the enclosing function (e.g., the cache initialization
function that currently checks "if err != nil") to return an error (or wrap the
err with context via fmt.Errorf) and propagate that error to callers (or to the
caller that performs startup), removing the panic(err) call; ensure the call
sites that invoke this init function handle and return/log the error rather than
assuming success.
- Around line 214-215: Add an inline justification for the
//nolint:gochecknoglobals directive so reviewers know why the global variable is
acceptable: update the declaration around downloadCoordinationFallbackTotal to
use “//nolint:gochecknoglobals — reason: <brief justification>” immediately
adjacent to the directive (e.g., explain that downloadCoordinationFallbackTotal
is a metrics/telemetry global intentionally scoped for package-wide reuse),
referencing the variable name downloadCoordinationFallbackTotal and the
surrounding metric.Int64Counter declaration.
- Around line 5603-5616: The reacquire path currently calls
c.downloadLocker.Lock(ctx, lockKey, c.downloadLockTTL) using a detached ctx
which can block beyond giveUpBound/caller cancellation; change the Lock call to
use the deadline/cancellation-bound context (e.g., deadlineCtx or the
giveUpBound context used earlier in this call path) instead of ctx so the
re-acquire attempt respects the same timeout/cancellation guarantees, and keep
the existing success/failure handling and metrics (referencing
c.downloadLocker.Lock, lockKey, and c.downloadLockTTL).
---
Nitpick comments:
In `@openspec/changes/archive/2026-05-29-fix-download-coordination-500/design.md`:
- Around line 96-101: Decision text and the resolved implementation disagree on
the timeout formula (Decision 3 uses a min(...) bound while the implementation
uses max(downloadLockTTL, downloadPollTimeout)); pick one authoritative formula
and update both places to match: use min(coordCtx deadline, downloadLockTTL)
(i.e., wait up to the lesser of the coordination context deadline and the
holder's lock TTL) and remove the max(...) wording and any references to
downloadPollTimeout as the dominating bound; ensure all occurrences (including
the resolved implementation and Decision 3) consistently mention the same
min(...) expression and the preference to take over immediately when the lock
frees.
In `@pkg/cache/coordination_internal_test.go`:
- Around line 179-183: The test currently uses time.Sleep before calling
locker.release(narKey), which is flaky; instead, make the waiter
deterministically reach the poll-and-reacquire fallback before releasing the
lock by observing the failed lock attempt (or the locker attempt counter) from
GetNar's acquisition logic; e.g., wait (using require.Eventually or a
channel/cond) until the locker shows a failed acquisition attempt for narKey or
the attempt counter increments, then call locker.release(narKey); apply the same
change to the other occurrence around the lines that reference locker.release
and the initial Sleep (also the occurrence at the later block).
🪄 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: 921e5837-10a6-49c0-8111-a54472d46d4e
📒 Files selected for processing (11)
openspec/changes/archive/2026-05-29-fix-download-coordination-500/.openspec.yamlopenspec/changes/archive/2026-05-29-fix-download-coordination-500/design.mdopenspec/changes/archive/2026-05-29-fix-download-coordination-500/proposal.mdopenspec/changes/archive/2026-05-29-fix-download-coordination-500/specs/nar-concurrent-streaming/spec.mdopenspec/changes/archive/2026-05-29-fix-download-coordination-500/specs/narinfo-concurrent-fetch/spec.mdopenspec/changes/archive/2026-05-29-fix-download-coordination-500/tasks.mdopenspec/specs/nar-concurrent-streaming/spec.mdopenspec/specs/narinfo-concurrent-fetch/spec.mdpkg/cache/cache.gopkg/cache/cache_test.gopkg/cache/coordination_internal_test.go
Address PR review: the take-over re-acquisition in pollForDownloadOrTakeOver called the blocking Lock, which retries internally on the Redis backend and could stall the 200ms poll loop and outlive both the give-up deadline and caller cancellation. Switch to a single non-blocking TryLock bounded by deadlineCtx so each tick returns promptly and the loop stays responsive. Also add the missing explanatory comment to the //nolint:gochecknoglobals on the new metric global. Co-Authored-By: Claude Opus 4.8 <[email protected]>
## Summary Closes the remaining gaps behind the "phantom nar_file" defect — permanent `error: file 'nar/<hash>.nar.xz' does not exist` 404s for paths whose narinfo was just served. A backing-less `nar_file` row (`total_chunks=0`, `chunking_started_at=NULL`) left by a failed background download was treated as servable and short-circuited `GET /nar` to a terminal 404. Prior PRs (#1255–#1290) fixed the core read path; this hardens the edges and prevents the recurring regression. - **Upstream retry (D5):** extend GET/HEAD retry beyond `GOAWAY` to also cover `http2: timeout awaiting response headers`, connection reset, and broken pipe via `isRetriableTransportError`. Genuine 404s return a response (not a transport error) and stay non-retryable. - **Single source of truth (D1):** unify the duplicated, drift-prone servability checks in `GetNar` and `prePullNar`'s `hasAsset` behind one `isServable()` predicate (+ `narFileServable()`), so a placeholder row is never servable and the regression can't return via divergent checks. Behavior-preserving. - **Recovery sweep:** `runCDCLazyRecovery` now skips backing-less stuck rows. `BackgroundMigrateNarToChunks` can only chunk a store-present NAR, so re-driving placeholder/genuinely-absent rows every interval was futile `error fetching nar from store: not found` spam that indefinitely retried unmigratable hashes. Such rows are recovered on demand by `GetNar`. No schema migration. OpenSpec change `fix-phantom-nar-cache-miss` archived and its delta specs synced into `openspec/specs/`. ## Test plan - [x] `task fmt` clean; changed packages lint clean - [x] `task test` green (all packages; `pkg/cache` + `pkg/cache/upstream` under `-race`) - [x] `phantom_recovery_test.go` — reproduces narinfo 200 → failed download → recovery on next request, plus the genuine-404 path - [x] `transient_retry_test.go` — new retriable errors retried; genuine 404 not retried - [x] `recovery_skip_internal_test.go` — sweep skips backing-less rows, re-drives store-present ones (RED→GREEN verified) --------- 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.
#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.
#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.
Summary
Fixes the HTTP 500s seen during concurrent
nixpulls against amulti-replica ncps (the
failed to acquire download lock and timeout polling for completionerrors).When a replica failed to acquire the distributed download lock, it fell
into a poll-only loop that watched solely for the asset to appear. If the
lock holder's download failed (e.g. an upstream HTTP/2 reset) or simply
ran past the fixed poll timeout, the waiter timed out and returned the
coordination error → HTTP 500. Nix treats 500 as a hard error and retries
it up to 5×, amplifying load during exactly the concurrent-pull bursts
that request coalescing exists to smooth.
What changed
coordinateDownloadinto apoll-or-reacquire loop (extracted to
pollForDownloadOrTakeOver):each tick checks for the asset and re-attempts lock acquisition.
producing the asset, so we take over as the sole downloader. The
upstreamJobsmap and the lock keep downloads serialized, so theconcurrent-CDC path is never exercised.
max(downloadLockTTL, downloadPollTimeout)so alegitimately slow holder is not abandoned, then give up with a clean
cache miss (
storage.ErrNotFound→ HTTP 404) so Nix falls back toanother substituter instead of retrying a 500. Caller cancellation
still surfaces as a context error.
ncps_download_coordination_fallback_totalcounter(
outcome=served_by_peer|take_over|give_up|caller_canceled) plusstructured logs so operators can see how contention resolves.
ds.wgonGetNarearly returns.Follow-up filed: #1289 (serve a whole NAR from shared storage during CDC
chunking instead of the progressive chunk stream).
Test plan
the NAR, narinfo miss → 404, NAR give-up → 404
(
pkg/cache/coordination_internal_test.go).task fmt(clean),task lint(0 issues),task testpass.task test:auto— full suite incl. the Redis-backed distributedcohort — passes.