Repository navigation
fix(cache,fsck): reconcile narinfo<->nar_file links (drain-mode unblock + prevention) - #1333
Conversation
|
This change is part of the following stack:
Change managed by git-spice. |
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThis PR adds URL-based NarHash fallback, cache-layer upsert reconciliation, and fsck relinking to recover missing narinfo_nar_files join links caused by async CDC chunk finalization races. ChangesRace condition recovery for missing narinfo↔nar_file links
Sequence Diagram(s)No additional sequence diagrams beyond the hidden review stack artifact. Estimated code review effort🎯 4 (Complex) | ⏱️ ~65 minutes Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Comment |
There was a problem hiding this comment.
Code Review
This pull request addresses a race condition where narinfo_nar_files join links are missing, which can leave chunked NAR files unlinked and cause the cache to get stuck in drain mode. It resolves this by reconciling the missing links right after chunking completes, falling back to URL-based resolution when verifying unlinked NARs, and repairing missing links during fsck instead of deleting valid metadata. The review feedback suggests improving robustness by properly handling transient database errors when resolving the backing NAR file, and ensuring deterministic linking during fsck repairs by prioritizing exact compression matches before falling back to any compression.
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
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
pkg/cache/cache.go (1)
5265-5294:⚠️ Potential issue | 🟠 Major | ⚡ Quick winReconcile against legacy compressed narinfo links, not only exact
narURLmatches.
Line 5265only loads narinfos whose persisted URL already equalsnarURL.String(). ButpullNarInfodeliberately keeps compressed URLs in the DB during CDC first pulls, while the finishednar_filehas already been normalized toCompression:none. If chunking wins that race, this reconciliation sees zero narinfos and never recreates the join, so the narinfo can still end up linked only to the old compressed placeholder row.Possible fix
- nis, err := c.dbClient.Ent().NarInfo.Query(). - Where(entnarinfo.URL(narURL.String())). + nis, err := c.dbClient.Ent().NarInfo.Query(). + Where( + entnarinfo.Or( + entnarinfo.URL(narURL.String()), + entnarinfo.HasNarInfoNarFilesWith( + entnarinfonarfile.HasNarFileWith( + entnarfile.HashEQ(narURL.Hash), + entnarfile.QueryEQ(narURL.Query.Encode()), + ), + ), + ), + ). All(ctx)🤖 Prompt for 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. In `@pkg/cache/cache.go` around lines 5265 - 5294, The query that loads narinfos only matches exact narURL.String(), so if the DB still stores legacy compressed URLs the code finds none and won't recreate the narinfo<->nar_file link; update the fetch to include legacy compressed variants (e.g. Compression:none and the compressed suffixes you accept) by building a list of candidate URLs and using ent's Where with Or/In (e.g. change c.dbClient.Ent().NarInfo.Query().Where(entnarinfo.URL(narURL.String())) to Query().Where(entnarinfo.URLIn(candidateURLs...)) or an Or clause) so the loop considers narinfos persisted with compressed URLs as well and reconciles the join using getNarFileFromDB and Create().SetNarinfoID(...).SetNarFileID(...).OnConflict...Ignore().Exec(ctx).
🤖 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 8149-8166: The lookup only checks the Compression:none URL
(noneURL) and misses raced narinfos saved under the original compressed URL
(narURL), so update the narinfo resolution in the block that calls
c.dbClient.Ent().NarInfo.Query() (the code around noneURL and the First(ctx)
call) to also probe the original narURL (or OR both in a single query) before
giving up; if the noneURL query returns a not-found error, attempt a second
query using narURL.String() (or combine ent narinfo URL equals noneURL OR
narURL) and return that result so MigrateChunksToNar can verify chunked
nar_files persisted under the compressed URL.
---
Outside diff comments:
In `@pkg/cache/cache.go`:
- Around line 5265-5294: The query that loads narinfos only matches exact
narURL.String(), so if the DB still stores legacy compressed URLs the code finds
none and won't recreate the narinfo<->nar_file link; update the fetch to include
legacy compressed variants (e.g. Compression:none and the compressed suffixes
you accept) by building a list of candidate URLs and using ent's Where with
Or/In (e.g. change
c.dbClient.Ent().NarInfo.Query().Where(entnarinfo.URL(narURL.String())) to
Query().Where(entnarinfo.URLIn(candidateURLs...)) or an Or clause) so the loop
considers narinfos persisted with compressed URLs as well and reconciles the
join using getNarFileFromDB and
Create().SetNarinfoID(...).SetNarFileID(...).OnConflict...Ignore().Exec(ctx).
🪄 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: ea8b6fa3-a7f8-49ff-9f07-2d0487d98317
📒 Files selected for processing (5)
pkg/cache/cache.gopkg/cache/migrate_chunks_to_nar_test.gopkg/cache/nondestructive_narinfo_purge_internal_test.gopkg/ncps/fsck.gopkg/ncps/fsck_test.go
879829c to
6893f55
Compare
6a73c93 to
6e10b5a
Compare
There was a problem hiding this comment.
🧹 Nitpick comments (1)
openspec/changes/reconcile-narinfo-narfile-links/specs/chunks-to-nar-migration/spec.md (1)
5-5: 💤 Low valueConsider simplifying the phrasing for clarity.
The phrase "for want of a verification hash" is grammatically correct but could be more direct. Consider using "without a verification hash" or "when no verification hash is available" for clearer technical communication.
✏️ Proposed revision
-When de-chunking a NAR, the system resolves the expected NarHash from the linked narinfo in order to content-verify the reconstruction (verified-or-nothing). When the `narinfo_nar_files` join link is absent — a known race leaves CDC-chunked `nar_file` rows unlinked — the system SHALL fall back to resolving the narinfo by the NAR's `Compression:none` URL (`nar/<hash>.nar`) instead of treating the NAR as un-verifiable and skipping it. Only when no narinfo references the NAR by either the join link or its URL SHALL the de-chunk be skipped for want of a verification hash. +When de-chunking a NAR, the system resolves the expected NarHash from the linked narinfo in order to content-verify the reconstruction (verified-or-nothing). When the `narinfo_nar_files` join link is absent — a known race leaves CDC-chunked `nar_file` rows unlinked — the system SHALL fall back to resolving the narinfo by the NAR's `Compression:none` URL (`nar/<hash>.nar`) instead of treating the NAR as un-verifiable and skipping it. Only when no narinfo references the NAR by either the join link or its URL SHALL the de-chunk be skipped without a verification hash.🤖 Prompt for 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. In `@openspec/changes/reconcile-narinfo-narfile-links/specs/chunks-to-nar-migration/spec.md` at line 5, The sentence ending with "SHALL the de-chunk be skipped for want of a verification hash" is awkward; update that clause in the spec text (the sentence that begins "Only when no narinfo references the NAR by either the join link or its URL SHALL...") to a clearer phrasing such as "SHALL the de-chunk be skipped without a verification hash" or "SHALL the de-chunk be skipped when no verification hash is available" to improve readability and technical clarity.
🤖 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.
Nitpick comments:
In
`@openspec/changes/reconcile-narinfo-narfile-links/specs/chunks-to-nar-migration/spec.md`:
- Line 5: The sentence ending with "SHALL the de-chunk be skipped for want of a
verification hash" is awkward; update that clause in the spec text (the sentence
that begins "Only when no narinfo references the NAR by either the join link or
its URL SHALL...") to a clearer phrasing such as "SHALL the de-chunk be skipped
without a verification hash" or "SHALL the de-chunk be skipped when no
verification hash is available" to improve readability and technical clarity.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: d4c9405b-5317-4a34-ad4e-3f9ee618b030
📒 Files selected for processing (13)
openspec/changes/reconcile-narinfo-narfile-links/.openspec.yamlopenspec/changes/reconcile-narinfo-narfile-links/design.mdopenspec/changes/reconcile-narinfo-narfile-links/proposal.mdopenspec/changes/reconcile-narinfo-narfile-links/specs/cdc-chunking/spec.mdopenspec/changes/reconcile-narinfo-narfile-links/specs/cdc-drain-mode/spec.mdopenspec/changes/reconcile-narinfo-narfile-links/specs/chunks-to-nar-migration/spec.mdopenspec/changes/reconcile-narinfo-narfile-links/specs/fsck/spec.mdopenspec/changes/reconcile-narinfo-narfile-links/tasks.mdpkg/cache/cache.gopkg/cache/migrate_chunks_to_nar_test.gopkg/cache/nondestructive_narinfo_purge_internal_test.gopkg/ncps/fsck.gopkg/ncps/fsck_test.go
✅ Files skipped from review due to trivial changes (5)
- openspec/changes/reconcile-narinfo-narfile-links/design.md
- openspec/changes/reconcile-narinfo-narfile-links/.openspec.yaml
- openspec/changes/reconcile-narinfo-narfile-links/specs/cdc-chunking/spec.md
- openspec/changes/reconcile-narinfo-narfile-links/tasks.md
- openspec/changes/reconcile-narinfo-narfile-links/proposal.md
🚧 Files skipped from review as they are similar to previous changes (6)
- pkg/cache/migrate_chunks_to_nar_test.go
- openspec/changes/reconcile-narinfo-narfile-links/specs/fsck/spec.md
- pkg/cache/nondestructive_narinfo_purge_internal_test.go
- pkg/ncps/fsck_test.go
- pkg/cache/cache.go
- pkg/ncps/fsck.go
6893f55 to
64d30e0
Compare
Addresses PR #1333 review comments: - checkAndFixNarInfosForNar (thread Ha2NI): surface a non-not-found getNarFileFromDB error instead of silently skipping link reconciliation, so a transient DB failure is visible. - relinkNarInfoToBackingNarFile (thread Ha2NL): prefer the nar_file whose compression exactly matches the narinfo URL, falling back to any compression only for CDC residue. Avoids non-deterministic linking when several nar_file rows share a hash with different compressions. Co-Authored-By: Claude Opus 4.8 <[email protected]>
521c632 to
631a7ae
Compare
64d30e0 to
f114ec1
Compare
Addresses PR #1333 review comments: - checkAndFixNarInfosForNar (thread Ha2NI): surface a non-not-found getNarFileFromDB error instead of silently skipping link reconciliation, so a transient DB failure is visible. - relinkNarInfoToBackingNarFile (thread Ha2NL): prefer the nar_file whose compression exactly matches the narinfo URL, falling back to any compression only for CDC residue. Avoids non-deterministic linking when several nar_file rows share a hash with different compressions. Co-Authored-By: Claude Opus 4.8 <[email protected]>
631a7ae to
22e0ae5
Compare
f114ec1 to
97a8661
Compare
Addresses PR #1333 review comments: - checkAndFixNarInfosForNar (thread Ha2NI): surface a non-not-found getNarFileFromDB error instead of silently skipping link reconciliation, so a transient DB failure is visible. - relinkNarInfoToBackingNarFile (thread Ha2NL): prefer the nar_file whose compression exactly matches the narinfo URL, falling back to any compression only for CDC residue. Avoids non-deterministic linking when several nar_file rows share a hash with different compressions. Co-Authored-By: Claude Opus 4.8 <[email protected]>
22e0ae5 to
ae31985
Compare
97a8661 to
bbe3526
Compare
Addresses PR #1333 review comments: - checkAndFixNarInfosForNar (thread Ha2NI): surface a non-not-found getNarFileFromDB error instead of silently skipping link reconciliation, so a transient DB failure is visible. - relinkNarInfoToBackingNarFile (thread Ha2NL): prefer the nar_file whose compression exactly matches the narinfo URL, falling back to any compression only for CDC residue. Avoids non-deterministic linking when several nar_file rows share a hash with different compressions. Co-Authored-By: Claude Opus 4.8 <[email protected]>
ae31985 to
c959add
Compare
bbe3526 to
0e73997
Compare
Addresses PR #1333 review comments: - checkAndFixNarInfosForNar (thread Ha2NI): surface a non-not-found getNarFileFromDB error instead of silently skipping link reconciliation, so a transient DB failure is visible. - relinkNarInfoToBackingNarFile (thread Ha2NL): prefer the nar_file whose compression exactly matches the narinfo URL, falling back to any compression only for CDC residue. Avoids non-deterministic linking when several nar_file rows share a hash with different compressions. Co-Authored-By: Claude Opus 4.8 <[email protected]>
c959add to
858c27f
Compare
The narinfo_nar_files join link is created in the narinfo-write path (storeInDatabase), decoupled from the async CDC chunking that finalizes the chunked nar_file. In a rare race the chunked nar_file ends up with no join link, which had two consequences: the de-chunk pass skipped it forever (ErrNoNarHashToVerify), keeping the cache stuck in drain mode; and fsck would later delete the (valid, reachable) narinfo. ~0.8% of CDC NARs in a production snapshot were affected. Two defenses: - De-chunk robustness: linkedNarinfoNarHash now falls back to resolving the narinfo by the NAR's Compression:none URL when no join link exists, so an unlinked chunked NAR is still content-verified and drained instead of skipped. - Creation-race prevention: checkAndFixNarInfosForNar (invoked right after chunking completes) now reconciles the link, upserting it for every narinfo whose URL references the finalized nar_file. The upsert is a no-op when the link already exists (the common case), so it closes the race without changing steady-state behavior. Co-Authored-By: Claude Opus 4.8 <[email protected]>
fsck classified a narinfo with no narinfo_nar_files link as a "narinfo without nar_file" and DELETED it. But a known CDC race leaves valid, reachable narinfos unlinked from an existing nar_file (~0.8% of CDC NARs in a production snapshot, 2333 in prod) -- deleting those destroys live metadata and orphans the NAR. Before deleting, repairFsckIssues now calls relinkNarInfoToBackingNarFile, which looks up the nar_file the narinfo's URL references (by hash+query, any compression) and recreates the missing link when found. Only a narinfo with no backing nar_file anywhere is still deleted, so genuine orphans are reclaimed as before. Co-Authored-By: Claude Opus 4.8 <[email protected]>
OpenSpec change documenting the narinfo<->nar_file link reconciliation fixes: spec deltas for chunks-to-nar-migration (de-chunk URL fallback), fsck (repair-not-delete), cdc-chunking (reconcile link on completion), and cdc-drain-mode (drain reachable for unlinked NARs), plus proposal, design, and tasks. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Drain mode is not exited by removing chunk-store config; initCDCDrainMode clears the stored CDC config and skips chunk-store init at boot once the chunked count is zero. Fix the cdc-drain-mode scenario and the operational task to reflect the auto-completion. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Addresses PR #1333 review comments: - checkAndFixNarInfosForNar (thread Ha2NI): surface a non-not-found getNarFileFromDB error instead of silently skipping link reconciliation, so a transient DB failure is visible. - relinkNarInfoToBackingNarFile (thread Ha2NL): prefer the nar_file whose compression exactly matches the narinfo URL, falling back to any compression only for CDC residue. Avoids non-deterministic linking when several nar_file rows share a hash with different compressions. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Sync the chunks-to-nar-migration, fsck, cdc-chunking, and cdc-drain-mode deltas into openspec/specs/ and move the change to the archive. (--no-validate: existing specs predate strict SHALL/MUST validation.) Co-Authored-By: Claude Opus 4.8 <[email protected]>
858c27f to
0a9975c
Compare
…Rs) (#1334) ## Summary Stacked on #1333. Makes `migrate-chunks-to-nar` always drive the chunked count to zero so CDC drain auto-completes without manual SQL, and adds an fsck residue-repair safety net. Three production failure classes (kept un-purged as a real-corruption fixture): 1. ~112 chunked NARs whose only NarHash-bearing narinfo advertises a different-compression URL (`.nar.xz`) than the bare `nar/<H>.nar`, so the verify-hash resolver misses and **skips** them. 2. De-chunking such a NAR to none/whole without normalizing its narinfo URL recreates the `.nar.xz` ≠ none/whole 404. 3. ~4 NARs whose reconstruction hard-fails are counted `failed` and left chunked. Code changes (proposal/design/specs in `openspec/changes/`): - **(A)** resolve the verify NarHash by NAR hash from any referencing narinfo, not just the exact none URL; - **(B)** normalize the narinfo URL to none on successful de-chunk; - **(C)** purge-on-unverifiable (no NarHash / hard reconstruction fail) instead of skip/fail, so the pass always reaches `chunked = 0`; - **(D)** an fsck repair pass that relinks/normalizes/purges chunked-NAR residue. This PR currently contains the OpenSpec proposal only; implementation follows (validated against the real production stragglers and the CDC-lifecycle e2e tests). ## Test plan - [ ] TDD fixtures per failure class (`.nar.xz`-URL narinfo, no-NarHash, corrupt chunks) - [ ] full pass over a mixed fixture leaves `chunked = 0` - [ ] deploy + run against the real 116 stragglers; drain auto-completes --------- Co-authored-by: Claude Opus 4.8 <[email protected]>
* origin/main: fix(cdc): heal orphaned mid-chunking NAR state via migration-lock liveness (kalbasit#1317) chore(deps): update codecov/codecov-action action to v7 (kalbasit#1340) feat(fsck): reclaim CDC chunked-NAR residue (grace-period mark-then-purge) (kalbasit#1335) fix(ent): stop sqlite phantom narinfos/nar_files rebuild (kalbasit#1339) chore: update flake.lock and run go mod tidy (kalbasit#1338) fix(deps): update module github.com/mattn/go-sqlite3 to v1.14.45 (kalbasit#1336) fix(cache,fsck): self-completing CDC drain (de-chunk never strands NARs) (kalbasit#1334) fix(cache,fsck): reconcile narinfo<->nar_file links (drain-mode unblock + prevention) (kalbasit#1333) fix(cache): close the CDC url=none/xz-NAR desync (prevention + repair) (kalbasit#1332) fix(cache): durable-bytes marker for /upload reference presence (kalbasit#1330) fix(cache): non-destructive narinfo purge on root path (kalbasit#1326) # Conflicts: # migrations/mysql/atlas.sum # migrations/postgres/atlas.sum # migrations/sqlite/atlas.sum # pkg/cache/cache.go
Summary
Stacked on #1332. Roots out the cause of the cache being stuck in CDC
drain mode (2,499 chunked NARs the de-chunk pass silently skipped),
and removes a related fsck data-loss hazard.
Root cause: the
narinfo_nar_filesjoin link is created in thenarinfo-write path (
storeInDatabase), decoupled from the async CDCchunking that finalizes the chunked
nar_file. A rare race (~0.8% of CDCNARs in a prod snapshot) leaves the chunked
nar_fileunlinked. Thatlink is the only way
linkedNarinfoNarHashresolves the verificationhash, so de-chunk skipped every unlinked NAR (
ErrNoNarHashToVerify) →drain never exits. Worse, fsck classified those valid, reachable
narinfos as orphans and deleted them.
Three fixes (A+C in
cache.go, B infsck.go):linkedNarinfoNarHashfalls back toresolving the narinfo by the NAR's
Compression:noneURL when no joinlink exists, so an unlinked chunked NAR is still content-verified and
drained.
checkAndFixNarInfosForNar(runsright after chunking completes) reconciles the link via upsert — a
no-op when it already exists, closing the race at the source.
nar_file the URL references is present) instead of deleting the
narinfo; only genuine orphans are still reclaimed.
A follow-up data remediation (backfill/repair the existing 2,499, re-run
migrate-chunks-to-nar, exit drain) is performed operationally againstprod with this image.
Test plan
task fmt/task lint/task testpassdeletes one with no backing (
-count=3, non-flaky)