Skip to content

fix(cache): prevent hang when client cancels concurrent NAR download - #1280

Merged
kalbasit merged 2 commits into
mainfrom
user/wnasreddine/next-fix
May 29, 2026
Merged

kalbasit merged 2 commits into
mainfrom
user/wnasreddine/next-fix

Conversation

@kalbasit

@kalbasit kalbasit commented May 28, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • The per-client streaming goroutine in GetNar had two blocking points with
    no 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 that
    calls ds.cond.Broadcast() when the client's ctx is cancelled, waking the
    loop immediately. Added ctx.Err() != nil alongside the existing
    downloadError check so the goroutine exits without waiting for the next
    data broadcast.

  • Storage-wait select: extended both the regular and decompression path
    selects (ds.stored / ds.done) with case <-ctx.Done(): so a cancelled
    client does not block indefinitely if storage stalls under I/O pressure.

  • fileAvailableReader: added ctx context.Context field; Read() now
    returns ctx.Err() after any cond.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 changes
  • task lint — 0 issues
  • task test — all pass including ConcurrentDownloadCancelOneClientOthersContinue
  • TestConcurrentDownloadCancelStress — 50/50 iterations pass under -race

Closes #1252

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

kalbasit commented May 28, 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 28, 2026
@coderabbitai

coderabbitai Bot commented May 28, 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: 356a88bf-8fa3-4c2a-8418-939dd3de059c

📥 Commits

Reviewing files that changed from the base of the PR and between ea6e938 and 7da7a3b.

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

📝 Walkthrough

Summary by CodeRabbit

  • Bug Fixes

    • Cancelled concurrent downloads now terminate promptly without leaving sibling downloads blocked; other clients continue receiving full streams.
  • Tests

    • Added a stress test that repeatedly exercises concurrent-cancel scenarios under race detection to catch regressions.
  • Documentation

    • Added design, proposal, task checklist, and specification documents describing the concurrency and cancellation behavior and validation plan.

Walkthrough

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

Changes

Concurrent Download Cancellation Fix

Layer / File(s) Summary
Design, proposal, spec, tasks, archive
openspec/changes/archive/2026-05-28-fix-concurrent-download-cancel-hang/*, openspec/specs/nar-concurrent-streaming/spec.md
Design, proposal, spec, and task checklist documenting the hang, the watcher + ctx.Done() approach, migration/test plan, and archive metadata.
Context-aware reader and watcher
pkg/cache/cache.go
fileAvailableReader now carries the request context.Context and returns on ctx.Err(); a watcher goroutine broadcasts ds.cond on ctx.Done() to unblock cond.Wait callers.
Decompression and progressive streaming paths
pkg/cache/cache.go
Decompression, CDC, and progressive streaming paths construct fileAvailableReader with ctx and add case <-ctx.Done() branches when waiting on ds.stored/ds.done so cancelled clients exit promptly.
Stress test and refactor
pkg/cache/cache_test.go
Refactor test logic into runConcurrentDownloadCancelOneClientOthersContinue; add TestConcurrentDownloadCancelStress that runs the scenario 50× (skippable under -short) against SQLite to validate under -race.

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Possibly related PRs

  • kalbasit/ncps#1257: Similar test-focused changes to make the concurrent-cancel test fail fast with runWithTimeout guards.
  • kalbasit/ncps#1256: Modifies ds.stored emission timing; touches the same storage-sync coordination observed by GetNar waits.
  • kalbasit/ncps#1207: Other changes to progressive streaming control flow that intersect with GetNar streaming logic.

Poem

🐰 I watched the streams where goroutines slept tight,
A cancelled ctx popped and gave them light—
A watcher tapped the cond, storage checked the hand,
Now pipes close cleanly and reads finish as planned. 🎉

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main fix: preventing a hang in concurrent NAR downloads when a client cancels, matching the core objective to address the GetNar blocking issue.
Description check ✅ Passed The description is directly related to the changeset, detailing the two blocking points fixed, the watcher goroutine, storage-wait select updates, fileAvailableReader context additions, and test additions.
Linked Issues check ✅ Passed The PR successfully addresses issue #1252 by fixing both blocking points identified (cond.Wait() loop and storage-wait select), adding context cancellation escape paths, and adding stress testing to validate the fix.
Out of Scope Changes check ✅ Passed All changes are directly scoped to fixing the concurrent download cancellation hang: watcher goroutine, context-aware waits, stress test, and spec/design documentation for the fix.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8d4531e and ea6e938.

📒 Files selected for processing (8)
  • openspec/changes/archive/2026-05-28-fix-concurrent-download-cancel-hang/.openspec.yaml
  • openspec/changes/archive/2026-05-28-fix-concurrent-download-cancel-hang/design.md
  • openspec/changes/archive/2026-05-28-fix-concurrent-download-cancel-hang/proposal.md
  • openspec/changes/archive/2026-05-28-fix-concurrent-download-cancel-hang/specs/nar-concurrent-streaming/spec.md
  • openspec/changes/archive/2026-05-28-fix-concurrent-download-cancel-hang/tasks.md
  • openspec/specs/nar-concurrent-streaming/spec.md
  • pkg/cache/cache.go
  • pkg/cache/cache_test.go

Comment thread pkg/cache/cache_test.go Resolved
Comment thread pkg/cache/cache.go Resolved
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]>
@kalbasit
kalbasit enabled auto-merge (squash) May 28, 2026 23:56
@kalbasit
kalbasit merged commit 3cd81eb into main May 29, 2026
26 of 36 checks passed
@kalbasit
kalbasit deleted the user/wnasreddine/next-fix branch May 29, 2026 00:02
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 size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Hang in TestCacheBackends/.../ConcurrentDownloadCancelOneClientOthersContinue — io.ReadAll has no timeout guard

1 participant