Repository navigation
fix(cache): prevent spurious narinfo purge under concurrent fetch - #1279
Conversation
|
This change is part of the following stack: Change managed by git-spice. |
📝 WalkthroughSummary by CodeRabbit
WalkthroughThis PR prevents spurious narinfo purges under concurrent fetches by adding a re-check of storage (HasNarInStore / HasNarInChunks) before purging in getNarInfoFromDatabase, and includes specification/design documents plus a concurrent cold-cache regression test. ChangesConcurrent Narinfo Fetch Fix
Sequence DiagramsequenceDiagram
participant Client as Test / Client
participant Cache as Cache.GetNarInfo
participant DB as getNarInfoFromDatabase
participant UpstreamJobs as upstreamJobs
participant Store as Storage (HasNarInStore/HasNarInChunks)
participant Purge as purgeNarInfo
Client->>Cache: GetNarInfo(hash)
Cache->>DB: lookup narinfo
DB->>UpstreamJobs: check in-flight job keys
DB->>Store: initial HasNarInStore / HasNarInChunks
DB->>Store: re-check HasNarInStore / HasNarInChunks (before purge)
alt re-check succeeds
DB-->>Cache: return narinfo
Cache-->>Client: 200 + narinfo
else still missing
DB->>Purge: purgeNarInfo(hash)
Purge-->>Cache: not found
Cache-->>Client: 404
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 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 aims to resolve a flaky TOCTOU race condition during concurrent narinfo fetches by extending the purge guard checks. Specifically, it updates hasUpstreamJob to check for both NAR and narinfo jobs and adds a concurrent cold cache fetch test. The reviewer identified a critical flaw in this approach: hasUpstreamJob is queried with the NAR hash while the narinfo job is registered under the narinfo hash, meaning they will never match. Additionally, the narinfo job is already deleted by the time piggybacking goroutines wake up. The reviewer suggests reverting this change and instead implementing a double-check of HasNarInStore in getNarInfoFromDatabase. A minor improvement was also suggested to use newContext() instead of context.Background() in the new test to maintain consistency and prevent log clutter.
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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
`@openspec/changes/archive/2026-05-28-fix-flaky-narinfo-concurrent-fetch/design.md`:
- Around line 11-19: In the fenced code block that begins with "goroutine A
(concurrent request that piggybacked)" add a language identifier to the opening
backticks (for example change ``` to ```text) so the markdown linter recognizes
the block language; edit the block in design.md containing the goroutine A /
goroutine B example and update the opening fence accordingly.
🪄 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: 501d9ab3-761f-47fe-9f99-87279574cbb6
📒 Files selected for processing (8)
openspec/changes/archive/2026-05-28-fix-flaky-narinfo-concurrent-fetch/.openspec.yamlopenspec/changes/archive/2026-05-28-fix-flaky-narinfo-concurrent-fetch/design.mdopenspec/changes/archive/2026-05-28-fix-flaky-narinfo-concurrent-fetch/proposal.mdopenspec/changes/archive/2026-05-28-fix-flaky-narinfo-concurrent-fetch/specs/narinfo-concurrent-fetch/spec.mdopenspec/changes/archive/2026-05-28-fix-flaky-narinfo-concurrent-fetch/tasks.mdopenspec/specs/narinfo-concurrent-fetch/spec.mdpkg/cache/cache.gopkg/cache/cache_test.go
hasUpstreamJob only checked narJobKey ("download:nar:…"), missing
the narInfoJobKey ("download:narinfo:…"). When concurrent goroutines
piggybacked on a narinfo fetch via coordinateDownload, they'd wake on
ds.done after the narinfo was stored in DB but before the NAR download
goroutine had registered its job key. In that narrow window both
hasUpstreamJob and isRemoteDownloadInProgress returned false, causing
the purge guard in getNarInfoFromDatabase to fire — deleting the
narinfo and returning storage.ErrNotFound → HTTP 404 to waiting
callers.
Fix: extend hasUpstreamJob to check narInfoJobKey in addition to
narJobKey. If the narinfo job is still in-flight, the purge is
suppressed. Adds testGetNarInfoConcurrentColdCacheFetch to guard
against regressions.
Fixes #1276
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
The initial fix used narInfoJobKey(narURL.Hash) in hasUpstreamJob, but narURL.Hash is the NAR hash — narinfo jobs are keyed by the narinfo hash, so that lookup always missed. Additionally, the narinfo job is removed from upstreamJobs as part of the same done() call that closes ds.done, so piggybacking goroutines always see it gone. The correct guard is a second HasNarInStore + HasNarInChunks check immediately before the purge. If the NAR download's os.Rename completed between the initial HasNarInStore check and hasUpstreamJob returning false (job removed after rename), the re-check sees the file and skips the purge. This closes the TOCTOU window without relying on upstreamJobs state. Also revert the erroneous narInfoJobKey check from hasUpstreamJob, and switch context.Background() → newContext() in the concurrent fetch test for consistency with the rest of the test suite. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
281d2b8 to
cce2316
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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 4127-4142: The double-check using HasNarInStore and HasNarInChunks
still allows a race because hasUpstreamJob only checks narJobKey
(download:nar:<hash>), missing concurrent download:narinfo:<hash> jobs; update
the logic around HasNarInStore/HasNarInChunks and hasUpstreamJob so you also
detect any in-flight narinfo jobs before deciding to purge: compute the narinfo
job key (download:narinfo:<hash>) and call hasUpstreamJob for both narJobKey and
the narinfo job key (or a combined helper like hasAnyUpstreamJob) and treat
either being present as proof to not purge/return nil.
🪄 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: 132a3688-73d2-4d21-9de2-cbb94bb1bca6
📒 Files selected for processing (8)
openspec/changes/archive/2026-05-28-fix-flaky-narinfo-concurrent-fetch/.openspec.yamlopenspec/changes/archive/2026-05-28-fix-flaky-narinfo-concurrent-fetch/design.mdopenspec/changes/archive/2026-05-28-fix-flaky-narinfo-concurrent-fetch/proposal.mdopenspec/changes/archive/2026-05-28-fix-flaky-narinfo-concurrent-fetch/specs/narinfo-concurrent-fetch/spec.mdopenspec/changes/archive/2026-05-28-fix-flaky-narinfo-concurrent-fetch/tasks.mdopenspec/specs/narinfo-concurrent-fetch/spec.mdpkg/cache/cache.gopkg/cache/cache_test.go
✅ Files skipped from review due to trivial changes (6)
- openspec/changes/archive/2026-05-28-fix-flaky-narinfo-concurrent-fetch/.openspec.yaml
- openspec/changes/archive/2026-05-28-fix-flaky-narinfo-concurrent-fetch/tasks.md
- openspec/changes/archive/2026-05-28-fix-flaky-narinfo-concurrent-fetch/design.md
- openspec/specs/narinfo-concurrent-fetch/spec.md
- openspec/changes/archive/2026-05-28-fix-flaky-narinfo-concurrent-fetch/specs/narinfo-concurrent-fetch/spec.md
- openspec/changes/archive/2026-05-28-fix-flaky-narinfo-concurrent-fetch/proposal.md
🚧 Files skipped from review as they are similar to previous changes (1)
- pkg/cache/cache_test.go
#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
hasUpstreamJobonly checkednarJobKey("download:nar:…"), notnarInfoJobKey("download:narinfo:…"). When concurrent goroutines piggybacked on a cold-cache narinfo fetch, they woke onds.doneafter the narinfo was stored in the DB but before the NAR download goroutine had registered its own job key. In that narrow TOCTOU window, bothhasUpstreamJobandisRemoteDownloadInProgressreturned false — causing the purge guard ingetNarInfoFromDatabaseto fire, deleting the narinfo and returningstorage.ErrNotFound→ HTTP 404 to the waiting callers.hasUpstreamJobto checknarInfoJobKeyin addition tonarJobKey. If the narinfo job is still registered inupstreamJobs, the purge guard is suppressed.testGetNarInfoConcurrentColdCacheFetch— 10 goroutines callGetNarInfofor the same hash simultaneously against a cold cache; all must succeed with no error.Closes #1276
Test plan
task fmtexits 0 with no changestask lintexits 0 (GOWORK=off golangci-lint run)GOWORK=off go test -race -count=10 ./pkg/cache/...— all passGOWORK=off go test -race ./...— all packages pass