Repository navigation
fix(cache,fsck): self-completing CDC drain (de-chunk never strands NARs) - #1334
Conversation
|
This change is part of the following stack:
Change managed by git-spice. |
|
Complex PR? Review this PR in Change Stack to move by importance, not file order. 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 implements self-completing CDC drain by extending ChangesSelf-Completing CDC Drain Feature
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 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 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.
7cac91f to
4abe213
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (6)
openspec/changes/self-completing-cdc-drain/specs/fsck/spec.md (1)
13-18: ⚡ Quick winConsider 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 chunkedThis 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 winConsider 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.xzand.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 winDefine 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:
- Delete the chunked
nar_filerecord- Delete associated
nar_file_chunklinks- Delete newly-orphaned
narinforecords (vianarinfo_nar_filescascade)- Delete newly-orphaned
chunkrecords and storage objectsConsider 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 winSpecify 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:
- Query via the
narinfo_nar_filesjoin table (all narinfo records linked to the nar_file ID), or- 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 nullThis 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 winBreak 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 recordsThis 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 valueConsider 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
📒 Files selected for processing (8)
openspec/changes/self-completing-cdc-drain/.openspec.yamlopenspec/changes/self-completing-cdc-drain/design.mdopenspec/changes/self-completing-cdc-drain/proposal.mdopenspec/changes/self-completing-cdc-drain/specs/cdc-chunking/spec.mdopenspec/changes/self-completing-cdc-drain/specs/cdc-drain-mode/spec.mdopenspec/changes/self-completing-cdc-drain/specs/chunks-to-nar-migration/spec.mdopenspec/changes/self-completing-cdc-drain/specs/fsck/spec.mdopenspec/changes/self-completing-cdc-drain/tasks.md
There was a problem hiding this comment.
🧹 Nitpick comments (1)
openspec/changes/self-completing-cdc-drain/specs/chunks-to-nar-migration/spec.md (1)
33-39: ⚡ Quick winConsider 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_LeavesCleanCacheMissForRefetchconfirms 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
📒 Files selected for processing (8)
openspec/changes/self-completing-cdc-drain/.openspec.yamlopenspec/changes/self-completing-cdc-drain/design.mdopenspec/changes/self-completing-cdc-drain/proposal.mdopenspec/changes/self-completing-cdc-drain/specs/cdc-chunking/spec.mdopenspec/changes/self-completing-cdc-drain/specs/cdc-drain-mode/spec.mdopenspec/changes/self-completing-cdc-drain/specs/chunks-to-nar-migration/spec.mdopenspec/changes/self-completing-cdc-drain/specs/fsck/spec.mdopenspec/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
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
pkg/cache/migrate_chunks_to_nar_test.go (1)
144-150: ⚡ Quick winAlso assert
FileSizeis cleared during normalization.This test validates
URL,Compression, andFileHash, but it does not verify thatFileSizeis 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
📒 Files selected for processing (7)
openspec/changes/self-completing-cdc-drain/design.mdopenspec/changes/self-completing-cdc-drain/proposal.mdopenspec/changes/self-completing-cdc-drain/tasks.mdpkg/cache/cache.gopkg/cache/migrate_chunks_to_nar_test.gopkg/ncps/migrate_chunks_to_nar.gopkg/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
22e0ae5 to
ae31985
Compare
- (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]>
28e52bf to
8bfb770
Compare
ae31985 to
c959add
Compare
- (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]>
8bfb770 to
eacc64a
Compare
c959add to
858c27f
Compare
- (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]>
eacc64a to
cf0e4f2
Compare
858c27f to
0a9975c
Compare
- (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]>
cf0e4f2 to
3803efc
Compare
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]>
3803efc to
1d97f02
Compare
There was a problem hiding this comment.
♻️ Duplicate comments (1)
pkg/ncps/migrate_chunks_to_nar.go (1)
433-443:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winUpdate 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
📒 Files selected for processing (11)
openspec/changes/self-completing-cdc-drain/.openspec.yamlopenspec/changes/self-completing-cdc-drain/design.mdopenspec/changes/self-completing-cdc-drain/proposal.mdopenspec/changes/self-completing-cdc-drain/specs/cdc-chunking/spec.mdopenspec/changes/self-completing-cdc-drain/specs/cdc-drain-mode/spec.mdopenspec/changes/self-completing-cdc-drain/specs/chunks-to-nar-migration/spec.mdopenspec/changes/self-completing-cdc-drain/tasks.mdpkg/cache/cache.gopkg/cache/migrate_chunks_to_nar_test.gopkg/ncps/migrate_chunks_to_nar.gopkg/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]>
|
Documentation Updates 1 document(s) were updated by changes in this PR: NAR File Download and StreamingView 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).
|
…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]>
* 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 #1333. Makes
migrate-chunks-to-naralways drive the chunkedcount 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):
different-compression URL (
.nar.xz) than the barenar/<H>.nar, sothe verify-hash resolver misses and skips them.
URL recreates the
.nar.xz≠ none/whole 404.failedand leftchunked.
Code changes (proposal/design/specs in
openspec/changes/):narinfo, not just the exact none URL;
instead of skip/fail, so the pass always reaches
chunked = 0;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
.nar.xz-URL narinfo, no-NarHash, corrupt chunks)chunked = 0