Skip to content

fix(ncps): purge unrecoverable NARs in migrate-chunks-to-nar - #1316

Merged
kalbasit merged 2 commits into
mainfrom
user/wnasreddine/migrate-failed-for-bad-nars
Jun 3, 2026
Merged

kalbasit merged 2 commits into
mainfrom
user/wnasreddine/migrate-failed-for-bad-nars

Conversation

@kalbasit

@kalbasit kalbasit commented Jun 3, 2026

Copy link
Copy Markdown
Owner

Summary

168 NARs consistently fail reconstruction with hash mismatches on every migration run — their chunk data is permanently corrupt and will never migrate successfully. Previously the command exited non-zero on any NAR failure, leaving the Kubernetes Job in a Failed state even after processing 99.6% of entries.

  • Add Cache.PurgeChunkedNar: when migrate-chunks-to-nar encounters ErrNarHashMismatch it purges the broken entry — deletes nar_file_chunks links, reclaims orphaned chunk objects, and deletes the nar_file record — so the hash re-enters the normal upstream fetch path on the next GetNar request
  • The linked narinfo is left intact so GetNarInfo still succeeds and the re-fetch can complete normally
  • Purge is dedup-safe: chunks still referenced by other nar_file records are retained
  • Add totalPurged counter tracked separately from totalFailed; command exits 0 when failed == 0 regardless of how many were purged
  • Add purged field to progress-ticker and summary log lines
  • Add MigrationResultPurged ("purged") metric result constant

Test plan

  • task fmt — no changes
  • task lint — no issues in changed files (pre-existing tmp-dir/ issues unrelated)
  • task test — all unit tests pass with race detector
  • TestPurgeChunkedNar_DeletesLinksChunksAndRecord — purge deletes chunk links, orphaned objects, and nar_file record
  • TestPurgeChunkedNar_RetainsSharedChunk — chunks shared with another nar_file are not deleted
  • TestPurgeChunkedNar_RetainsNarInfoRecord — narinfo is left intact after purge
  • TestMigrateChunksToNar_CLI_HashMismatchPurgesNarAndExitsZero — command exits 0, nar_file and orphaned chunks deleted, narinfo retained

168 NARs consistently fail reconstruction with hash mismatches across
every migration run because their chunk data is permanently corrupt.
Previously the command exited non-zero on any NAR failure, leaving the
Kubernetes Job in a Failed state even after processing 99.6% of entries.

Add Cache.PurgeChunkedNar: when migrate-chunks-to-nar encounters
ErrNarHashMismatch it now purges the broken entry (deletes nar_file_chunks
links, reclaims orphaned chunk objects, deletes the nar_file record) so
the hash re-enters the normal upstream fetch path on the next GetNar
request. The linked narinfo is left intact so GetNarInfo still succeeds.
Purge is dedup-safe: chunks shared with other nar_files are retained.

A new totalPurged counter tracks purged entries separately from failures.
The command exits 0 when failed == 0 regardless of how many were purged;
purged count appears in both progress-ticker and summary log lines.
MigrationResultPurged ("purged") added to the metrics result constants.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@kalbasit

kalbasit commented Jun 3, 2026 •

Copy link
Copy Markdown
Owner Author

This change is part of the following stack:

Change managed by git-spice.

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. go Pull requests that update go code labels Jun 3, 2026
@coderabbitai

coderabbitai Bot commented Jun 3, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Summary by CodeRabbit

  • Bug Fixes

    • Migration now purges unrecoverable NARs on hash-mismatch or missing chunks, preserves narinfo so GetNar can re-fetch, continues processing remaining items, and treats purges as non-fatal (command exits 0 when only purges occur). Progress and final summary now report purged counts.
  • Documentation

    • Added design, spec, proposal, and task docs describing the purge-and-evict migration behavior and checklist.
  • Tests

    • Added/updated tests covering purge behavior, dedup-safe reclamation, and preserved narinfo.

Walkthrough

This PR adds purge-on-unrecoverable-failure behavior for chunked NAR reconstruction: Cache.PurgeChunkedNar removes nar_file_chunk links and the nar_file record (dedup-safe reclamation of orphaned chunks), preserves narinfo, and the migrate-chunks-to-nar command records and reports purged outcomes while exiting 0 when only purges/successes occur.

Changes

Chunked NAR hash-mismatch purge

Layer / File(s) Summary
Design, proposal, spec, and tasks
openspec/changes/archive/2026-06-02-migrate-skip-bad-nars/..., openspec/specs/chunks-to-nar-migration/spec.md
Design, proposal, formal spec, and task checklist define purge triggers (hash-mismatch, missing-chunk), transactional unlink + record deletion ordering, dedup-safe chunk reclamation, preservation of narinfo, batch semantics, and exit/logging behavior.
Cache purge implementation and tests
pkg/cache/cache.go, pkg/cache/migrate_chunks_to_nar_test.go
Adds ErrMissingChunk, hardens cleanupStaleLockChunks, and implements Cache.PurgeChunkedNar (migration-lock coordinated transactional unlink + nar_file deletion, immediate orphan reclamation). Tests verify link/record deletion, dedup-safe retention, and narinfo preservation.
Command integration and observability
pkg/ncps/metrics.go, pkg/ncps/migrate_chunks_to_nar.go, pkg/ncps/migrate_chunks_to_nar_test.go
Adds MigrationResultPurged, totalPurged counter, includes purged in periodic progress and final summary logs, calls PurgeChunkedNar on ErrNarHashMismatch/ErrMissingChunk, and updates CLI tests to expect purge-and-exit-0 behavior and purged in logs.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • kalbasit/ncps#1229: Related changes to cleanupStaleLockChunks and orphan-chunk deletion logic.
  • kalbasit/ncps#1301: Prior work on Cache.MigrateChunksToNar that this PR extends with purge handling.
  • kalbasit/ncps#1310: Related migration progress-logging changes that this PR extends to include purged counts.

Suggested labels

bug, size:M, merge-stack

Poem

🐰 A NAR once split into many small parts,
Some pieces were missing, sad broken hearts.
We purge what is certain and keep the map tight,
Leave narinfo to beckon the upstream light.
Exit zero sings — migration dances right.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title 'fix(ncps): purge unrecoverable NARs in migrate-chunks-to-nar' directly and specifically describes the main change: adding purge functionality for unrecoverable NARs in the migration command.
Description check ✅ Passed The description provides relevant context about the problem (168 NARs with permanent hash mismatches) and clearly explains the solution (PurgeChunkedNar function, exit code behavior, metrics), all directly related to the changeset.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

Comment @coderabbitai help to get the list of available commands and usage tips.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request implements a mechanism to purge permanently broken chunked NARs (e.g., due to hash mismatches) during the migrate-chunks-to-nar migration process, allowing the migration job to exit successfully (0) instead of failing. It introduces the PurgeChunkedNar method in the cache layer to safely delete nar_file_chunks links, orphaned chunk objects, and the nar_file record while keeping the narinfo record intact for future upstream re-fetching. The command layer is updated to handle ErrNarHashMismatch by triggering this purge, tracking it with a new totalPurged counter, and adjusting the exit condition. The review feedback suggests adding a defensive nil guard check for narURL in PurgeChunkedNar to prevent potential nil-pointer dereferences.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread pkg/cache/cache.go Resolved
@dosubot

dosubot Bot commented Jun 3, 2026 •

Copy link
Copy Markdown

Documentation Updates

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

NAR File Download and Streaming
View Changes
@@ -128,13 +128,15 @@
 
 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. It supports:
+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 command supports:
 
 - `--dry-run`: Preview the migration without making changes
 - `--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 and the command exits non-zero only if any NAR failed.
+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.
 
 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

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

🤖 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/archive/2026-06-02-migrate-skip-bad-nars/design.md`:
- Around line 9-12: Update the design text so the inline purge trigger is
explicitly limited to hash/size mismatches: remove the claim that "missing
chunks are purged inline" from the Goals section and instead state that
missing-chunk cases are deferred per the cache contract; explicitly reference
the cache error symbol ErrNarHashMismatch as the only inline-purge condition and
keep the text in the later section (lines ~43-46) asserting missing chunks are
handled via the deferred path so the design is unambiguous.
- Around line 27-31: Update the "Purge sequence" paragraph to match the
implemented API: state that the purge deletes `nar_file_chunks` links and the
`nar_file` record together in a single transaction, and only after that
transaction completes the system reclaims orphaned chunk objects (instead of
deleting chunk objects before removing the `nar_file`). Reference the same
symbols used in code (`nar_file_chunks`, `nar_file`, and the chunk reclaim
behavior implemented in pkg/cache/cache.go) so tests and follow-up work target
the real contract.

In `@openspec/specs/chunks-to-nar-migration/spec.md`:
- Around line 31-38: The reconstruction path currently wraps missing-chunk
failures as generic errors so migrate-chunks-to-nar only purges on
cache.ErrNarHashMismatch; introduce a dedicated sentinel error (e.g.,
cache.ErrMissingChunk) in pkg/cache/cache.go and change the reconstruction logic
that detects absent chunk(s) (the code around the reconstruction failure) to
return that sentinel instead of a generic error, then update
pkg/ncps/migrate_chunks_to_nar.go to treat cache.ErrMissingChunk the same as
cache.ErrNarHashMismatch (call PurgeChunkedNar and avoid incrementing
failed/marking batch as error) so missing-chunk cases are purged and the batch
continues.

In `@pkg/cache/cache.go`:
- Around line 7794-7824: The current purge path unconditionally deletes chunk
rows cached in prevChunks and then removes the backing blob, which can race with
a concurrent GetNar re-linking a chunk; update the deletion logic in
cleanupStaleLockChunks (and the code that iterates prevChunks/oc) to perform a
conditional DB delete using
c.dbClient.Ent().Chunk.Delete().Where(entchunk.IDEQ(oc.ID),
entchunk.Not(entchunk.HasNarFileLinks())).Exec(ctx), check the deleted count > 0
before calling the backing store delete (c.chunkStore.DeleteChunk or
cs.DeleteChunk), and only remove the blob if the conditional delete succeeded;
handle and log non-fatal errors from DeleteChunk (ignore chunk.ErrNotFound) and
skip deleting when deleted == 0 so live-relinked chunks are preserved.

In `@pkg/ncps/migrate_chunks_to_nar.go`:
- Around line 431-442: The purge branch for cache.ErrNarHashMismatch treats any
purge error as a failure; change it so if PurgeChunkedNar returns
cache.ErrMigrationInProgress you treat it as a skip instead of a failure: in the
case purgeErr != nil, check errors.Is(purgeErr, cache.ErrMigrationInProgress)
and when true log an informative skip message, atomically increment totalSkipped
(not totalFailed), and call RecordMigrationObject(ctx, MigrationTypeChunksToNar,
MigrationOperationMigrate, MigrationResultSkipped); otherwise keep the existing
failure handling (log error, increment totalFailed, RecordMigrationObject with
MigrationResultFailure). Ensure you reference PurgeChunkedNar,
cache.ErrMigrationInProgress, totalFailed/totalSkipped, and
RecordMigrationObject/MigrationResultSkipped when making the change.
🪄 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: ac8d8a0e-8c12-4175-bab2-4275d5b67426

📥 Commits

Reviewing files that changed from the base of the PR and between 1c101ba and a60988f.

📒 Files selected for processing (11)
  • openspec/changes/archive/2026-06-02-migrate-skip-bad-nars/.openspec.yaml
  • openspec/changes/archive/2026-06-02-migrate-skip-bad-nars/design.md
  • openspec/changes/archive/2026-06-02-migrate-skip-bad-nars/proposal.md
  • openspec/changes/archive/2026-06-02-migrate-skip-bad-nars/specs/chunks-to-nar-migration/spec.md
  • openspec/changes/archive/2026-06-02-migrate-skip-bad-nars/tasks.md
  • openspec/specs/chunks-to-nar-migration/spec.md
  • pkg/cache/cache.go
  • pkg/cache/migrate_chunks_to_nar_test.go
  • pkg/ncps/metrics.go
  • pkg/ncps/migrate_chunks_to_nar.go
  • pkg/ncps/migrate_chunks_to_nar_test.go

Comment thread pkg/cache/cache.go Resolved
Comment thread pkg/ncps/migrate_chunks_to_nar.go Resolved
- Add ErrMissingChunk sentinel; MigrateChunksToNar returns it when
  chunk.ErrNotFound or storage.ErrNotFound surfaces from getNarFromChunks.
  The command now purges on ErrMissingChunk the same as ErrNarHashMismatch,
  matching the spec's missing-chunk purge-and-evict requirement.

- Treat ErrMigrationInProgress from PurgeChunkedNar as a skip (another
  worker is already handling the hash) instead of a failure, preventing
  spurious non-zero exits in concurrent migration runs.

- Fix race in cleanupStaleLockChunks: chunk DB delete is now conditioned
  on Not(HasNarFileLinks()) at delete time, and the physical blob is only
  removed when the conditional delete rows > 0. Prevents tearing down a
  chunk that a concurrent GetNar re-fetch re-linked between the orphan
  snapshot and the delete.

- Update archived design.md to reflect the correct purge sequence
  (links + nar_file record in one tx, then orphaned chunks) and to
  document both ErrNarHashMismatch and ErrMissingChunk as inline purge
  triggers.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@kalbasit
kalbasit enabled auto-merge (squash) June 3, 2026 06:14

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
pkg/cache/cache.go (1)

7778-7847: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Keep the migration lock alive for the full purge.

PurgeChunkedNar uses the same per-hash migration lock as MigrateChunksToNar, but it never starts a refresher. On a large purge or slow chunk store, the TTL can expire while chunk reclamation is still running, letting another worker reacquire the lock and observe a half-finished purge as a hard failure.

Suggested fix
 func (c *Cache) PurgeChunkedNar(ctx context.Context, narURL *nar.URL) error {
 	if !c.isCDCEnabled() {
 		return ErrCDCDisabled
 	}
@@
 	defer func() {
 		if err := c.downloadLocker.Unlock(context.WithoutCancel(ctx), lockKey); err != nil {
 			zerolog.Ctx(ctx).Error().Err(err).Str("nar_hash", narURL.Hash).Msg("failed to release migration lock")
 		}
 	}()
+
+	// Keep the lock held for the full purge, including orphan chunk cleanup.
+	defer lock.StartRefresher(ctx, c.downloadLocker, lockKey, c.downloadLockTTL)()
 
 	noneURL := nar.URL{Hash: narURL.Hash, Compression: nar.CompressionTypeNone, Query: narURL.Query}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/cache/cache.go` around lines 7778 - 7847, After acquiring the migration
lock in PurgeChunkedNar (after calling c.downloadLocker.TryLock with
migrationLockKey and c.downloadLockTTL), start a background refresher that
periodically extends the lock TTL (using your locker refresh/extend API, e.g.,
c.downloadLocker.Refresh or TryRefresh) until the purge completes; stop the
refresher before calling c.downloadLocker.Unlock in the defer so the lock is
kept alive for the entire purge and chunk-reclamation phase. Ensure the
refresher is canceled on function exit (use a context/cancel or channel) and
that any refresh errors are logged but do not prevent final Unlock.
🤖 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/archive/2026-06-02-migrate-skip-bad-nars/design.md`:
- Around line 45-47: Update the design doc so references to the purge trigger
are consistent: wherever the earlier "PurgeChunkedNar" paragraph or the
migration plan currently mention only ErrNarHashMismatch, add ErrMissingChunk as
an equal trigger (e.g., "ErrNarHashMismatch and ErrMissingChunk trigger purge")
and adjust any explanatory sentences to include ErrMissingChunk behavior; ensure
MigrateChunksToNar, PurgeChunkedNar, and any contract/summary sections all
explicitly list both ErrNarHashMismatch and ErrMissingChunk so the contract is
unambiguous.

---

Outside diff comments:
In `@pkg/cache/cache.go`:
- Around line 7778-7847: After acquiring the migration lock in PurgeChunkedNar
(after calling c.downloadLocker.TryLock with migrationLockKey and
c.downloadLockTTL), start a background refresher that periodically extends the
lock TTL (using your locker refresh/extend API, e.g., c.downloadLocker.Refresh
or TryRefresh) until the purge completes; stop the refresher before calling
c.downloadLocker.Unlock in the defer so the lock is kept alive for the entire
purge and chunk-reclamation phase. Ensure the refresher is canceled on function
exit (use a context/cancel or channel) and that any refresh errors are logged
but do not prevent final Unlock.
🪄 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: df30fe7e-ec13-40d2-9054-88bd41356733

📥 Commits

Reviewing files that changed from the base of the PR and between a60988f and 00dba56.

📒 Files selected for processing (3)
  • openspec/changes/archive/2026-06-02-migrate-skip-bad-nars/design.md
  • pkg/cache/cache.go
  • pkg/ncps/migrate_chunks_to_nar.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/ncps/migrate_chunks_to_nar.go

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

go Pull requests that update go code merge-stack size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant