Skip to content

fix(cache): stop returning HTTP 500 on download-lock contention - #1290

Merged
kalbasit merged 4 commits into
mainfrom
user/wnasreddine/ncps-error-500
May 29, 2026
Merged

kalbasit merged 4 commits into
mainfrom
user/wnasreddine/ncps-error-500

Conversation

@kalbasit

Copy link
Copy Markdown
Owner

Summary

Fixes the HTTP 500s seen during concurrent nix pulls against a
multi-replica ncps (the failed to acquire download lock and timeout polling for completion errors).

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

  • 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.
    • Asset appears → holder succeeded, serve it.
    • Lock re-acquired → 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) so Nix falls back to
      another substituter instead of retrying a 500. Caller cancellation
      still surfaces as a context error.
  • Add the ncps_download_coordination_fallback_total counter
    (outcome=served_by_peer|take_over|give_up|caller_canceled) plus
    structured logs so operators can see how contention resolves.
  • Also includes earlier fixes on this branch balancing ds.wg on
    GetNar early returns.

Follow-up filed: #1289 (serve a whole NAR from shared storage during CDC
chunking instead of the progressive chunk stream).

Test plan

  • New deterministic mock-locker tests (RED→GREEN): take-over serves
    the NAR, narinfo miss → 404, NAR give-up → 404
    (pkg/cache/coordination_internal_test.go).
  • task fmt (clean), task lint (0 issues), task test pass.
  • task test:auto — full suite incl. the Redis-backed distributed
    cohort — passes.

kalbasit and others added 3 commits May 29, 2026 12:15
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]>
@kalbasit

kalbasit commented May 29, 2026 •

Copy link
Copy Markdown
Owner Author

This change is part of the following stack:

Change managed by git-spice.

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

coderabbitai Bot commented May 29, 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: 2473ee4a-12ee-4c9e-9045-6893a63b6f77

📥 Commits

Reviewing files that changed from the base of the PR and between b16475d and 217afea.

📒 Files selected for processing (1)
  • pkg/cache/cache.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/cache/cache.go

📝 Walkthrough

Summary by CodeRabbit

  • Bug Fixes

    • Fixed spurious HTTP 500 errors during concurrent downloads; replicas now wait, re-acquire and take over downloads when appropriate or return clean cache-miss (404) outcomes.
    • Fixed potential goroutine/workgroup hang when requests are canceled during download flows.
  • Documentation

    • Added design, proposal, and spec updates describing serialized takeover behavior, timeouts, and expected HTTP outcomes for NAR and narinfo coordination.
  • Tests

    • Added regression and integration tests covering lock contention, takeover, and give-up behaviors.

Walkthrough

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

Changes

Download Coordination 500 Fix

Layer / File(s) Summary
Specifications, Design, and Requirements
openspec/changes/archive/2026-05-29-fix-download-coordination-500/..., openspec/specs/nar-concurrent-streaming/spec.md, openspec/specs/narinfo-concurrent-fetch/spec.md
OpenSpec metadata, design document, proposal, tasks, and spec additions define poll-or-reacquire behavior, TTL-aligned give-up mapped to storage.ErrNotFound (404), and serialized takeover requirements for NAR and narinfo coordination.
Coordination Fallback Implementation and Metrics
pkg/cache/cache.go
Adds downloadCoordinationFallbackTotal counter with outcome labels (served_by_peer, take_over, give_up, caller_canceled); fixes WaitGroup imbalance in GetNar early-exit paths; replaces the poll-only fallback with pollForDownloadOrTakeOver, which polls storage, periodically tries to re-acquire the lock to take over, records outcome, and closes ds channels to avoid deadlocks.
Coordination and Concurrency Tests
pkg/cache/coordination_internal_test.go, pkg/cache/cache_test.go
Adds takeoverLocker test double and setupTakeoverCache, configures short TTLs, and adds tests: TestCoordinateDownloadTakesOverNAR, TestCoordinateDownloadNarInfoMissReturnsNotFound, TestCoordinateDownloadNARGiveUpReturnsNotFound, plus TestGetNarCloseDoesNotHangAfterContextCancelledBeforeStart to guard against Close hangs.

Sequence Diagram(s)

sequenceDiagram
  participant ComponentA
  participant ComponentB
  ComponentA->>ComponentB: observable interaction
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • kalbasit/ncps#1257: Adds runWithTimeout helper and related test patterns for fast-failing cancellation/coordination hang tests used in pkg/cache/cache_test.go.
  • kalbasit/ncps#1256: Related coordination work that adjusts the timing/order of the ds.stored signal affecting takeover correctness.
  • kalbasit/ncps#1280: Overlaps in GetNar concurrent streaming cancellation and downloadState lifecycle handling.

Poem

🐰 I hopped to fetch a shiny tar,
The first held tight and kept it far.
I polled, then tried once more—
Took over, closed the door,
Served bytes, not a 500 scar.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main change: fixing HTTP 500 errors that occur during download-lock contention. It is specific, actionable, and accurately represents the core objective of the PR.
Description check ✅ Passed The description is comprehensive and directly related to the changeset. It explains the problem (HTTP 500s during concurrent pulls), the root cause (poll-only loop timeout), the solution (poll-or-reacquire loop), and testing approach.
Docstring Coverage ✅ Passed Docstring coverage is 87.50% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

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

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

Comment thread pkg/cache/cache.go Resolved

@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: 3

🧹 Nitpick comments (2)
pkg/cache/coordination_internal_test.go (1)

179-183: ⚡ Quick win

Replace 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.Eventually over 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 win

Align the timeout-bound formula across sections.

Decision 3 describes a min(...)-style bound, while the resolved implementation states max(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

📥 Commits

Reviewing files that changed from the base of the PR and between bbc6808 and b16475d.

📒 Files selected for processing (11)
  • openspec/changes/archive/2026-05-29-fix-download-coordination-500/.openspec.yaml
  • openspec/changes/archive/2026-05-29-fix-download-coordination-500/design.md
  • openspec/changes/archive/2026-05-29-fix-download-coordination-500/proposal.md
  • openspec/changes/archive/2026-05-29-fix-download-coordination-500/specs/nar-concurrent-streaming/spec.md
  • openspec/changes/archive/2026-05-29-fix-download-coordination-500/specs/narinfo-concurrent-fetch/spec.md
  • openspec/changes/archive/2026-05-29-fix-download-coordination-500/tasks.md
  • openspec/specs/nar-concurrent-streaming/spec.md
  • openspec/specs/narinfo-concurrent-fetch/spec.md
  • pkg/cache/cache.go
  • pkg/cache/cache_test.go
  • pkg/cache/coordination_internal_test.go

Comment thread pkg/cache/cache.go Resolved
Comment thread pkg/cache/cache.go Resolved
Comment thread pkg/cache/cache.go Resolved
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]>
@kalbasit
kalbasit enabled auto-merge (squash) May 29, 2026 19:31
@kalbasit
kalbasit merged commit e07d9a0 into main May 29, 2026
26 checks passed
@kalbasit
kalbasit deleted the user/wnasreddine/ncps-error-500 branch May 29, 2026 19:48
kalbasit added a commit that referenced this pull request May 30, 2026
## 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]>
kalbasit added a commit that referenced this pull request Jun 9, 2026
#1375)

The coordination poll loop called hasFinishedAsset then hasAsset on every
200ms tick, each repeating HasNarInStore (a storage stat / S3 HEAD) and
the nar_file lookup — redundant I/O and DB load under contention.

Extract one oracle, narServability(ctx, narURL) (servable, finished, err),
and have isServable and hasFinishedNar both delegate to it (preserving the
single-source-of-truth that prevents the divergent-check regressions
#1255/#1263/#1279/#1290). Collapse coordinateDownload /
pollForDownloadOrTakeOver from two predicate closures to one
checkAsset(ctx) (servable, finished); the tick now computes both states in
a single call. Behavior is unchanged (full -race suite green).

Resolves threads PRRT_kwDONV6tZs6H_WfI, _WfM, _WfP, _WfR, _WfW, _Wfa,
_Wfc, _Wfn, _Wfo.
kalbasit added a commit that referenced this pull request Jun 9, 2026
#1375)

The coordination poll loop called hasFinishedAsset then hasAsset on every
200ms tick, each repeating HasNarInStore (a storage stat / S3 HEAD) and
the nar_file lookup — redundant I/O and DB load under contention.

Extract one oracle, narServability(ctx, narURL) (servable, finished, err),
and have isServable and hasFinishedNar both delegate to it (preserving the
single-source-of-truth that prevents the divergent-check regressions
#1255/#1263/#1279/#1290). Collapse coordinateDownload /
pollForDownloadOrTakeOver from two predicate closures to one
checkAsset(ctx) (servable, finished); the tick now computes both states in
a single call. Behavior is unchanged (full -race suite green).

Resolves threads PRRT_kwDONV6tZs6H_WfI, _WfM, _WfP, _WfR, _WfW, _Wfa,
_Wfc, _Wfn, _Wfo.
kalbasit added a commit that referenced this pull request Jun 9, 2026
#1375)

The coordination poll loop called hasFinishedAsset then hasAsset on every
200ms tick, each repeating HasNarInStore (a storage stat / S3 HEAD) and
the nar_file lookup — redundant I/O and DB load under contention.

Extract one oracle, narServability(ctx, narURL) (servable, finished, err),
and have isServable and hasFinishedNar both delegate to it (preserving the
single-source-of-truth that prevents the divergent-check regressions
#1255/#1263/#1279/#1290). Collapse coordinateDownload /
pollForDownloadOrTakeOver from two predicate closures to one
checkAsset(ctx) (servable, finished); the tick now computes both states in
a single call. Behavior is unchanged (full -race suite green).

Resolves threads PRRT_kwDONV6tZs6H_WfI, _WfM, _WfP, _WfR, _WfW, _Wfa,
_Wfc, _Wfn, _Wfo.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working go Pull requests that update go code merge-stack size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant