Skip to content

fix(cache): fall back to chunks when migration races serve - #1324

Merged
kalbasit merged 2 commits into
mainfrom
user/wnasreddine/fix-flaky-pg-test
Jun 4, 2026
Merged

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

Conversation

@kalbasit

@kalbasit kalbasit commented Jun 4, 2026

Copy link
Copy Markdown
Owner

Summary

Fixes the flaky TestCDCBackends/.../Mixed_Mode failure 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, 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. 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 ErrNotFound while CDC is enabled and the
request is uncompressed, fall back to getNarFromChunks.

  • The chunk result is adopted only on success; if chunks are also
    absent, the original store ErrNotFound is preserved (genuine
    not-found semantics unchanged).
  • Compressed requests are excluded — chunks are stored uncompressed, so
    a .nar.xz request keeps returning ErrNotFound and falls back
    upstream.

Test plan

  • New deterministic regression test reproduces the race via a
    narStore wrapper (RED → GREEN; RED reproduced the exact CI error)
  • Added coverage for the compressed-request and genuinely-absent
    edges; documented the race in testCDCMixedMode
  • TestCDCBackends + new tests pass under -race (repeated runs)
  • task fmt, task lint (0 issues), task test, and full
    integration suite (task test:auto, real Postgres/MySQL/Redis) pass

Spec

Adds the cdc-chunking requirement "Serving a whole-file NAR MUST be
resilient 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/.

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

kalbasit commented Jun 4, 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 Jun 4, 2026
@coderabbitai

coderabbitai Bot commented Jun 4, 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: 6b960196-9116-4c66-b959-20396c086a08

📥 Commits

Reviewing files that changed from the base of the PR and between c55c12f and 96f7c1f.

📒 Files selected for processing (3)
  • openspec/specs/cdc-chunking/spec.md
  • pkg/cache/cache.go
  • pkg/cache/cdc_migration_race_internal_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • pkg/cache/cache.go
  • openspec/specs/cdc-chunking/spec.md

📝 Walkthrough

Summary by CodeRabbit

  • Bug Fixes

    • Fixed intermittent CI failures from a TOCTOU race: uncompressed NAR requests now fall back to chunk reassembly when a whole-file read transiently reports not-found, avoiding spurious not-found errors.
  • Documentation / Specs

    • Added design, proposal, spec, and task guidance defining the fallback behavior, scenarios, and migration considerations.
  • Tests

    • Added deterministic race-oriented tests and hardened mixed-mode tests to validate fallback and compressed-request behavior.

Walkthrough

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

Changes

CDC TOCTOU Race Fix for NAR Mixed-Mode Serving

Layer / File(s) Summary
Problem and Decision Capture
openspec/changes/archive/2026-06-03-fix-flaky-cdc-mixed-mode-test/{proposal.md, design.md, tasks.md, .openspec.yaml}
Proposal, design, tasks, and metadata document the TOCTOU race and the decision: on uncompressed CDC requests, if whole-file store read returns storage.ErrNotFound, retry via chunk reassembly; includes test hardening and tasks.
CDC Specification and Race-Resilience Requirements
openspec/changes/archive/2026-06-03-fix-flaky-cdc-mixed-mode-test/specs/cdc-chunking/spec.md, openspec/specs/cdc-chunking/spec.md
Spec updates require that uncompressed whole-file serves fallback to chunks if deleted mid-serve; compressed requests and genuinely absent NARs preserve storage.ErrNotFound. Multiple scenarios added.
Cache Serving Fallback Implementation
pkg/cache/cache.go
serveNarFromStorageViaPipe adds a guarded recovery: on storage.ErrNotFound for CompressionTypeNone and when chunk store is available, attempt getNarFromChunks; only suppress original not-found when chunk reassembly succeeds; surface other chunk errors.
Race Condition Test Harness and Scenarios
pkg/cache/cdc_migration_race_internal_test.go
Adds migrationRaceNarStore, raceTestCache, and four tests that simulate the TOCTOU window: fallback-to-chunks success, compressed-request still not found, genuinely absent returns not found, and drain-mode fallback.
Existing Test Documentation Update
pkg/cache/cdc_test.go
Adds clarifying comments in testCDCMixedMode about the potential race between whole-file retrieval and background migration and the expected deterministic success.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • kalbasit/ncps#1207: Touches the uncompressed chunk reassembly path used by this PR's fallback.
  • kalbasit/ncps#1319: Hardens chunk-path completeness checks that interact with fallback reassembly semantics.
  • kalbasit/ncps#1255: Also modifies serveNarFromStorageViaPipe decision logic around CompressionTypeNone and storage.ErrNotFound.

🐰 A rabbit scribbles in the codepile small,
A race that made flaky tests fall.
With chunks as a ladder when whole files drop,
The cache hums steady — no missed stop.
Hoppity joy, CI sings, tests stand tall.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title 'fix(cache): fall back to chunks when migration races serve' accurately summarizes the main change—adding fallback logic when CDC migration races with NAR serving.
Description check ✅ Passed The description is directly related to the changeset, explaining the TOCTOU race issue, the fix implementation, test coverage, and spec updates.
Docstring Coverage ✅ Passed Docstring coverage is 83.33% which is sufficient. The required threshold is 80.00%.
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 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.

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

📥 Commits

Reviewing files that changed from the base of the PR and between ca03c2c and c55c12f.

📒 Files selected for processing (9)
  • openspec/changes/archive/2026-06-03-fix-flaky-cdc-mixed-mode-test/.openspec.yaml
  • openspec/changes/archive/2026-06-03-fix-flaky-cdc-mixed-mode-test/design.md
  • openspec/changes/archive/2026-06-03-fix-flaky-cdc-mixed-mode-test/proposal.md
  • openspec/changes/archive/2026-06-03-fix-flaky-cdc-mixed-mode-test/specs/cdc-chunking/spec.md
  • openspec/changes/archive/2026-06-03-fix-flaky-cdc-mixed-mode-test/tasks.md
  • openspec/specs/cdc-chunking/spec.md
  • pkg/cache/cache.go
  • pkg/cache/cdc_migration_race_internal_test.go
  • pkg/cache/cdc_test.go

Comment thread pkg/cache/cache.go Resolved
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]>
@kalbasit
kalbasit enabled auto-merge (squash) June 4, 2026 03:52
@kalbasit
kalbasit merged commit 4f8ad70 into main Jun 4, 2026
34 checks passed
@kalbasit
kalbasit deleted the user/wnasreddine/fix-flaky-pg-test branch June 4, 2026 03:58
kalbasit added a commit that referenced this pull request Jun 4, 2026
## 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]>
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.

1 participant