Repository navigation
fix(ncps): purge unrecoverable NARs in migrate-chunks-to-nar - #1316
Conversation
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]>
|
This change is part of the following stack: Change managed by git-spice. |
📝 WalkthroughSummary by CodeRabbit
WalkthroughThis 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. ChangesChunked NAR hash-mismatch purge
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
Comment |
There was a problem hiding this comment.
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.
|
Documentation Updates 1 document(s) were updated by changes in this PR: NAR File Download and StreamingView 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).
|
There was a problem hiding this comment.
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
📒 Files selected for processing (11)
openspec/changes/archive/2026-06-02-migrate-skip-bad-nars/.openspec.yamlopenspec/changes/archive/2026-06-02-migrate-skip-bad-nars/design.mdopenspec/changes/archive/2026-06-02-migrate-skip-bad-nars/proposal.mdopenspec/changes/archive/2026-06-02-migrate-skip-bad-nars/specs/chunks-to-nar-migration/spec.mdopenspec/changes/archive/2026-06-02-migrate-skip-bad-nars/tasks.mdopenspec/specs/chunks-to-nar-migration/spec.mdpkg/cache/cache.gopkg/cache/migrate_chunks_to_nar_test.gopkg/ncps/metrics.gopkg/ncps/migrate_chunks_to_nar.gopkg/ncps/migrate_chunks_to_nar_test.go
- 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]>
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
pkg/cache/cache.go (1)
7778-7847:⚠️ Potential issue | 🟠 Major | ⚡ Quick winKeep the migration lock alive for the full purge.
PurgeChunkedNaruses the same per-hash migration lock asMigrateChunksToNar, 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
📒 Files selected for processing (3)
openspec/changes/archive/2026-06-02-migrate-skip-bad-nars/design.mdpkg/cache/cache.gopkg/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
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
Failedstate even after processing 99.6% of entries.Cache.PurgeChunkedNar: whenmigrate-chunks-to-narencountersErrNarHashMismatchit purges the broken entry — deletesnar_file_chunkslinks, reclaims orphaned chunk objects, and deletes thenar_filerecord — so the hash re-enters the normal upstream fetch path on the nextGetNarrequestGetNarInfostill succeeds and the re-fetch can complete normallynar_filerecords are retainedtotalPurgedcounter tracked separately fromtotalFailed; command exits 0 whenfailed == 0regardless of how many were purgedpurgedfield to progress-ticker and summary log linesMigrationResultPurged("purged") metric result constantTest plan
task fmt— no changestask lint— no issues in changed files (pre-existingtmp-dir/issues unrelated)task test— all unit tests pass with race detectorTestPurgeChunkedNar_DeletesLinksChunksAndRecord— purge deletes chunk links, orphaned objects, andnar_filerecordTestPurgeChunkedNar_RetainsSharedChunk— chunks shared with anothernar_fileare not deletedTestPurgeChunkedNar_RetainsNarInfoRecord— narinfo is left intact after purgeTestMigrateChunksToNar_CLI_HashMismatchPurgesNarAndExitsZero— command exits 0,nar_fileand orphaned chunks deleted, narinfo retained