Repository navigation
fix(cache): prevent hang when client cancels concurrent NAR download - #1280
Conversation
The per-client streaming goroutine in GetNar had two blocking points with no context cancellation escape: 1. The cond.Wait() loop exited on downloadError but not on the client's own context cancellation. A cancelled client could be stuck waiting for the next data broadcast from the download goroutine instead of exiting promptly. 2. The storage-wait select (waiting for ds.stored or ds.done before closing the pipe) had no ctx.Done() case. If storage stalled under I/O pressure the goroutine blocked indefinitely, keeping the pipe writer open and causing io.ReadAll on the caller's reader to hang for the full go test -timeout budget (20 min). Fixes both by: - Adding a watcher goroutine per streaming SafeGo that calls ds.cond.Broadcast() when ctx is cancelled, waking the cond.Wait() loop immediately. - Checking ctx.Err() inside the cond.Wait() loop alongside the existing downloadError check. - Adding case <-ctx.Done() to both storage-wait selects (regular and decompression paths). - Adding ctx to fileAvailableReader so the decompression path also exits promptly on cancellation. Adds TestConcurrentDownloadCancelStress (50 iterations, skipped under -short) to surface the race reliably. 50/50 pass with fix. Closes #1252. Co-Authored-By: Claude Sonnet 4.6 <[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 (2)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughSummary by CodeRabbit
WalkthroughAdds design/spec/docs, makes GetNar streaming goroutines cancellation-aware (fileAvailableReader checks ctx; watcher broadcasts ds.cond; storage waits include ctx.Done()), and adds a 50× stress test to validate the fix. ChangesConcurrent Download Cancellation Fix
Sequence Diagram(s)sequenceDiagram
participant Client
participant StreamingGoroutine
participant Watcher
participant Storage
Client->>StreamingGoroutine: Start GetNar (ctx)
StreamingGoroutine->>StreamingGoroutine: cond.Wait for bytes
Client->>Watcher: ctx.Done
Watcher->>StreamingGoroutine: ds.cond.Broadcast
StreamingGoroutine->>StreamingGoroutine: check ctx.Err -> return if cancelled
StreamingGoroutine->>Storage: wait ds.stored/ds.done
Client->>Storage: ctx.Done triggers storage-wait exit
StreamingGoroutine->>Client: close pipe / return
Estimated code review effort🎯 4 (Complex) | ⏱️ ~75 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 concurrent download cancellation hang (issue #1252) by making the cond.Wait() loop and storage-wait select blocks context-aware in pkg/cache/cache.go. It also adds a stress test to verify the fix. A critical review comment points out a potential nil pointer dereference on r.ctx in fileAvailableReader.Read and a race condition where a cancellation broadcast could be lost if the context is cancelled before entering Wait(), providing a code suggestion to check the context before waiting.
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@pkg/cache/cache_test.go`:
- Around line 4177-4185: The test currently calls
testConcurrentDownloadCancelOneClientOthersContinue which itself calls
t.Parallel(), so the 50 iterations run concurrently; change the test to run
iterations strictly sequentially by invoking a non-parallel variant of the
helper (or extract the shared test body and call it directly) instead of the
parallel helper. Concretely, either add a new helper like
testConcurrentDownloadCancelOneClientOthersContinueSerial (or modify
testConcurrentDownloadCancelOneClientOthersContinue to accept a parallel flag)
that does not call t.Parallel(), and then replace the t.Run(...,
testConcurrentDownloadCancelOneClientOthersContinue(setupSQLiteFactory)) calls
with t.Run(...,
testConcurrentDownloadCancelOneClientOthersContinueSerial(setupSQLiteFactory))
so each iterXX runs one after another.
In `@pkg/cache/cache.go`:
- Around line 500-503: The code calls r.ctx.Err() without guarding r.ctx which
can panic when ctx is nil; update the reader logic in fileAvailableReader to
check r.ctx != nil before calling r.ctx.Err() (e.g., if r.ctx != nil &&
r.ctx.Err() != nil { ... }) and also fix the constructor site that creates
fileAvailableReader without a context (the other instantiation of
fileAvailableReader/fForCDC) to pass the surrounding ctx (e.g., set ctx: ctx) so
fileAvailableReader instances consistently have a non-nil ctx.
🪄 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: 04478fd3-95a8-4cd8-9d1e-cedc4da7af30
📒 Files selected for processing (8)
openspec/changes/archive/2026-05-28-fix-concurrent-download-cancel-hang/.openspec.yamlopenspec/changes/archive/2026-05-28-fix-concurrent-download-cancel-hang/design.mdopenspec/changes/archive/2026-05-28-fix-concurrent-download-cancel-hang/proposal.mdopenspec/changes/archive/2026-05-28-fix-concurrent-download-cancel-hang/specs/nar-concurrent-streaming/spec.mdopenspec/changes/archive/2026-05-28-fix-concurrent-download-cancel-hang/tasks.mdopenspec/specs/nar-concurrent-streaming/spec.mdpkg/cache/cache.gopkg/cache/cache_test.go
Three issues raised by automated reviewers: 1. fileAvailableReader.ctx nil-pointer panic: the CDC path at line ~2774 instantiated fileAvailableReader without ctx, causing a nil dereference on ctx.Err(). Fixed by passing ctx at that site. Added a nil guard (r.ctx != nil) to Read() as defence in depth. 2. Lost-broadcast race in fileAvailableReader.Read: ctx.Err() was checked *after* cond.Wait(), but sync.Cond has no memory — a Broadcast that fires before Wait() is silently lost. Moved the ctx.Err() check to *before* cond.Wait() so a broadcast that already fired is caught on the next loop iteration. 3. Stress test iterations were concurrent, not sequential: the 50- iteration stress loop called testConcurrentDownloadCancelOne- ClientOthersContinue whose returned func calls t.Parallel(), causing all 50 subtests to run in parallel. Extracted the test body into runConcurrentDownloadCancelOneClientOthersContinue (no t.Parallel()) and updated the stress loop to call it directly, making each iter run strictly after the previous one. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Summary
The per-client streaming goroutine in
GetNarhad two blocking points withno context cancellation escape, causing a once-in-CI 20-minute hang when one
client cancelled a shared in-flight download (ncps Hang in TestCacheBackends/.../ConcurrentDownloadCancelOneClientOthersContinue — io.ReadAll has no timeout guard #1252).
cond.Wait()loop: added a watcher goroutine per streaming SafeGo thatcalls
ds.cond.Broadcast()when the client'sctxis cancelled, waking theloop immediately. Added
ctx.Err() != nilalongside the existingdownloadErrorcheck so the goroutine exits without waiting for the nextdata broadcast.
Storage-wait
select: extended both the regular and decompression pathselects (
ds.stored/ds.done) withcase <-ctx.Done():so a cancelledclient does not block indefinitely if storage stalls under I/O pressure.
fileAvailableReader: addedctx context.Contextfield;Read()nowreturns
ctx.Err()after anycond.Wait()wakeup when the context is done,covering the decompression streaming path.
Added
TestConcurrentDownloadCancelStress(50 iterations, skipped under-short) to surface the race reliably. 50/50 pass with fix under-race.Test plan
task fmt— no changestask lint— 0 issuestask test— all pass includingConcurrentDownloadCancelOneClientOthersContinueTestConcurrentDownloadCancelStress— 50/50 iterations pass under-raceCloses #1252