Skip to content

fix(cache): close ds.stored after storeInDatabase, not before - #1256

Merged
kalbasit merged 1 commit into
mainfrom
fix-narinfo-distributed-coordination-race
May 24, 2026
Merged

kalbasit merged 1 commit into
mainfrom
fix-narinfo-distributed-coordination-race

Conversation

@kalbasit

Copy link
Copy Markdown
Owner

Summary

pullNarInfo signaled ds.stored before calling storeInDatabase. The coordinator at coordinateDownload waits on ds.stored and then releases the distributed download lock, so the order made the lock release race against the actual database write:

  1. c1 calls upstream, gets narinfo
  2. c1 signals ds.stored
  3. c1's coordinator releases the download lock
  4. c2 (which was blocked on Lock) acquires the lock
  5. c2's "double-check" hasAsset() reads the database — still empty, because c1 hasn't called storeInDatabase yet
  6. c2 starts its own upstream download — duplicate work
  7. c1 finally calls storeInDatabase

Surfaced as a 10% flake on TestGetNarInfoDistributedCoordination (reproducible locally with go test -count=10; also observed once on the lean-flake-check PR's CI run 26353355126). The fix is a straight swap: signal ds.stored AFTER storeInDatabase succeeds — which is exactly what the existing comment claims ("the asset is now in final storage") but the code wasn't doing.

Why this slipped through

The comment at the original ds.storedOnce.Do site said:

Signal that the asset is now in final storage and the distributed lock can be released. This prevents the race condition where other instances check hasAsset() before storage completes.

That was the intent. The code was doing the opposite. The new comment now matches what the code actually does and names the specific failure mode to make the ordering load-bearing for anyone who refactors this path later.

Error path

Unchanged behavior. If storeInDatabase fails, pullNarInfo returns without signaling ds.stored, but the defer done() closes ds.done. The coordinator's case <-ds.done arm fires and the lock is still released — same as before, just no spurious "stored" signal.

Test plan

  • go test -race -count=30 -run "^TestGetNarInfoDistributedCoordination$" ./pkg/cache/ → 30/30 pass (was failing ~10% before).
  • Adjacent test sanity: go test -race -run "TestGetNarInfo|TestCacheBackends/SQLite/(GetNarInfo|PutNarInfo)" ./pkg/cache/ → all pass.

Refs #1247.

🤖 Generated with Claude Code

pullNarInfo signaled ds.stored BEFORE calling storeInDatabase. The
coordinator at coordinateDownload waits on ds.stored and then releases
the distributed download lock, so the order made the lock release
race against the actual database write:

  1. c1 calls upstream, gets narinfo
  2. c1 signals ds.stored
  3. c1's coordinator releases the download lock
  4. c2 (which was blocked on Lock) acquires the lock
  5. c2's "double-check" hasAsset() reads the database — still empty,
     because c1 hasn't called storeInDatabase yet
  6. c2 starts its own upstream download — duplicate work
  7. c1 finally calls storeInDatabase

Surfaced as a 10% flake on TestGetNarInfoDistributedCoordination
(observed locally with `go test -count=10`; also fired once on the
lean-flake-check PR's CI run 26353355126). The fix is a straight
swap: signal ds.stored after storeInDatabase succeeds, which is
exactly what the existing comment claims ("the asset is now in final
storage") but the code wasn't doing.

The error path is unaffected. If storeInDatabase fails, pullNarInfo
returns without signaling ds.stored, but the defer in `done` closes
ds.done. The coordinator's `case <-ds.done` arm fires and the lock
is still released — same behavior as before, just no false "stored"
signal.

Verified by running TestGetNarInfoDistributedCoordination 30 times
under -race: 30/30 pass. Adjacent tests
(TestGetNarInfo*, TestCacheBackends/SQLite/{GetNarInfo,PutNarInfo})
all still pass.

Refs #1247.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@kalbasit

Copy link
Copy Markdown
Owner Author

This change is part of the following stack:

Change managed by git-spice.

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

coderabbitai Bot commented May 24, 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: ac475f7c-3345-49a6-80da-663902bddd41

📥 Commits

Reviewing files that changed from the base of the PR and between dd9622c and a9af63f.

📒 Files selected for processing (1)
  • pkg/cache/cache.go

📝 Walkthrough

Summary by CodeRabbit

  • Bug Fixes
    • Resolved a distributed cache coordination issue where multiple clients could initiate duplicate asset downloads. Asset ready signals now synchronize properly with database persistence to ensure efficient coordinated caching.

Walkthrough

pullNarInfo defers closing the distributed download coordinator's ready signal until after storeInDatabase succeeds, ensuring other instances do not acquire the lock while asset state is incomplete in the database.

Changes

Download Coordination Race Fix

Layer / File(s) Summary
Distribute storage signal after database persist
pkg/cache/cache.go
pullNarInfo now emits the "asset ready" signal (ds.stored) only after storeInDatabase completes successfully. The completion channel close is deferred until the database write path finishes, preventing other distributed instances from acquiring the lock prematurely based on incomplete asset state. Documentation is expanded to clarify the coordination invariant.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested labels

bug, go

Poem

A rabbit once locked up too quick,
Releasing the gate with a flick—
But now it holds fast,
Till databases last,
No more stampedes, problem fixed! 🐰

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically describes the main change: fixing the timing of when ds.stored is signaled relative to storeInDatabase.
Description check ✅ Passed The description thoroughly explains the race condition, its symptoms, the fix, test plan, and error path behavior—all directly related to the changeset.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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 moves the signaling of asset storage completion in pkg/cache/cache.go to occur after the database update. This change ensures that the distributed lock is only released once the asset is verifiable in the database, preventing race conditions where concurrent instances might trigger redundant upstream downloads. I have no further feedback to provide as there were no review comments to evaluate.

@kalbasit
kalbasit merged commit 95ac42a into main May 24, 2026
25 checks passed
@kalbasit
kalbasit deleted the fix-narinfo-distributed-coordination-race branch May 24, 2026 16:22
kalbasit added a commit that referenced this pull request May 24, 2026
…1257)

## Summary

testConcurrentDownloadCancelOneClientOthersContinue had two
un-timeout-guarded blocking calls after the existing 5–10 s `t.Fatal`
guards: `io.ReadAll(readerB)` (line 1916) and `wg.Wait()` (line 1932).
When the shared streaming goroutine got stuck in some race with client
A's cancellation, `readerB`'s pipe writer never closed and `io.ReadAll`
blocked for the full `go test -timeout` budget — observed as **20-minute
hangs** on CI under heavy load during the lean-flake-check measurement
runs.

This PR wraps both calls in a new test-only helper `runWithTimeout` (30
s budget, dumps all goroutines via `runtime.Stack` on timeout) so the
next occurrence of the hang fails the test in 30 s with the exact
stuck-goroutine trace instead of consuming 20 minutes of CI.

## What this PR does NOT do

It does not fix the underlying race. The race is non-trivial: not
reproducible locally even under 200× `-race -count` stress, code
inspection in `c.GetNar`'s shared-reader-fanout path is suggestive but
ambiguous (see #1252 for the hypotheses), and a real fix needs
goroutine-level diagnostics from an actual CI hang.

Once this PR is merged and the hang fires once more in CI, the failure
will print exactly which goroutine is stuck where. That data should let
us pinpoint and fix the root cause cheaply.

## Stack

```
main → fix-narinfo-distributed-coordination-race (#1256, the real ds.stored race fix)
     → fail-fast-concurrent-download-cancel-hang (this PR)
```

## Test plan

- [x] `go test -race -count=50 -run
"TestCacheBackends/SQLite/ConcurrentDownloadCancelOneClientOthersContinue"
./pkg/cache/` → 50/50 pass (the bug doesn't reproduce locally; this is
purely defensive instrumentation).
- [x] `golangci-lint run ./pkg/cache/cache_test.go` → 0 issues after
`--fix`.

Refs #1252.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 4.7 <[email protected]>
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:S This PR changes 10-29 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant