Skip to content

fix(cache,fsck): reconcile narinfo<->nar_file links (drain-mode unblock + prevention) - #1333

Merged
kalbasit merged 6 commits into
mainfrom
user/wnasreddine/reconcile-narinfo-narfile-links
Jun 5, 2026
Merged

kalbasit merged 6 commits into
mainfrom
user/wnasreddine/reconcile-narinfo-narfile-links

Conversation

@kalbasit

@kalbasit kalbasit commented Jun 5, 2026

Copy link
Copy Markdown
Owner

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_files join link is created in the
narinfo-write path (storeInDatabase), decoupled from the async CDC
chunking that finalizes the chunked nar_file. A rare race (~0.8% of CDC
NARs in a prod snapshot) leaves the chunked nar_file unlinked. That
link is the only way linkedNarinfoNarHash resolves the verification
hash, 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 in fsck.go):

  • A — de-chunk robustness: linkedNarinfoNarHash 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.
  • C — creation-race prevention: checkAndFixNarInfosForNar (runs
    right after chunking completes) reconciles the link via upsert — a
    no-op when it already exists, closing the race at the source.
  • B — fsck safety: repair the missing link (recreate it when the
    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 against
prod with this image.

Test plan

  • task fmt / task lint / task test pass
  • de-chunk of an unlinked chunked NAR succeeds via URL fallback
  • chunking-completion reconciles the missing link
  • fsck repairs an unlinked narinfo with a backing nar_file; still
    deletes one with no backing (-count=3, non-flaky)
  • prod: re-run de-chunk drains all chunked NARs, then exit drain mode

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jun 5, 2026
@dosubot dosubot Bot added bug Something isn't working go Pull requests that update go code labels Jun 5, 2026
@coderabbitai

coderabbitai Bot commented Jun 5, 2026 •

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

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

Changes

Race condition recovery for missing narinfo↔nar_file links

Layer / File(s) Summary
URL-based NarHash fallback for content verification
pkg/cache/cache.go, pkg/cache/migrate_chunks_to_nar_test.go
linkedNarinfoNarHash now accepts a target narURL and falls back to a compression=none narinfo URL lookup when the narinfo_nar_files join is missing. MigrateChunksToNar passes noneURL to enable verification; test verifies de-chunking reconstructs and validates the whole NAR via URL fallback.
Cache fixup reconciliation of missing links
pkg/cache/cache.go, pkg/cache/nondestructive_narinfo_purge_internal_test.go
checkAndFixNarInfosForNar resolves the corresponding nar_file for the provided narURL and upserts missing narinfo_nar_files join rows (OnConflict.Ignore) before running per-narinfo fixups. Test seeds an unlinked finalized chunked NAR and narinfo, then verifies the join row is created.
Fsck repair with URL-based relinking
pkg/ncps/fsck.go, pkg/ncps/fsck_test.go
Adds relinkNarInfoToBackingNarFile which parses narinfo URLs, looks up matching nar_file by hash+query (compression-agnostic), and recreates the join via conflict-ignored insert. fsck --repair now attempts relink before deleting an unlinked narinfo. Tests cover relink-success (link recreated and narinfo preserved) and genuine orphan deletion.

Sequence Diagram(s)

No additional sequence diagrams beyond the hidden review stack artifact.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~65 minutes

Possibly related PRs

  • kalbasit/ncps#1208: Related work on relinking/backfill of narinfo_nar_files using bulk CreateBulk(...).Ignore() patterns.
  • kalbasit/ncps#1301: Earlier changes to MigrateChunksToNar / linkedNarinfoNarHash flow that this PR extends.
  • kalbasit/ncps#1205: Related join-table reconciliation updates for narinfo_nar_files.

Suggested labels

merge-stack

Poem

🐰 I sniff the URL where links went astray,
I upsert lanes where bytes forgot their way,
Fsck hums a tune and cache mends the seam,
Whole NARs hop home, stitched back into the stream,
A rabbit's cheer for tidy data day.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main change: reconciling narinfo<->nar_file links to address both drain-mode blocking and prevent data loss, which are the core issues this PR solves.
Description check ✅ Passed The description is comprehensive and directly related to the changeset, detailing the root cause (race condition in join-link creation), three coordinated fixes across multiple files, and the test plan.
Docstring Coverage ✅ Passed Docstring coverage is 91.67% 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.


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

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

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 win

Reconcile against legacy compressed narinfo links, not only exact narURL matches.

Line 5265 only loads narinfos whose persisted URL already equals narURL.String(). But pullNarInfo deliberately keeps compressed URLs in the DB during CDC first pulls, while the finished nar_file has already been normalized to Compression: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

📥 Commits

Reviewing files that changed from the base of the PR and between 879829c and b551ddd.

📒 Files selected for processing (5)
  • pkg/cache/cache.go
  • pkg/cache/migrate_chunks_to_nar_test.go
  • pkg/cache/nondestructive_narinfo_purge_internal_test.go
  • pkg/ncps/fsck.go
  • pkg/ncps/fsck_test.go

Comment thread pkg/cache/cache.go Resolved
@kalbasit
kalbasit force-pushed the user/wnasreddine/cdc-url-desync-prevention branch from 879829c to 6893f55 Compare June 5, 2026 16:40
@kalbasit
kalbasit force-pushed the user/wnasreddine/reconcile-narinfo-narfile-links branch from 6a73c93 to 6e10b5a Compare June 5, 2026 16:40

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

🧹 Nitpick comments (1)
openspec/changes/reconcile-narinfo-narfile-links/specs/chunks-to-nar-migration/spec.md (1)

5-5: 💤 Low value

Consider 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

📥 Commits

Reviewing files that changed from the base of the PR and between 6a73c93 and 6e10b5a.

📒 Files selected for processing (13)
  • openspec/changes/reconcile-narinfo-narfile-links/.openspec.yaml
  • openspec/changes/reconcile-narinfo-narfile-links/design.md
  • openspec/changes/reconcile-narinfo-narfile-links/proposal.md
  • openspec/changes/reconcile-narinfo-narfile-links/specs/cdc-chunking/spec.md
  • openspec/changes/reconcile-narinfo-narfile-links/specs/cdc-drain-mode/spec.md
  • openspec/changes/reconcile-narinfo-narfile-links/specs/chunks-to-nar-migration/spec.md
  • openspec/changes/reconcile-narinfo-narfile-links/specs/fsck/spec.md
  • openspec/changes/reconcile-narinfo-narfile-links/tasks.md
  • pkg/cache/cache.go
  • pkg/cache/migrate_chunks_to_nar_test.go
  • pkg/cache/nondestructive_narinfo_purge_internal_test.go
  • pkg/ncps/fsck.go
  • pkg/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

@kalbasit
kalbasit force-pushed the user/wnasreddine/cdc-url-desync-prevention branch from 6893f55 to 64d30e0 Compare June 5, 2026 17:37
kalbasit added a commit that referenced this pull request Jun 5, 2026
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]>
@kalbasit
kalbasit force-pushed the user/wnasreddine/reconcile-narinfo-narfile-links branch from 521c632 to 631a7ae Compare June 5, 2026 17:37
@kalbasit
kalbasit force-pushed the user/wnasreddine/cdc-url-desync-prevention branch from 64d30e0 to f114ec1 Compare June 5, 2026 17:59
kalbasit added a commit that referenced this pull request Jun 5, 2026
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]>
@kalbasit
kalbasit force-pushed the user/wnasreddine/reconcile-narinfo-narfile-links branch from 631a7ae to 22e0ae5 Compare June 5, 2026 17:59
@kalbasit
kalbasit force-pushed the user/wnasreddine/cdc-url-desync-prevention branch from f114ec1 to 97a8661 Compare June 5, 2026 19:07
kalbasit added a commit that referenced this pull request Jun 5, 2026
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]>
@kalbasit
kalbasit force-pushed the user/wnasreddine/reconcile-narinfo-narfile-links branch from 22e0ae5 to ae31985 Compare June 5, 2026 19:07
@kalbasit
kalbasit force-pushed the user/wnasreddine/cdc-url-desync-prevention branch from 97a8661 to bbe3526 Compare June 5, 2026 19:08
kalbasit added a commit that referenced this pull request Jun 5, 2026
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]>
@kalbasit
kalbasit force-pushed the user/wnasreddine/reconcile-narinfo-narfile-links branch from ae31985 to c959add Compare June 5, 2026 19:08
@kalbasit
kalbasit force-pushed the user/wnasreddine/cdc-url-desync-prevention branch from bbe3526 to 0e73997 Compare June 5, 2026 19:15
kalbasit added a commit that referenced this pull request Jun 5, 2026
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]>
@kalbasit
kalbasit force-pushed the user/wnasreddine/reconcile-narinfo-narfile-links branch from c959add to 858c27f Compare June 5, 2026 19:15
Base automatically changed from user/wnasreddine/cdc-url-desync-prevention to main June 5, 2026 19:23
kalbasit and others added 6 commits June 5, 2026 19:23
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]>
@kalbasit
kalbasit force-pushed the user/wnasreddine/reconcile-narinfo-narfile-links branch from 858c27f to 0a9975c Compare June 5, 2026 19:23
@kalbasit
kalbasit enabled auto-merge (squash) June 5, 2026 19:23
@kalbasit
kalbasit merged commit 415d552 into main Jun 5, 2026
34 checks passed
@kalbasit
kalbasit deleted the user/wnasreddine/reconcile-narinfo-narfile-links branch June 5, 2026 19:30
kalbasit added a commit that referenced this pull request Jun 5, 2026
…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]>
kalbasit added a commit to bryandph/ncps that referenced this pull request Jun 7, 2026
* 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
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 merge-stack 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