Repository navigation
fix(cache): fall back to chunks when migration races serve - #1324
Conversation
GetNar's TestCDCBackends/.../Mixed_Mode flaked in CI with "error fetching the nar from the store: not found". The cause is a TOCTOU in the read path: when a whole-file NAR is served while CDC is enabled, GetNar triggers a background NAR->chunks migration that deletes the whole file, then synchronously serves from that same store. If the delete wins the race after serveNarFromStorageViaPipe chose the store branch (total_chunks still observed as 0) but before getNarFromStore opens the file, the read 404s even though the NAR is fully available as chunks. Because the migration commits chunks before deleting the whole file, the NAR is always retrievable from chunks at that point. Fix the serve path so a store read that returns ErrNotFound while CDC is enabled and the request is uncompressed falls back to getNarFromChunks. The chunk result is only adopted on success; if chunks are also absent the original store ErrNotFound is preserved, and compressed requests keep returning ErrNotFound so clients fall back upstream. Add deterministic regression tests that reproduce the race via a narStore wrapper, plus coverage for the compressed-request and genuinely-absent edges, and document the race in testCDCMixedMode. Co-Authored-By: Claude Opus 4.8 <[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 (3)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughSummary by CodeRabbit
WalkthroughThis PR fixes a TOCTOU in CDC mixed-mode NAR serving: uncompressed requests that see a whole-file store miss during background migration now fall back to chunk reassembly; compressed requests and genuinely absent NARs preserve not-found. Changes include spec updates, cache fallback logic, and race simulation tests. ChangesCDC TOCTOU Race Fix for NAR Mixed-Mode Serving
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
🚥 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 TOCTOU race condition where a concurrent background migration deletes a whole-file NAR from the store while it is being served. The fix introduces a fallback mechanism in serveNarFromStorageViaPipe to reassemble the NAR from chunks if the whole-file read misses, restricted to uncompressed requests. New regression tests have been added to verify this behavior. The reviewer suggested checking c.isChunkStoreAvailable() instead of c.isCDCEnabled() to ensure the fallback remains functional during drain mode.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
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 3088-3094: The code currently preserves the original
storage.ErrNotFound even when getNarFromChunks returns a different error, hiding
real failures; change the logic in the branch that calls c.getNarFromChunks(ctx,
narURL) so that if chunkErr == nil you set storageSize, storageReader, err =
chunkSize, chunkReader, nil, but if chunkErr != nil then set err = chunkErr
unless errors.Is(chunkErr, storage.ErrNotFound) (in which case keep the original
ErrNotFound); update the branch around c.getNarFromChunks to propagate
non-ErrNotFound chunkErrs instead of swallowing them.
🪄 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: 75d72cbd-2fe0-4d24-8ba8-8d0ee6631c19
📒 Files selected for processing (9)
openspec/changes/archive/2026-06-03-fix-flaky-cdc-mixed-mode-test/.openspec.yamlopenspec/changes/archive/2026-06-03-fix-flaky-cdc-mixed-mode-test/design.mdopenspec/changes/archive/2026-06-03-fix-flaky-cdc-mixed-mode-test/proposal.mdopenspec/changes/archive/2026-06-03-fix-flaky-cdc-mixed-mode-test/specs/cdc-chunking/spec.mdopenspec/changes/archive/2026-06-03-fix-flaky-cdc-mixed-mode-test/tasks.mdopenspec/specs/cdc-chunking/spec.mdpkg/cache/cache.gopkg/cache/cdc_migration_race_internal_test.gopkg/cache/cdc_test.go
Address PR review on the migration-race chunk fallback: - Gate the fallback on isChunkStoreAvailable() instead of isCDCEnabled(). The fallback is a read-path operation and must also apply in drain mode (CDC writes disabled, chunk store still configured), where chunked NARs remain servable. This matches getNarFromChunks' own guard. - Surface genuine chunk-path failures (e.g. DB/storage errors) instead of masking them as the original store not-found, matching how the direct chunk-serve path propagates errors. A miss is detected via both storage.ErrNotFound and an ent not-found result, so a genuinely absent NAR still resolves to the original not-found sentinel. Add a drain-mode regression test; the existing genuinely-absent test guards the miss-detection (both not-found sentinels). Co-Authored-By: Claude Opus 4.8 <[email protected]>
## Summary Fixes the flaky `TestCacheBackends/.../RunLRUCleanupInconsistentNarInfoState` failure in CI ([run 26929993682](https://github.com/kalbasit/ncps/actions/runs/26929993682/job/79447676107)) — `chunk store not initialized, cannot serve NAR from chunks`. The root cause is a TOCTOU on `hasInStore` in `GetNar`. It reads `HasNarInStore` once, then re-evaluates servability via `isServable`, which performs its **own** fresh `HasNarInStore`. When the whole-file NAR lands in the store between those two checks, the first flag is stale (`false`) while the NAR is in fact present. `serveNarFromStorageViaPipe` then computed `serveFromChunks := !hasInStore = true` and routed an uncompressed request to `getNarFromChunks`, which hard-fails when no chunk store is configured. This is the inverse of #1324 (present-at-check, deleted-before-use); here it is absent-at-check, present-before-use. ## Fix - Gate the chunk route on chunk-store availability: `serveFromChunks := !hasInStore && c.isChunkStoreAvailable()`. - When no chunk store exists, an uncompressed request resolves against the whole-file store: a present whole file is served; a genuine absence returns a clean `storage.ErrNotFound`, preserving cache-miss recovery and the upload-only contract. - When a chunk store **is** present the gate reduces to the original `!hasInStore`, so standard CDC and drain-mode serving are byte-identical (the #1324 store→chunks fallback is unchanged). ## Test plan - [x] New deterministic regression test reproduces the exact CI error (RED → GREEN): `pkg/cache/cdc_serve_stale_hasinstore_internal_test.go` - [x] Formerly-flaky `RunLRUCleanupInconsistentNarInfoState` passes 5× under `-race` - [x] `#1324` migration-race tests still pass (no regression) - [x] `task fmt`, `task lint` (0 issues), `task test`, and full `task test:auto` (real Postgres/MySQL/Redis/Garage) pass ## Spec Adds the `cdc-chunking` requirement "Serving a whole-file NAR MUST be resilient to a stale time-of-check store-presence observation" (4 scenarios), and archives the OpenSpec change under `openspec/changes/archive/2026-06-03-fix-flaky-pg-test/`. Co-authored-by: Claude Opus 4.8 <[email protected]>
Summary
Fixes the flaky
TestCDCBackends/.../Mixed_Modefailure seen in CI(e.g. on #1322) —
error fetching the nar from the store: not found.The root cause is a TOCTOU race in the NAR read path. When a whole-file
NAR is served while CDC is enabled,
GetNartriggers a backgroundNAR→chunks migration that deletes the whole file, then synchronously
serves from that same store. If the delete wins the race after
serveNarFromStorageViaPipechose the store branch (total_chunksstill observed as
0) but beforegetNarFromStoreopens the file, theread 404s — even though the NAR is fully available as chunks. In
production this surfaces as spurious 404s on freshly-migrated NARs.
Because the migration commits the chunks before deleting the whole
file, the NAR is always retrievable from chunks at that point. The fix:
when a store read returns
ErrNotFoundwhile CDC is enabled and therequest is uncompressed, fall back to
getNarFromChunks.absent, the original store
ErrNotFoundis preserved (genuinenot-found semantics unchanged).
a
.nar.xzrequest keeps returningErrNotFoundand falls backupstream.
Test plan
narStorewrapper (RED → GREEN; RED reproduced the exact CI error)edges; documented the race in
testCDCMixedModeTestCDCBackends+ new tests pass under-race(repeated runs)task fmt,task lint(0 issues),task test, and fullintegration suite (
task test:auto, real Postgres/MySQL/Redis) passSpec
Adds the
cdc-chunkingrequirement "Serving a whole-file NAR MUST beresilient to a concurrent background migration" (4 scenarios), and
archives the OpenSpec change under
openspec/changes/archive/2026-06-03-fix-flaky-cdc-mixed-mode-test/.