Skip to content

fix(cache,fsck): self-completing CDC drain (de-chunk never strands NARs) - #1334

Merged
kalbasit merged 5 commits into
mainfrom
user/wnasreddine/self-completing-cdc-drain
Jun 5, 2026
Merged

kalbasit merged 5 commits into
mainfrom
user/wnasreddine/self-completing-cdc-drain

Conversation

@kalbasit

@kalbasit kalbasit commented Jun 5, 2026

Copy link
Copy Markdown
Owner

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

@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. documentation Improvements or additions to documentation labels Jun 5, 2026
@coderabbitai

coderabbitai Bot commented Jun 5, 2026 •

Copy link
Copy Markdown

Complex PR? Review this PR in Change Stack to move by importance, not file order.

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 implements self-completing CDC drain by extending migrate-chunks-to-nar to de-chunk or purge every chunked NAR, normalize narinfo URLs to Compression:none form, and resolve NarHash via join-then-NAR-hash-prefix fallback so drain always reaches zero chunked rows and auto-completes without manual intervention.

Changes

Self-Completing CDC Drain Feature

Layer / File(s) Summary
OpenSpec Requirements, Design, and Acceptance Docs
openspec/changes/archive/2026-06-05-self-completing-cdc-drain/, openspec/specs/cdc-chunking/spec.md, openspec/specs/cdc-drain-mode/spec.md, openspec/specs/chunks-to-nar-migration/spec.md
Adds OpenSpec metadata and documents proposal (three observed failure modes), design (NarHash resolution, narinfo normalization, purge-on-unverifiable), archive specs and tasks (de-chunk pass implementation, test validation strategy), and main spec updates across cdc-chunking, cdc-drain-mode, and chunks-to-nar-migration requiring content verification before commit, consistent narinfo URL advertising, purge-driven residue cleanup, and zero-chunked auto-completion guarantee.
Cache: NarHash Resolution and Narinfo Normalization
pkg/cache/cache.go, pkg/cache/migrate_chunks_to_nar_test.go
MigrateChunksToNar flip transaction now normalizes all narinfo rows referencing the NAR to the Compression:none URL form, sets compression to none, and clears FileHash/FileSize for consistency. linkedNarinfoNarHash resolves verification NarHash by preferring join-linked narinfo with NarHash set, then falling back to any narinfo whose URL starts with nar/<hash>. prefix. Unit tests cover narinfo normalization when linked narinfo advertises .nar.xz URL and de-chunking via URL-derived NarHash when join link is missing.
ncps: Error Handling Consolidation and Purge-on-Unverifiable
pkg/ncps/migrate_chunks_to_nar.go, pkg/ncps/migrate_chunks_to_nar_test.go
Consolidates migrate-chunks-to-nar per-NAR error handling into unified err != nil path that logs warning, invokes PurgeChunkedNar, and records Purged/Skipped/Failure based on purge outcome; context cancellations and deadline-exceeded errors are handled separately as Failure without purging. CLI integration test verifies unverifiable chunked NARs (missing NarHash) are purged so drain completes with zero chunked rows.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • kalbasit/ncps#1301: Both PRs modify the migrate-chunks-to-nar implementation—this PR's Cache.MigrateChunksToNar/linkedNarinfoNarHash URL and hash verification refinements build on the reverse CDC migration introduced in #1301.
  • kalbasit/ncps#1333: Both PRs modify pkg/cache/cache.go's linkedNarinfoNarHash and MigrateChunksToNar de-chunk verification to resolve NarHash using Compression:none/nar/<H>.nar URL fallback when narinfo_nar_files links are missing.
  • kalbasit/ncps#1316: Both PRs modify migrate-chunks-to-nar to purge unrecoverable chunked NARs via Cache.PurgeChunkedNar on de-chunk verification failures and extend related purge-driven test and error-handling logic.

Suggested labels

bug, go

🐰 Bunny's Ballad of the Drained CDC

Chunks once stuck now flow like streams,
Normalized URLs fulfill the dreams,
NarHash verified, then purged with care,
Zero rows left—drain's answered prayer!
Hops away victorious 🌙✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 75.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 clearly and concisely summarizes the main change: ensuring CDC drain auto-completes by preventing chunked NARs from being stranded during de-chunking.
Description check ✅ Passed The description thoroughly explains the problem (three production failure classes), proposed solutions (A-D), and testing strategy, all directly related to the changeset.
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 introduces an OpenSpec design and specification to ensure that the CDC de-chunking migration successfully drives the chunked NAR count to zero, allowing drain mode to auto-complete. It addresses issues with unresolvable verification hashes, inconsistent narinfo URLs, and hard reconstruction failures by resolving hashes from any referencing narinfo, normalizing URLs to 'Compression:none' on de-chunk, purging un-verifiable NARs, and adding an fsck repair pass. The reviewer feedback is highly constructive, recommending that the database query for the NAR hash use direct indexing on nar_hash = H instead of an inefficient LIKE pattern, and that FileSize also be set to null (or 0) during normalization to comply with cache validation rules. All review comments are valid and should be addressed.

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.

@kalbasit
kalbasit force-pushed the user/wnasreddine/self-completing-cdc-drain branch from 7cac91f to 4abe213 Compare June 5, 2026 18:19

@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

🧹 Nitpick comments (6)
openspec/changes/self-completing-cdc-drain/specs/fsck/spec.md (1)

13-18: ⚡ Quick win

Consider adding a scenario for the corrupt-chunks case.

The requirement (line 5) mentions two un-de-chunkable conditions: "no narinfo carries a resolvable NarHash" (covered by this scenario) and "the chunks are missing/corrupt". While scenario 1 implicitly excludes corrupt chunks by requiring a "valid NarHash", adding an explicit third scenario would improve completeness:

#### Scenario: fsck purges a chunked NAR with corrupt chunks

- **GIVEN** a chunked `nar_file` with a resolvable NarHash but missing or corrupt chunks
- **WHEN** `fsck --repair` runs
- **THEN** it SHALL purge the chunked `nar_file` (because verification fails)
- **AND** SHALL NOT leave it chunked

This would make the specification more explicit about all failure modes mentioned in the requirement.

🤖 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/self-completing-cdc-drain/specs/fsck/spec.md` around lines
13 - 18, Add an explicit scenario for corrupt/missing chunks: create a new
scenario titled like "Scenario: fsck purges a chunked NAR with corrupt chunks"
that mirrors the existing scenario for un-de-chunkable NARs but sets up a
chunked `nar_file` where a resolvable `NarHash` exists in `narinfo` yet one or
more chunks are missing/corrupt, invoke `fsck --repair`, and assert that fsck
purges the chunked `nar_file` and does not leave it chunked; update the spec
around the fsck requirement text to reference this new scenario so both failure
modes (no resolvable `NarHash` and corrupt/missing chunks) are explicitly
covered.
openspec/changes/self-completing-cdc-drain/specs/chunks-to-nar-migration/spec.md (1)

30-39: ⚡ Quick win

Consider clarifying narinfo cardinality in the scenario.

The requirement (line 32) states "every narinfo referencing that NAR" (plural), implying multiple narinfo records may reference the same NAR with different compressions. However, the scenario (line 36) uses "a chunked NAR whose narinfo" (singular), which could create ambiguity about whether the implementation should handle one-to-many relationships.

Consider either:

  • Expanding the scenario to explicitly cover the case where multiple narinfo records (e.g., .nar.xz and .nar.zst) reference the same NAR, or
  • Adding a note clarifying that the scenario covers the simplest case and the requirement handles the general case.

This would improve clarity for implementers and test authors.

🤖 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/self-completing-cdc-drain/specs/chunks-to-nar-migration/spec.md`
around lines 30 - 39, The scenario text under "Requirement: De-chunking MUST
normalize the narinfo URL to none" is ambiguous about narinfo cardinality;
update the Scenario "A de-chunked NAR's narinfo advertises none" to explicitly
state whether it covers one or many narinfo records and add at least one
sub-scenario showing multiple narinfo variants (e.g., both `nar/<H>.nar.xz` and
`nar/<H>.nar.zst`) referencing the same NAR, and assert that after de-chunking
all such narinfo entries are updated to `nar/<H>.nar` with Compression none so
it clearly matches the general requirement that "every narinfo referencing that
NAR" must be normalized.
openspec/changes/self-completing-cdc-drain/tasks.md (4)

13-14: ⚡ Quick win

Define the "purge" operation scope.

Tasks 3.1 and 3.2 reference "purge" without specifying what should be deleted. Based on the fsck repair pattern in Context snippet 3, a full purge likely includes:

  1. Delete the chunked nar_file record
  2. Delete associated nar_file_chunk links
  3. Delete newly-orphaned narinfo records (via narinfo_nar_files cascade)
  4. Delete newly-orphaned chunk records and storage objects

Consider adding a brief definition or cross-reference to avoid implementation ambiguity:

-- [ ] 3.1 When no NarHash is resolvable from any narinfo, purge the chunked nar_file instead of returning the skip sentinel
+- [ ] 3.1 When no NarHash is resolvable from any narinfo, purge the chunked nar_file (delete nar_file, chunk links, orphaned narinfo/chunk records) instead of returning the skip sentinel
🤖 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/self-completing-cdc-drain/tasks.md` around lines 13 - 14,
Tasks 3.1 and 3.2 use the ambiguous term "purge"; define the purge operation so
implementers of migrate_chunks_to_nar.go and any logic that handles missing
NarHash know exactly what to remove: delete the nar_file record for the chunked
object, delete all associated nar_file_chunk links, remove any now-orphaned
narinfo rows (relying on narinfo_nar_files cascade where applicable), and delete
any newly-orphaned chunk records and their backing storage objects; add this
brief definition as a comment or cross-reference in the tasks and in the code
paths in migrate_chunks_to_nar.go that perform hard reconstruction failure
handling so the implementation removes those four categories atomically or in a
documented order.

8-8: ⚡ Quick win

Specify how to locate "every referencing narinfo."

Task 2.1 instructs updating "every referencing narinfo" but does not specify the query strategy. The implementation should either:

  1. Query via the narinfo_nar_files join table (all narinfo records linked to the nar_file ID), or
  2. Query by NAR hash in the narinfo URL field (parsing and matching).

The join-table approach is more reliable. Consider clarifying:

-- [ ] 2.1 After the record flip in `MigrateChunksToNar`, update every referencing narinfo to `nar/<H>.nar` / Compression none / FileHash null
+- [ ] 2.1 After the record flip in `MigrateChunksToNar`, query all narinfo records via `narinfo_nar_files` join (or by NAR hash in URL field) and update each to `nar/<H>.nar` / Compression none / FileHash null

This prevents ambiguity about the implementation approach.

🤖 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/self-completing-cdc-drain/tasks.md` at line 8, The task
"After the record flip in MigrateChunksToNar" is ambiguous about locating "every
referencing narinfo" — use the narinfo_nar_files join table to reliably find all
narinfo rows linked to the nar_file ID and update those narinfo records (set url
to "nar/<H>.nar", compression to "none", and filehash to null) in the
MigrateChunksToNar flow; if you must support the alternate approach also include
a fallback that parses the existing narinfo.url for a matching NAR hash, but
prefer and document the join-table query against narinfo_nar_files and the
nar_file ID as the canonical method.

19-19: ⚡ Quick win

Break down the "relink+normalize" action into sub-steps.

Task 4.1 combines "relink+normalize" into a single action, but these are distinct operations that may have different preconditions. Consider clarifying the sequence:

-- [ ] 4.1 Add an fsck check + `--repair` action for chunked nar_files: relink+normalize when a valid NarHash exists, purge otherwise
+- [ ] 4.1 Add an fsck check + `--repair` action for chunked nar_files (total_chunks > 0): (a) if a valid NarHash is resolvable, relink missing narinfo_nar_files joins and normalize narinfo URLs to Compression:none; (b) otherwise, purge the nar_file and orphaned records

This makes the two-phase logic (validate → relink+normalize or purge) and the selection criteria explicit.

🤖 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/self-completing-cdc-drain/tasks.md` at line 19, Split task
"4.1 Add an fsck check + `--repair` action for chunked nar_files:
relink+normalize when a valid NarHash exists, purge otherwise" into explicit
sub-steps: 1) Validate: run fsck to detect chunked nar_files and verify NarHash;
2) If NarHash is valid, perform "relink" (recreate/repair chunk links and update
metadata) as a distinct step, then perform "normalize" (canonicalize file
layout/metadata) as a separate step only after successful relink; 3) If NarHash
is invalid or missing, perform "purge" (safe removal) with criteria for when
purge is allowed; and 4) document preconditions, failure handling, and selection
criteria for choosing relink vs purge in the task description so the two-phase
logic (validate → relink then normalize, or validate → purge) is explicit.
Reference the task label "4.1", the action names "relink", "normalize", "purge",
and the `--repair` flag in the updated description.

1-26: 💤 Low value

Consider adding cross-references to detailed spec files.

The tasks reference the high-level changes (A, B, C, D) from the PR objectives, but don't link to the detailed spec files in the same directory tree (e.g., specs/chunks-to-nar-migration/spec.md, specs/fsck/spec.md). Adding these references would improve traceability for implementers who need to understand the full requirements:

## 1. De-chunk: resolve NarHash by NAR hash (A)
See: [specs/chunks-to-nar-migration/spec.md](specs/chunks-to-nar-migration/spec.md)

...

This is optional but would strengthen the connection between work items and their specifications.

🤖 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/self-completing-cdc-drain/tasks.md` around lines 1 - 26, The
task list lacks links to the detailed specs; update the headings in
openspec/changes/self-completing-cdc-drain/tasks.md (for example the sections
"1. De-chunk: resolve NarHash by NAR hash (A)", "2. De-chunk: normalize narinfo
URL on de-chunk (B)", "3. De-chunk: purge-on-unverifiable (C)", and "4. fsck
residue repair (D)") to include direct cross-references to the matching spec
files (e.g., specs/chunks-to-nar-migration/spec.md and specs/fsck/spec.md),
adding a short "See:" line under each numbered section that points to the
precise spec path so implementers can jump from the task entry to the full
requirements.
🤖 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/self-completing-cdc-drain/tasks.md`:
- Line 3: The task text is ambiguous about what linkedNarinfoNarHash currently
falls back to; update the task description for item 1.1 to either (a) explicitly
state that linkedNarinfoNarHash falls back only to a compression=none URL lookup
(i.e. URLEQ(noneURL.String())) when the join link miss occurs, or (b) if the
spec intends a broader search by nar_hash across all narinfo records, change the
task to require extending linkedNarinfoNarHash (or a dedicated resolver) to
perform an additional nar_hash-based lookup across all narinfo records (any URL
with that nar_hash) after the join-link and exact-none-URL attempts; reference
linkedNarinfoNarHash and the URLEQ(noneURL.String()) behavior so reviewers can
locate and update the correct behavior.

---

Nitpick comments:
In
`@openspec/changes/self-completing-cdc-drain/specs/chunks-to-nar-migration/spec.md`:
- Around line 30-39: The scenario text under "Requirement: De-chunking MUST
normalize the narinfo URL to none" is ambiguous about narinfo cardinality;
update the Scenario "A de-chunked NAR's narinfo advertises none" to explicitly
state whether it covers one or many narinfo records and add at least one
sub-scenario showing multiple narinfo variants (e.g., both `nar/<H>.nar.xz` and
`nar/<H>.nar.zst`) referencing the same NAR, and assert that after de-chunking
all such narinfo entries are updated to `nar/<H>.nar` with Compression none so
it clearly matches the general requirement that "every narinfo referencing that
NAR" must be normalized.

In `@openspec/changes/self-completing-cdc-drain/specs/fsck/spec.md`:
- Around line 13-18: Add an explicit scenario for corrupt/missing chunks: create
a new scenario titled like "Scenario: fsck purges a chunked NAR with corrupt
chunks" that mirrors the existing scenario for un-de-chunkable NARs but sets up
a chunked `nar_file` where a resolvable `NarHash` exists in `narinfo` yet one or
more chunks are missing/corrupt, invoke `fsck --repair`, and assert that fsck
purges the chunked `nar_file` and does not leave it chunked; update the spec
around the fsck requirement text to reference this new scenario so both failure
modes (no resolvable `NarHash` and corrupt/missing chunks) are explicitly
covered.

In `@openspec/changes/self-completing-cdc-drain/tasks.md`:
- Around line 13-14: Tasks 3.1 and 3.2 use the ambiguous term "purge"; define
the purge operation so implementers of migrate_chunks_to_nar.go and any logic
that handles missing NarHash know exactly what to remove: delete the nar_file
record for the chunked object, delete all associated nar_file_chunk links,
remove any now-orphaned narinfo rows (relying on narinfo_nar_files cascade where
applicable), and delete any newly-orphaned chunk records and their backing
storage objects; add this brief definition as a comment or cross-reference in
the tasks and in the code paths in migrate_chunks_to_nar.go that perform hard
reconstruction failure handling so the implementation removes those four
categories atomically or in a documented order.
- Line 8: The task "After the record flip in MigrateChunksToNar" is ambiguous
about locating "every referencing narinfo" — use the narinfo_nar_files join
table to reliably find all narinfo rows linked to the nar_file ID and update
those narinfo records (set url to "nar/<H>.nar", compression to "none", and
filehash to null) in the MigrateChunksToNar flow; if you must support the
alternate approach also include a fallback that parses the existing narinfo.url
for a matching NAR hash, but prefer and document the join-table query against
narinfo_nar_files and the nar_file ID as the canonical method.
- Line 19: Split task "4.1 Add an fsck check + `--repair` action for chunked
nar_files: relink+normalize when a valid NarHash exists, purge otherwise" into
explicit sub-steps: 1) Validate: run fsck to detect chunked nar_files and verify
NarHash; 2) If NarHash is valid, perform "relink" (recreate/repair chunk links
and update metadata) as a distinct step, then perform "normalize" (canonicalize
file layout/metadata) as a separate step only after successful relink; 3) If
NarHash is invalid or missing, perform "purge" (safe removal) with criteria for
when purge is allowed; and 4) document preconditions, failure handling, and
selection criteria for choosing relink vs purge in the task description so the
two-phase logic (validate → relink then normalize, or validate → purge) is
explicit. Reference the task label "4.1", the action names "relink",
"normalize", "purge", and the `--repair` flag in the updated description.
- Around line 1-26: The task list lacks links to the detailed specs; update the
headings in openspec/changes/self-completing-cdc-drain/tasks.md (for example the
sections "1. De-chunk: resolve NarHash by NAR hash (A)", "2. De-chunk: normalize
narinfo URL on de-chunk (B)", "3. De-chunk: purge-on-unverifiable (C)", and "4.
fsck residue repair (D)") to include direct cross-references to the matching
spec files (e.g., specs/chunks-to-nar-migration/spec.md and specs/fsck/spec.md),
adding a short "See:" line under each numbered section that points to the
precise spec path so implementers can jump from the task entry to the full
requirements.
🪄 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: 8475d297-6c84-40cf-9891-080464afa26e

📥 Commits

Reviewing files that changed from the base of the PR and between 22e0ae5 and 7cac91f.

📒 Files selected for processing (8)
  • openspec/changes/self-completing-cdc-drain/.openspec.yaml
  • openspec/changes/self-completing-cdc-drain/design.md
  • openspec/changes/self-completing-cdc-drain/proposal.md
  • openspec/changes/self-completing-cdc-drain/specs/cdc-chunking/spec.md
  • openspec/changes/self-completing-cdc-drain/specs/cdc-drain-mode/spec.md
  • openspec/changes/self-completing-cdc-drain/specs/chunks-to-nar-migration/spec.md
  • openspec/changes/self-completing-cdc-drain/specs/fsck/spec.md
  • openspec/changes/self-completing-cdc-drain/tasks.md

@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/self-completing-cdc-drain/specs/chunks-to-nar-migration/spec.md (1)

33-39: ⚡ Quick win

Consider clarifying narinfo retention during purge.

The scenario correctly specifies that purging removes chunk links to enable re-pull (line 37), which implies the narinfo is retained. However, this could be more explicit for clarity. The design document states "Purge keeps the narinfo" directly (design.md line 14), and the test snippet TestPurgeChunkedNar_LeavesCleanCacheMissForRefetch confirms this behavior.

Consider adding a clause like:

  • AND SHALL retain the narinfo so a later request can refetch from upstream

This would make the self-healing contract explicit in the formal spec.

🤖 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/self-completing-cdc-drain/specs/chunks-to-nar-migration/spec.md`
around lines 33 - 39, The Scenario "Un-verifiable NAR is purged, not skipped"
should explicitly state that narinfo is retained during purge: update the
scenario text under that heading to add a clause such as "AND SHALL retain the
narinfo so a later request can refetch from upstream" (mirroring the design note
and the behavior asserted by TestPurgeChunkedNar_LeavesCleanCacheMissForRefetch)
so the spec makes the retention / self-healing contract explicit.
🤖 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/self-completing-cdc-drain/specs/chunks-to-nar-migration/spec.md`:
- Around line 33-39: The Scenario "Un-verifiable NAR is purged, not skipped"
should explicitly state that narinfo is retained during purge: update the
scenario text under that heading to add a clause such as "AND SHALL retain the
narinfo so a later request can refetch from upstream" (mirroring the design note
and the behavior asserted by TestPurgeChunkedNar_LeavesCleanCacheMissForRefetch)
so the spec makes the retention / self-healing contract explicit.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 3e446b0e-f389-4107-be18-2d1168a78b89

📥 Commits

Reviewing files that changed from the base of the PR and between 7cac91f and 4abe213.

📒 Files selected for processing (8)
  • openspec/changes/self-completing-cdc-drain/.openspec.yaml
  • openspec/changes/self-completing-cdc-drain/design.md
  • openspec/changes/self-completing-cdc-drain/proposal.md
  • openspec/changes/self-completing-cdc-drain/specs/cdc-chunking/spec.md
  • openspec/changes/self-completing-cdc-drain/specs/cdc-drain-mode/spec.md
  • openspec/changes/self-completing-cdc-drain/specs/chunks-to-nar-migration/spec.md
  • openspec/changes/self-completing-cdc-drain/specs/fsck/spec.md
  • openspec/changes/self-completing-cdc-drain/tasks.md
✅ Files skipped from review due to trivial changes (4)
  • openspec/changes/self-completing-cdc-drain/specs/cdc-drain-mode/spec.md
  • openspec/changes/self-completing-cdc-drain/specs/fsck/spec.md
  • openspec/changes/self-completing-cdc-drain/specs/cdc-chunking/spec.md
  • openspec/changes/self-completing-cdc-drain/.openspec.yaml
🚧 Files skipped from review as they are similar to previous changes (1)
  • openspec/changes/self-completing-cdc-drain/tasks.md

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:M This PR changes 30-99 lines, ignoring generated files. labels Jun 5, 2026

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

🧹 Nitpick comments (1)
pkg/cache/migrate_chunks_to_nar_test.go (1)

144-150: ⚡ Quick win

Also assert FileSize is cleared during normalization.

This test validates URL, Compression, and FileHash, but it does not verify that FileSize is also cleared after normalization. A regression there would currently pass.

Suggested assertion
 	assert.Nil(t, row.FileHash, "a Compression:none narinfo must have a null file_hash")
+	assert.Nil(t, row.FileSize, "a Compression:none narinfo must have a null file_size")
🤖 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/migrate_chunks_to_nar_test.go` around lines 144 - 150, Add an
assertion in the migrate_chunks_to_nar_test (in
pkg/cache/migrate_chunks_to_nar_test.go) to verify that the row.FileSize field
is cleared (nil) after normalization; locate the existing assertions that check
row.URL, row.Compression, and row.FileHash (they reference variables row and
noneURL) and add a require.Nil/assert.Nil for row.FileSize immediately after the
FileHash assertion to guard against regressions that fail to clear the file
size.
🤖 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 8068-8083: The update only matches narinfos by URL prefix and
misses entries linked via the narinfo_nar_files relation; change the
tx.NarInfo.Update() predicate to select narinfos that are linked to this NAR via
the relation (use the ent predicate such as entnarinfo.HasNarFiles or the
relation-join variant entnarinfo.NarFilesWith(...) to target entries whose
NarFiles reference narURL.Hash) and keep a broader URL fallback (e.g.,
URLContains(narURL.Hash) or URLHasPrefix("nar/"+narURL.Hash) OR
URLHasPrefix("<original-prefix>"+narURL.Hash)) so both linked and
prefixed/original URLs are normalized; make the same change in the other block
mentioned (around the NarHash fallback) so both normalization sites use the
narinfo_nar_files relation as the primary selector and a broader URL predicate
as the secondary fallback.

---

Nitpick comments:
In `@pkg/cache/migrate_chunks_to_nar_test.go`:
- Around line 144-150: Add an assertion in the migrate_chunks_to_nar_test (in
pkg/cache/migrate_chunks_to_nar_test.go) to verify that the row.FileSize field
is cleared (nil) after normalization; locate the existing assertions that check
row.URL, row.Compression, and row.FileHash (they reference variables row and
noneURL) and add a require.Nil/assert.Nil for row.FileSize immediately after the
FileHash assertion to guard against regressions that fail to clear the file
size.
🪄 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: edddd3a5-937e-4480-b98b-10e72292cce6

📥 Commits

Reviewing files that changed from the base of the PR and between 4abe213 and 28e52bf.

📒 Files selected for processing (7)
  • openspec/changes/self-completing-cdc-drain/design.md
  • openspec/changes/self-completing-cdc-drain/proposal.md
  • openspec/changes/self-completing-cdc-drain/tasks.md
  • pkg/cache/cache.go
  • pkg/cache/migrate_chunks_to_nar_test.go
  • pkg/ncps/migrate_chunks_to_nar.go
  • pkg/ncps/migrate_chunks_to_nar_test.go
✅ Files skipped from review due to trivial changes (3)
  • openspec/changes/self-completing-cdc-drain/design.md
  • openspec/changes/self-completing-cdc-drain/tasks.md
  • openspec/changes/self-completing-cdc-drain/proposal.md

Comment thread pkg/cache/cache.go Resolved
Comment thread pkg/ncps/migrate_chunks_to_nar.go Resolved
@kalbasit
kalbasit force-pushed the user/wnasreddine/reconcile-narinfo-narfile-links branch from 22e0ae5 to ae31985 Compare June 5, 2026 19:07
kalbasit added a commit that referenced this pull request Jun 5, 2026
- (B) Normalize narinfos matched by the narinfo_nar_files join link OR
  the none-URL prefix, so nix-serve-style prefixed URLs the prefix would
  miss are normalized too (thread Hc3tu).
- (C) Do not purge on context.Canceled/DeadlineExceeded — a cancelled
  run must not reclaim possibly-healthy chunked NARs (thread Hc3ty).
- Docs: spell out FileSize null alongside FileHash null in design + the
  cdc-chunking / chunks-to-nar-migration specs (the code already clears
  it) (threads HccUG, HccUX, HccUd).

Threads HccTn/HccUm (query by nar_hash=H) intentionally not applied: the
nar_file hash passed to the resolver is the compressed-file hash, which
does not equal the narinfo's uncompressed nar_hash column, so a nar_hash
lookup would miss; the URL-prefix/join match is correct.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@kalbasit
kalbasit force-pushed the user/wnasreddine/self-completing-cdc-drain branch from 28e52bf to 8bfb770 Compare June 5, 2026 19:07
@kalbasit
kalbasit force-pushed the user/wnasreddine/reconcile-narinfo-narfile-links branch from ae31985 to c959add Compare June 5, 2026 19:08
kalbasit added a commit that referenced this pull request Jun 5, 2026
- (B) Normalize narinfos matched by the narinfo_nar_files join link OR
  the none-URL prefix, so nix-serve-style prefixed URLs the prefix would
  miss are normalized too (thread Hc3tu).
- (C) Do not purge on context.Canceled/DeadlineExceeded — a cancelled
  run must not reclaim possibly-healthy chunked NARs (thread Hc3ty).
- Docs: spell out FileSize null alongside FileHash null in design + the
  cdc-chunking / chunks-to-nar-migration specs (the code already clears
  it) (threads HccUG, HccUX, HccUd).

Threads HccTn/HccUm (query by nar_hash=H) intentionally not applied: the
nar_file hash passed to the resolver is the compressed-file hash, which
does not equal the narinfo's uncompressed nar_hash column, so a nar_hash
lookup would miss; the URL-prefix/join match is correct.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@kalbasit
kalbasit force-pushed the user/wnasreddine/self-completing-cdc-drain branch from 8bfb770 to eacc64a Compare June 5, 2026 19:08
@kalbasit
kalbasit force-pushed the user/wnasreddine/reconcile-narinfo-narfile-links branch from c959add to 858c27f Compare June 5, 2026 19:15
kalbasit added a commit that referenced this pull request Jun 5, 2026
- (B) Normalize narinfos matched by the narinfo_nar_files join link OR
  the none-URL prefix, so nix-serve-style prefixed URLs the prefix would
  miss are normalized too (thread Hc3tu).
- (C) Do not purge on context.Canceled/DeadlineExceeded — a cancelled
  run must not reclaim possibly-healthy chunked NARs (thread Hc3ty).
- Docs: spell out FileSize null alongside FileHash null in design + the
  cdc-chunking / chunks-to-nar-migration specs (the code already clears
  it) (threads HccUG, HccUX, HccUd).

Threads HccTn/HccUm (query by nar_hash=H) intentionally not applied: the
nar_file hash passed to the resolver is the compressed-file hash, which
does not equal the narinfo's uncompressed nar_hash column, so a nar_hash
lookup would miss; the URL-prefix/join match is correct.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@kalbasit
kalbasit force-pushed the user/wnasreddine/self-completing-cdc-drain branch from eacc64a to cf0e4f2 Compare June 5, 2026 19:15
@kalbasit
kalbasit force-pushed the user/wnasreddine/reconcile-narinfo-narfile-links branch from 858c27f to 0a9975c Compare June 5, 2026 19:23
kalbasit added a commit that referenced this pull request Jun 5, 2026
- (B) Normalize narinfos matched by the narinfo_nar_files join link OR
  the none-URL prefix, so nix-serve-style prefixed URLs the prefix would
  miss are normalized too (thread Hc3tu).
- (C) Do not purge on context.Canceled/DeadlineExceeded — a cancelled
  run must not reclaim possibly-healthy chunked NARs (thread Hc3ty).
- Docs: spell out FileSize null alongside FileHash null in design + the
  cdc-chunking / chunks-to-nar-migration specs (the code already clears
  it) (threads HccUG, HccUX, HccUd).

Threads HccTn/HccUm (query by nar_hash=H) intentionally not applied: the
nar_file hash passed to the resolver is the compressed-file hash, which
does not equal the narinfo's uncompressed nar_hash column, so a nar_hash
lookup would miss; the URL-prefix/join match is correct.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@kalbasit
kalbasit force-pushed the user/wnasreddine/self-completing-cdc-drain branch from cf0e4f2 to 3803efc Compare June 5, 2026 19:23
Base automatically changed from user/wnasreddine/reconcile-narinfo-narfile-links to main June 5, 2026 19:30
kalbasit and others added 4 commits June 5, 2026 19:30
Make migrate-chunks-to-nar always drive the chunked count to zero (and
fsck heal residue) so CDC drain auto-completes without manual SQL.
Spec deltas for chunks-to-nar-migration, cdc-drain-mode, fsck, and
cdc-chunking covering: resolve verify-hash by NAR hash (any narinfo URL),
normalize narinfo URL to none on de-chunk, purge-on-unverifiable instead
of skip/fail, and an fsck residue-repair pass.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Make migrate-chunks-to-nar always drive the chunked count to zero:

- (A) linkedNarinfoNarHash resolves the verify NarHash from ANY narinfo
  referencing the NAR by hash (any compression URL), not just the exact
  Compression:none URL. The NarHash is the uncompressed content hash,
  identical across compressions; content verification of the
  reconstructed bytes remains the gate, so a wrong source mismatches and
  purges rather than corrupting.
- (B) on the record flip, normalize every referencing narinfo to the
  Compression:none URL (FileHash/FileSize cleared) so the de-chunked
  whole-file NAR and its narinfo stay consistent (no recreated .nar.xz
  404 once chunks are gone).
- (C) the driver loop purges any NAR it cannot de-chunk (no resolvable
  NarHash, missing/corrupt chunks, hash mismatch, or other reconstruction
  failure) instead of skipping/failing, so the pass self-completes and
  CDC drain auto-exits. The narinfo remains and re-pulls from upstream.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Split the fsck residue-repair safety net out of this change into its own
proposal (a daily-janitor grace-period mark-then-purge reclaimer with a
persistent mark column). The de-chunk migration (A+B+C) already drives
the chunked count to zero on its own, so this change is the self-
completing de-chunk migration; fsck is handled separately.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
- (B) Normalize narinfos matched by the narinfo_nar_files join link OR
  the none-URL prefix, so nix-serve-style prefixed URLs the prefix would
  miss are normalized too (thread Hc3tu).
- (C) Do not purge on context.Canceled/DeadlineExceeded — a cancelled
  run must not reclaim possibly-healthy chunked NARs (thread Hc3ty).
- Docs: spell out FileSize null alongside FileHash null in design + the
  cdc-chunking / chunks-to-nar-migration specs (the code already clears
  it) (threads HccUG, HccUX, HccUd).

Threads HccTn/HccUm (query by nar_hash=H) intentionally not applied: the
nar_file hash passed to the resolver is the compressed-file hash, which
does not equal the narinfo's uncompressed nar_hash column, so a nar_hash
lookup would miss; the URL-prefix/join match is correct.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@kalbasit
kalbasit force-pushed the user/wnasreddine/self-completing-cdc-drain branch from 3803efc to 1d97f02 Compare June 5, 2026 19:30
@kalbasit
kalbasit enabled auto-merge (squash) June 5, 2026 19:31

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

♻️ Duplicate comments (1)
pkg/ncps/migrate_chunks_to_nar.go (1)

433-443: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Update CLI description to match new purge-on-unverifiable behavior.

The catch-all path now purges unverifiable/unreconstructable NARs, but the command description still says no-NarHash NARs are skipped and left chunked. Please align the help text.

Suggested text update
- NARs whose narinfo has no recorded NarHash are left chunked (skipped) rather than de-chunked unverified.`,
+ NARs that cannot be content-verified or reconstructed are purged so they can be re-fetched from upstream on next request.`,
🤖 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/ncps/migrate_chunks_to_nar.go` around lines 433 - 443, The CLI help text
for the migrate-chunks-to-nar command is outdated: it says NARs without NarHash
are skipped and left chunked, but the code (see the purging behavior logged in
log.Warn().Err(err).Msg("cannot de-chunk nar; purging so it re-fetches from
upstream")) now purges unverifiable/unreconstructable NARs so they will be
re-fetched; update the command description string (the migrate-chunks-to-nar CLI
help/usage text in this package) to state that NARs that cannot be
verified/reconstructed are purged to force re-fetch from upstream rather than
being skipped.
🤖 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.

Duplicate comments:
In `@pkg/ncps/migrate_chunks_to_nar.go`:
- Around line 433-443: The CLI help text for the migrate-chunks-to-nar command
is outdated: it says NARs without NarHash are skipped and left chunked, but the
code (see the purging behavior logged in log.Warn().Err(err).Msg("cannot
de-chunk nar; purging so it re-fetches from upstream")) now purges
unverifiable/unreconstructable NARs so they will be re-fetched; update the
command description string (the migrate-chunks-to-nar CLI help/usage text in
this package) to state that NARs that cannot be verified/reconstructed are
purged to force re-fetch from upstream rather than being skipped.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c65db9c2-f5fd-4c1e-a99b-c514e0510937

📥 Commits

Reviewing files that changed from the base of the PR and between 28e52bf and 1d97f02.

📒 Files selected for processing (11)
  • openspec/changes/self-completing-cdc-drain/.openspec.yaml
  • openspec/changes/self-completing-cdc-drain/design.md
  • openspec/changes/self-completing-cdc-drain/proposal.md
  • openspec/changes/self-completing-cdc-drain/specs/cdc-chunking/spec.md
  • openspec/changes/self-completing-cdc-drain/specs/cdc-drain-mode/spec.md
  • openspec/changes/self-completing-cdc-drain/specs/chunks-to-nar-migration/spec.md
  • openspec/changes/self-completing-cdc-drain/tasks.md
  • pkg/cache/cache.go
  • pkg/cache/migrate_chunks_to_nar_test.go
  • pkg/ncps/migrate_chunks_to_nar.go
  • pkg/ncps/migrate_chunks_to_nar_test.go
✅ Files skipped from review due to trivial changes (3)
  • openspec/changes/self-completing-cdc-drain/.openspec.yaml
  • openspec/changes/self-completing-cdc-drain/specs/cdc-chunking/spec.md
  • openspec/changes/self-completing-cdc-drain/specs/cdc-drain-mode/spec.md
🚧 Files skipped from review as they are similar to previous changes (4)
  • pkg/ncps/migrate_chunks_to_nar_test.go
  • openspec/changes/self-completing-cdc-drain/tasks.md
  • pkg/cache/migrate_chunks_to_nar_test.go
  • pkg/cache/cache.go

The openspec-guard CI gate requires active OpenSpec changes to be
archived before a PR merges. This change is fully implemented (de-chunk
ANY-narinfo NarHash resolution, post-de-chunk URL normalization,
purge-on-unverifiable, and the fsck safety net) and all CI checks pass,
so archive it: sync the cdc-chunking, cdc-drain-mode, and
chunks-to-nar-migration delta specs into the baseline and move the
change under openspec/changes/archive/.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@kalbasit
kalbasit merged commit 63993cf into main Jun 5, 2026
65 of 78 checks passed
@kalbasit
kalbasit deleted the user/wnasreddine/self-completing-cdc-drain branch June 5, 2026 21:00
@dosubot

dosubot Bot commented Jun 5, 2026

Copy link
Copy Markdown

Documentation Updates

1 document(s) were updated by changes in this PR:

NAR File Download and Streaming
View Changes
@@ -129,7 +129,7 @@
 
 If CDC is not enabled in the database, the command will return an error: "migrate-nar-to-chunks command requires CDC to be enabled in the database; please run 'ncps serve' with CDC enabled first". This ensures that the migration infrastructure is properly configured before attempting to migrate existing NAR files to the chunked storage format.
 
-The `ncps migrate-chunks-to-nar` command provides the reverse migration, reconstituting whole NAR files from their stored chunks. This command updates the database and reclaims the chunk objects. The Cache provides a `PurgeChunkedNar` method that deletes permanently broken chunked NAR entries (those with hash mismatches or missing chunks) so they can be re-fetched from upstream on the next `GetNar` request.
+The `ncps migrate-chunks-to-nar` command provides the reverse migration, reconstituting whole NAR files from their stored chunks. This command updates the database and reclaims the chunk objects. The Cache provides a `PurgeChunkedNar` method that deletes broken chunked NAR entries so they can be re-fetched from upstream on the next `GetNar` request.
 
 The command supports:
 
@@ -137,11 +137,13 @@
 - `--concurrency`: Control the number of parallel migrations (default matches CPU count)
 - `--force-reclaim`: Bypass the in-flight-serve safety check
 
-Per-NAR failures are isolated—the batch continues processing remaining NARs. When a NAR encounters `ErrNarHashMismatch` or `ErrMissingChunk`, the command calls `PurgeChunkedNar` to delete the `nar_file` record, remove chunk links, and reclaim orphaned chunks. The narinfo record is intentionally left intact so the next `GetNarInfo` can trigger a clean upstream re-fetch. Purged NARs are counted separately from failures in metrics and logs. The command exits 0 when all NARs were either successfully migrated, skipped, or purged. Only genuine migration errors (not hash mismatches or missing chunks) cause non-zero exit.
+Per-NAR failures are isolated—the batch continues processing remaining NARs. When a NAR encounters any error during de-chunking (except context cancellation or interruption), the command calls `PurgeChunkedNar` to delete the `nar_file` record, remove chunk links, and reclaim orphaned chunks. This includes NARs with no NarHash to verify, missing or corrupt chunks, hash or size mismatches, and any other reconstruction failures. The narinfo record is intentionally left intact so the next `GetNarInfo` can trigger a clean upstream re-fetch. Purged NARs are counted separately from failures in metrics and logs. The command exits 0 when all NARs were either successfully migrated, skipped (already in whole-file format or being migrated by another worker), or purged. Only context cancellation or interruption causes non-zero exit. This change makes CDC drain self-completing by driving the chunked count to zero, rather than stranding unprocessable NARs.
+
+The command resolves the expected NarHash from any narinfo referencing the NAR by hash, not just the join-linked narinfo. This handles cases where narinfos advertise different-compression URLs (e.g., `.nar.xz`) or where the join link is missing. On successful de-chunk, all narinfos referencing the NAR are normalized to the Compression:none URL, ensuring persisted narinfos match the new whole-file storage and preventing 404s.
 
 **Handling Un-reassemblable Chunked NARs:**
 
-The migration command skips un-reassemblable chunked NARs instead of aborting the entire run. When `migrate-chunks-to-nar` encounters a chunked NAR that cannot be reassembled—because its `nar_file_chunks` links are incomplete (fewer links than `total_chunks`) or because a referenced chunk's blob is absent from the chunk store—it skips that NAR and continues migrating the remaining NARs. Un-reassemblable NARs are counted and reported by hash at the end of the run, allowing operators to identify and address them. These NARs can be purged to a clean cache-miss state using `PurgeChunkedNar`, which deletes the `nar_file` record and chunk links while retaining the linked narinfo, allowing the NAR to be refetched from upstream on the next request. This makes HTTP 404 responses for incomplete chunked NARs self-healing rather than permanent failures.
+The migration command purges un-reassemblable chunked NARs instead of aborting the entire run. When `migrate-chunks-to-nar` encounters a chunked NAR that cannot be reassembled—because its `nar_file_chunks` links are incomplete (fewer links than `total_chunks`) or because a referenced chunk's blob is absent from the chunk store—it purges that NAR and continues migrating the remaining NARs. The `PurgeChunkedNar` method deletes the `nar_file` record and chunk links while retaining the linked narinfo, allowing the NAR to be refetched from upstream on the next request. This makes HTTP 404 responses for incomplete chunked NARs self-healing rather than permanent failures.
 
 When lazy chunking is enabled (via `--cache-cdc-lazy-chunking-enabled=true`), compressed NAR files are stored without immediate chunking, and background workers automatically perform migration using the same infrastructure as the `migrate-nar-to-chunks` command. The background workers can be configured via `--cache-cdc-background-workers` (default: number of CPUs).
 

How did I do? Any feedback?  Join Discord

kalbasit added a commit that referenced this pull request Jun 7, 2026
…urge) (#1335)

## Summary

A routine-fsck safety net for CDC chunked-NAR residue, complementing the
self-completing de-chunk migration (#1334).

Two tiers, per chunked `nar_file`:
- **Recoverable** (a narinfo with a resolvable NarHash, inconsistent
URL): relink + normalize the URL to none **immediately** (touches no
chunks; safe in any CDC state).
- **Un-de-chunkable** (no resolvable NarHash): **mark** with a
persistent `nar_file.dechunk_residue_flagged_at` timestamp; **purge only
on a later fsck run** once the flag has aged past a configurable ~24h
grace window (`--dechunk-residue-grace`) and the row is still suspect.
Becomes-recoverable/de-chunked → flag cleared, never purged. Rows
mid-chunking are skipped.

The grace window (two daily runs) prevents purging transient states and
protects legitimately chunked NARs. Non-repair/dry-run runs only report
already-flagged, grace-elapsed residue, so they raise no false
positives.

Includes the OpenSpec proposal **and** the implementation: nullable
`dechunk_residue_flagged_at` column (forward-only additive migration,
all three dialects), the two-tier reclaimer in `pkg/ncps/fsck.go`
reusing `PurgeChunkedNar` and the shared de-chunk resolver, a white-box
policy test, the five spec scenarios as CLI tests, and a CDC-lifecycle
e2e exercising the reclaimer alongside the drain.

---------

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

documentation Improvements or additions to documentation 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