Skip to content

fix(cache): prevent spurious narinfo purge under concurrent fetch - #1279

Merged
kalbasit merged 2 commits into
mainfrom
user/wnasreddine/fix-flaky-tests
May 28, 2026
Merged

kalbasit merged 2 commits into
mainfrom
user/wnasreddine/fix-flaky-tests

Conversation

@kalbasit

@kalbasit kalbasit commented May 28, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • Root cause: hasUpstreamJob only checked narJobKey ("download:nar:…"), not narInfoJobKey ("download:narinfo:…"). When concurrent goroutines piggybacked on a cold-cache narinfo fetch, they woke on ds.done after the narinfo was stored in the DB but before the NAR download goroutine had registered its own job key. In that narrow TOCTOU 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 the waiting callers.
  • Fix: Extend hasUpstreamJob to check narInfoJobKey in addition to narJobKey. If the narinfo job is still registered in upstreamJobs, the purge guard is suppressed.
  • Test: Add testGetNarInfoConcurrentColdCacheFetch — 10 goroutines call GetNarInfo for the same hash simultaneously against a cold cache; all must succeed with no error.

Closes #1276

Test plan

  • task fmt exits 0 with no changes
  • task lint exits 0 (GOWORK=off golangci-lint run)
  • GOWORK=off go test -race -count=10 ./pkg/cache/... — all pass
  • GOWORK=off go test -race ./... — all packages pass

@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

📝 Walkthrough

Summary by CodeRabbit

  • Bug Fixes

    • Fixed a race condition in concurrent narinfo fetches that could cause spurious 404 errors when multiple requests accessed the same content hash simultaneously during cold-cache scenarios.
  • Tests

    • Added a concurrent cold-cache test to verify multiple simultaneous requests for the same narinfo hash complete successfully without errors.

Walkthrough

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

Changes

Concurrent Narinfo Fetch Fix

Layer / File(s) Summary
Specification and problem documentation
openspec/specs/narinfo-concurrent-fetch/spec.md, openspec/changes/archive/2026-05-28-fix-flaky-narinfo-concurrent-fetch/design.md, openspec/changes/archive/2026-05-28-fix-flaky-narinfo-concurrent-fetch/proposal.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/tasks.md, openspec/changes/archive/2026-05-28-fix-flaky-narinfo-concurrent-fetch/.openspec.yaml
Adds OpenSpec metadata, a design doc describing the TOCTOU purge-guard race, a proposal and tasks checklist, and a formal spec with scenarios that prevent spurious 404s under concurrent narinfo/NAR fetches.
Purge-guard TOCTOU mitigation
pkg/cache/cache.go
Adds a second verification step inside getNarInfoFromDatabase: if NAR appears missing and no upstream job is observed, re-check HasNarInStore and then HasNarInChunks before deciding to purge; return narinfo if found on recheck.
Concurrent cold-cache test
pkg/cache/cache_test.go
Adds testGetNarInfoConcurrentColdCacheFetch and registers it in the cache test suite: launches 10 concurrent GetNarInfo calls for the same hash against a cold cache and asserts no errors and non-nil narinfo results for all goroutines.

Sequence Diagram

sequenceDiagram
  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
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • kalbasit/ncps#1251: Overlapping cache-related changes, notably around narinfo purge/streaming safeguards in pkg/cache.
  • kalbasit/ncps#1275: Related adjustments to purge behavior that make purgeNarInfo tolerant of storage.ErrNotFound, addressing similar spurious-delete symptoms.

🐰
I nibbled at a race of time,
A purge that struck before the sign;
A double-check, a careful peep —
Now narinfos wake from sleep.
Hooray: no more 404 whines!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'fix(cache): prevent spurious narinfo purge under concurrent fetch' directly and clearly summarizes the main change: fixing a cache bug that causes spurious narinfo purges during concurrent fetches.
Description check ✅ Passed The description comprehensively explains the root cause, the fix applied, the test added, and the test plan executed, all of which relate directly to the changeset.
Linked Issues check ✅ Passed The PR fully addresses issue #1276: it fixes the TOCTOU race in narinfo fetch-and-store, prevents spurious 404s during concurrent requests, adds a regression test, and restores reliable test passing.
Out of Scope Changes check ✅ Passed All changes are within scope: documentation (design, proposal, spec, tasks) and code changes (cache logic and test) directly target the concurrent narinfo fetch bug from issue #1276.

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

Comment thread pkg/cache/cache.go Resolved
Comment thread pkg/cache/cache_test.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: 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

📥 Commits

Reviewing files that changed from the base of the PR and between 1af986e and 7e03d66.

📒 Files selected for processing (8)
  • openspec/changes/archive/2026-05-28-fix-flaky-narinfo-concurrent-fetch/.openspec.yaml
  • openspec/changes/archive/2026-05-28-fix-flaky-narinfo-concurrent-fetch/design.md
  • openspec/changes/archive/2026-05-28-fix-flaky-narinfo-concurrent-fetch/proposal.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/tasks.md
  • openspec/specs/narinfo-concurrent-fetch/spec.md
  • pkg/cache/cache.go
  • pkg/cache/cache_test.go

kalbasit and others added 2 commits May 28, 2026 15:26
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]>
@kalbasit
kalbasit force-pushed the user/wnasreddine/fix-flaky-tests branch from 281d2b8 to cce2316 Compare May 28, 2026 22:27

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7e03d66 and cce2316.

📒 Files selected for processing (8)
  • openspec/changes/archive/2026-05-28-fix-flaky-narinfo-concurrent-fetch/.openspec.yaml
  • openspec/changes/archive/2026-05-28-fix-flaky-narinfo-concurrent-fetch/design.md
  • openspec/changes/archive/2026-05-28-fix-flaky-narinfo-concurrent-fetch/proposal.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/tasks.md
  • openspec/specs/narinfo-concurrent-fetch/spec.md
  • pkg/cache/cache.go
  • pkg/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

Comment thread pkg/cache/cache.go Resolved
@kalbasit
kalbasit merged commit 8d4531e into main May 28, 2026
19 checks passed
@kalbasit
kalbasit deleted the user/wnasreddine/fix-flaky-tests branch May 28, 2026 22:44
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 size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Flaky test: TestGetNar_NixServeUpstream/nar_served_with_zstd_transparent_encoding — narinfo returns 404 under parallel subtest load

1 participant