Repository navigation
feat(cache): add migrate-chunks-to-nar (reverse CDC migration) - #1301
Conversation
|
This change is part of the following stack: Change managed by git-spice. |
📝 WalkthroughSummary by CodeRabbit
WalkthroughAdds a verified, idempotent reverse migration (chunks→NAR): spec/design/tasks, Cache.MigrateChunksToNar with SHA-256 verification and optional force reclaim, CLI command + metrics + wiring, unit and CLI tests, Helm Job template/values/tests, and README/docs updates for exiting CDC mode. ChangesChunks to NAR Migration
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. ✨ Finishing Touches📝 Generate docstrings
Comment |
There was a problem hiding this comment.
Code Review
This pull request introduces the migrate-chunks-to-nar CLI command and the corresponding MigrateChunksToNar cache method, enabling operators to safely exit Content-Defined Chunking (CDC) by reconstructing chunked NARs back into verified whole files. The implementation includes robust content verification against the recorded NarHash, idempotent execution, and dedup-safe chunk reclamation, alongside a Helm chart job, tests, and documentation. The review feedback highlights two important improvements: implementing a lock refresher to prevent the distributed migration lock from expiring during long-running transfers of large NAR files, and checking for context cancellation inside the worker goroutines to avoid a flood of misleading error logs during a graceful shutdown.
There was a problem hiding this comment.
Actionable comments posted: 6
🤖 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-05-30-migrate-chunks-to-nar/design.md`:
- Line 15: Fix the typo in the description for the CLI entry named
migrate-chunks-to-nar: change the word "comman" to "command" in the design
document text for migrate-chunks-to-nar so the line reads "A
`migrate-chunks-to-nar` CLI command mirroring the forward command's flags and
walk/concurrency structure."
In `@openspec/changes/archive/2026-05-30-migrate-chunks-to-nar/tasks.md`:
- Line 17: Update the checklist item that currently reads "3.3 DEVIATION from
the design's deferred-reclaim default: reclamation is **immediate and
dedup-safe** (no `delete-delay` deferral, no `--force-reclaim` flag)" to reflect
the implemented behavior (deferred reclaim by default with opt-in
`--force-reclaim`); locate the line containing the exact phrase "3.3 DEVIATION
from the design's deferred-reclaim default" or the parenthetical mentioning
`delete-delay`/`--force-reclaim` and change the wording to state that default
reclaim is deferred and that `--force-reclaim` is available as an opt-in flag
(or otherwise align the checklist text with the rest of the PR/spec).
In `@pkg/cache/cache.go`:
- Around line 7565-7579: The forward and reverse migrations use different lock
keys ("migration-to-nar:<hash>" in MigrateChunksToNar vs
"migration-to-chunks:<hash>" in MigrateNarToChunks) causing races; unify them by
introducing a single lock key helper (e.g., migrationLockKey(hash) or a shared
prefix like "migration:<hash>") and update MigrateChunksToNar,
MigrateNarToChunks and BackgroundMigrateNarToChunks to call
c.downloadLocker.TryLock(ctx, migrationLockKey(narURL.Hash), c.downloadLockTTL)
(and honor the acquired boolean/ErrMigrationInProgress result) so both
directions serialize on the same per-hash lock.
- Around line 7663-7665: The PutNar call can legitimately fail if the whole-file
was already stored by a prior run; change the error handling around
c.narStore.PutNar(ctx, noneURL, rf, size) so that an "already exists" condition
is treated as success and not returned as fatal: detect the specific
already-exists error (e.g. errors.Is(err, store.ErrAlreadyExists) or by calling
c.narStore.HasNar(ctx, noneURL) as a fallback) and continue the flow, only
returning fmt.Errorf("error storing reconstructed whole nar: %w", err) for
genuine errors other than "already exists".
In `@pkg/ncps/migrate_chunks_to_nar.go`:
- Around line 327-340: The code currently increments totalProcessed after the
query-parse block, causing parse failures to increment totalFailed but not
totalProcessed; move the atomic.AddInt32(&totalProcessed, 1) so it executes
before attempting to parse row.Query (i.e., before the url.ParseQuery call) so
both the success path and the early-return failure path still count as
processed; keep the existing error handling that calls
RecordMigrationObject(..., MigrationTypeChunksToNar, MigrationOperationMigrate,
MigrationResultFailure) and returns on parse error.
- Around line 314-315: Validate or clamp the concurrency flag before calling
g.SetLimit to avoid passing 0 or negative values into errgroup.SetLimit which
can deadlock; locate where you call errgroup.WithContext and
g.SetLimit(cmd.Int("concurrency")) in migrate_chunks_to_nar.go and either add a
flag Validator on the concurrency flag to require >=1 or normalize the value
(e.g., if cmd.Int("concurrency") <= 0 then set it to 1) and then pass the
validated/clamped value into g.SetLimit; ensure the validation emits an error or
fallback message so callers know an invalid concurrency was corrected.
🪄 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: 4c0ced29-b07c-4d37-ae32-d8c51d8943f8
📒 Files selected for processing (19)
README.mdcharts/ncps/templates/migrate-chunks-to-nar-job.yamlcharts/ncps/tests/migrate_chunks_to_nar_job_test.yamlcharts/ncps/values.yamldocs/docs/User Guide/Features/CDC.mddocs/docs/User Guide/Operations.mddocs/docs/User Guide/Operations/Chunks to NAR Migration.mdopenspec/changes/archive/2026-05-30-migrate-chunks-to-nar/.openspec.yamlopenspec/changes/archive/2026-05-30-migrate-chunks-to-nar/design.mdopenspec/changes/archive/2026-05-30-migrate-chunks-to-nar/proposal.mdopenspec/changes/archive/2026-05-30-migrate-chunks-to-nar/specs/chunks-to-nar-migration/spec.mdopenspec/changes/archive/2026-05-30-migrate-chunks-to-nar/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.gopkg/ncps/root.go
CodeRabbit findings (verified against the code):
- Serialize forward/reverse migrations on one per-hash lock. Both directions now
use the existing migrationLockKey(hash) ("migration:<hash>") instead of
distinct "migration-to-chunks:" / "migration-to-nar:" keys, so a reverse
de-chunk can't race the background forward re-chunk of the same NAR. (The
background path goes through MigrateNarToChunks, so it inherits the key.)
- Treat an already-present whole file as resumable, not fatal: PutNar's
storage.ErrAlreadyExists (after a crash between PutNar and the DB flip) now
falls through to the flip instead of erroring.
- Clamp --concurrency to >= 1: errgroup.SetLimit(0) would make the first g.Go
block forever.
- Count a NAR as processed before the query-parse step so a parse failure still
reconciles with the processed total.
- Fix the stale "DEVIATION: immediate reclaim" wording in the archived tasks.md
to match the shipped deferred-by-default + --force-reclaim behavior.
Also fixes the deploy-docs-pages CI failure: register the new "Chunks to NAR
Migration" page under Operations in docs/!!!meta.json (the Trilium tree manifest)
so it has a parentNoteId.
(The "CLI comman" typo comment was a false positive — the doc already says
"command".)
Tests: shared-lock serialization (both directions return ErrMigrationInProgress
under the held key) and resume-when-whole-file-present, under -race. task
fmt/lint/test green; 146 helm unittests pass.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
CodeRabbit: - Serialize forward/reverse migrations on one per-hash lock (both now use the existing migrationLockKey(hash) = "migration:<hash>" instead of distinct keys), so a reverse de-chunk can't race the background forward re-chunk of the same NAR. - Treat an already-present whole file as resumable, not fatal: PutNar's storage.ErrAlreadyExists (crash between PutNar and the DB flip) falls through to the flip instead of erroring. - Clamp --concurrency to >= 1 (errgroup.SetLimit(0) would block g.Go forever). - Count a NAR as processed before query-parse so a parse failure reconciles. - Fix stale "DEVIATION: immediate reclaim" wording in the archived tasks.md. Gemini: - Start a lock refresher for the duration of MigrateChunksToNar: a large NAR (reconstruct + verify + upload to remote S3) can exceed downloadLockTTL; without refreshing, the lock could expire and another replica migrate concurrently. - Exit queued errgroup workers early when the group context is cancelled (graceful shutdown), avoiding a flood of misleading errors / inflated failures. DevSkim: drop the hardcoded test hash literal (flagged as a possible secret) in favor of testdata.Nar1.NarHash. Docs/CI: register the new "Chunks to NAR Migration" page under Operations in docs/!!!meta.json (Trilium tree manifest) so it has a parentNoteId — fixes the deploy-docs-pages build failure. (The "CLI comman" typo comment was a false positive — the doc already says "command".) Tests (under -race): shared-lock serialization (both directions return ErrMigrationInProgress under the held key) and resume-when-whole-file-present. task fmt/lint/test green; 146 helm unittests pass. Co-Authored-By: Claude Opus 4.8 <[email protected]>
32ded03 to
37afe63
Compare
Proposal for the reverse of migrate-nar-to-chunks: reconstruct whole NAR files from CDC chunks (hash-verified, idempotent/resumable, dedup-safe chunk reclamation) so a deployment can safely exit CDC. Specs/design/tasks and the implementation are TODO — see proposal.md. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…n/tasks) Flesh out the reverse-of-migrate-nar-to-chunks change to apply-ready: - specs/chunks-to-nar-migration: hash-verified reconstruction (verified-or- nothing), idempotent + resumable, dedup-safe chunk reclamation, dry-run, per-NAR failure isolation. - design: reuse streamCompleteChunks for reconstruction wrapped in a verifying hasher; write-then-flip-then-reclaim crash-safe ordering; idempotency via state detection; reclaim via the existing orphan predicate; command mirrors migrate-nar-to-chunks (flags, WalkNarInfos + errgroup concurrency). - tasks: TDD-ordered slices (reconstruct/verify -> record flip -> reclaim -> CLI -> docs -> verify). Implementation is TODO (run /opsx:apply on this branch). Co-Authored-By: Claude Opus 4.8 <[email protected]>
Provides a supported path to exit CDC: reconstruct CDC-chunked NARs back into
whole files. Previously migrate-nar-to-chunks was one-way (with delete-delay the
whole files are GC'd), so a deployment that enabled CDC could not return to
whole-file storage.
Cache (Cache.MigrateChunksToNar):
- Per-hash TryLock("migration-to-nar:"+hash), mirroring the forward migration.
- Reconstructs from chunks (getNarFromChunks), verifies the assembled SHA-256
against the linked narinfo NarHash + nar_file.file_size (verified-or-nothing),
and writes the whole file via narStore.PutNar (bypassing c.PutNar so CDC does
not re-chunk it).
- Write -> flip (total_chunks=0, drop nar_file_chunks links) -> reclaim ordering
for crash-safe resumability. Orphaned chunks are reclaimed dedup-safely via the
existing cleanupStaleLockChunks (chunks still referenced by another nar_file are
retained).
- Sentinels: ErrNarAlreadyWholeFile, ErrNoNarHashToVerify (no NarHash -> left
chunked, not de-chunked unverified), ErrNarHashMismatch.
CLI (ncps migrate-chunks-to-nar): mirrors migrate-nar-to-chunks (flags, errgroup
concurrency, --dry-run), iterates chunked nar_files, isolates per-NAR failures,
and exits non-zero if any failed. Registered in the root command.
Docs: README storage-backend section + command Description document the CDC
round-trip. openspec change migrate-chunks-to-nar archived (chunks-to-nar-migration
spec synced).
Tests (TDD, RED-verified; cache tests under -race): reconstruct+verify+store,
record flip, orphan reclaim, dedup-safe retention; CLI success, dry-run-no-changes,
and hash-mismatch -> non-zero exit without destroying data.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Reclaim safety: migrate-chunks-to-nar no longer deletes chunks out from under in-flight serves. A serve that began streaming from chunks before the record flip may still be reading those chunk files; deleting them mid-stream would truncate that transfer (the failure class #1296/#1297 fixed). - MigrateChunksToNar(ctx, narURL, forceReclaim): by default it flips the record and leaves now-orphaned chunks for the GC. forceReclaim=true (CLI --force-reclaim) reclaims immediately for drained/maintenance-window runs. Dedup-safe in both paths (shared chunks retained). - Spec (chunks-to-nar-migration): reclamation deferred-by-default + always dedup-safe; Purpose filled in. Helm chart: - Opt-in migrate-chunks-to-nar Job (post-install/post-upgrade hook) with forceReclaim / dryRun / concurrency toggles, so the de-chunking migration can be driven from the chart. Reuses the deployment's db/storage/redis config. (The cache.cdc.chunk-wait-timeout chart wiring already lives in main; not re-added here.) Docs (docs/docs): - New "Operations/Chunks to NAR Migration" page (reverse migration, --dry-run, --force-reclaim with in-flight-serve safety, Helm Job, verification/skip, failure isolation); linked from the Operations index and CDC feature page. Tests: cache tests under -race (default-leaves-chunks, force-reclaim-deletes, force-reclaim-retains-shared) + CLI tests (default-defer, force-reclaim, dry-run, hash-mismatch). task fmt/lint/test green; 146 helm unittests pass. Co-Authored-By: Claude Opus 4.8 <[email protected]>
CodeRabbit: - Serialize forward/reverse migrations on one per-hash lock (both now use the existing migrationLockKey(hash) = "migration:<hash>" instead of distinct keys), so a reverse de-chunk can't race the background forward re-chunk of the same NAR. - Treat an already-present whole file as resumable, not fatal: PutNar's storage.ErrAlreadyExists (crash between PutNar and the DB flip) falls through to the flip instead of erroring. - Clamp --concurrency to >= 1 (errgroup.SetLimit(0) would block g.Go forever). - Count a NAR as processed before query-parse so a parse failure reconciles. - Fix stale "DEVIATION: immediate reclaim" wording in the archived tasks.md. Gemini: - Start a lock refresher for the duration of MigrateChunksToNar: a large NAR (reconstruct + verify + upload to remote S3) can exceed downloadLockTTL; without refreshing, the lock could expire and another replica migrate concurrently. - Exit queued errgroup workers early when the group context is cancelled (graceful shutdown), avoiding a flood of misleading errors / inflated failures. DevSkim: drop the hardcoded test hash literal (flagged as a possible secret) in favor of testdata.Nar1.NarHash. Docs/CI: register the new "Chunks to NAR Migration" page under Operations in docs/!!!meta.json (Trilium tree manifest) so it has a parentNoteId — fixes the deploy-docs-pages build failure. (The "CLI comman" typo comment was a false positive — the doc already says "command".) Tests (under -race): shared-lock serialization (both directions return ErrMigrationInProgress under the held key) and resume-when-whole-file-present. task fmt/lint/test green; 146 helm unittests pass. Co-Authored-By: Claude Opus 4.8 <[email protected]>
37afe63 to
bfdf722
Compare
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 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 `@docs/`!!!meta.json:
- Around line 1827-1861: The docs metadata is missing the CDC internalLink
relation for the new "Chunks-to-NAR" note: add a relation object with
"type":"relation", "name":"internalLink", "value":"Chnk2NarMig1",
"isInheritable":false and an appropriate "position" (e.g., after existing
10/20/30/40 entries, use 50) into the metadata block where other internalLink
relations are defined (the same block containing values "ZBLjSKKfK6yH",
"QXVK8oy1Fxt4", "IjYqLhriG6Le", "3PqatYARSWot"); apply the same insertion to the
second metadata occurrence around the 2775-2820 range to keep backlinks in sync.
In `@docs/docs/User` Guide/Configuration/Storage/S3-Compatible Storage.md:
- Line 24: The code blocks that show the command starting with "ncps serve \"
are missing language identifiers; update each opening triple-backtick for the
three blocks containing that snippet (the ones around "ncps serve \") to use a
bash identifier by changing "```" to "```bash" so syntax highlighting applies to
all three occurrences.
In `@docs/docs/User` Guide/Deployment/High Availability.md:
- Line 152: The Garage setup code block lost its bash language identifier which
disables syntax highlighting; restore the opening fence to "```bash" for the
Garage setup code block (the block starting with the comment "# Start Garage
(requires a garage.toml in the current directory; see Garage docs)." in the High
Availability document) so the snippet is fenced as bash.
🪄 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: 170c293e-ae98-4e2b-851a-7b32224f642f
📒 Files selected for processing (25)
README.mdcharts/ncps/templates/migrate-chunks-to-nar-job.yamlcharts/ncps/tests/migrate_chunks_to_nar_job_test.yamlcharts/ncps/values.yamldocs/!!!meta.jsondocs/docs/Developer Guide/Contributing.mddocs/docs/User Guide/Configuration/Database/SQLite Configuration.mddocs/docs/User Guide/Configuration/Storage/S3-Compatible Storage.mddocs/docs/User Guide/Deployment/High Availability.mddocs/docs/User Guide/Features/CDC.mddocs/docs/User Guide/Operations.mddocs/docs/User Guide/Operations/Chunks to NAR Migration.mdopenspec/changes/archive/2026-05-30-migrate-chunks-to-nar/.openspec.yamlopenspec/changes/archive/2026-05-30-migrate-chunks-to-nar/design.mdopenspec/changes/archive/2026-05-30-migrate-chunks-to-nar/proposal.mdopenspec/changes/archive/2026-05-30-migrate-chunks-to-nar/specs/chunks-to-nar-migration/spec.mdopenspec/changes/archive/2026-05-30-migrate-chunks-to-nar/tasks.mdopenspec/specs/chunks-to-nar-migration/spec.mdpkg/cache/cache.gopkg/cache/migrate_chunks_to_nar_test.gopkg/cache/migration_lock_internal_test.gopkg/ncps/metrics.gopkg/ncps/migrate_chunks_to_nar.gopkg/ncps/migrate_chunks_to_nar_test.gopkg/ncps/root.go
✅ Files skipped from review due to trivial changes (7)
- pkg/ncps/metrics.go
- docs/docs/User Guide/Configuration/Database/SQLite Configuration.md
- openspec/changes/archive/2026-05-30-migrate-chunks-to-nar/.openspec.yaml
- docs/docs/Developer Guide/Contributing.md
- README.md
- docs/docs/User Guide/Operations/Chunks to NAR Migration.md
- openspec/changes/archive/2026-05-30-migrate-chunks-to-nar/tasks.md
🚧 Files skipped from review as they are similar to previous changes (4)
- charts/ncps/values.yaml
- charts/ncps/tests/migrate_chunks_to_nar_job_test.yaml
- openspec/changes/archive/2026-05-30-migrate-chunks-to-nar/specs/chunks-to-nar-migration/spec.md
- pkg/cache/cache.go
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #1301 +/- ##
============================
============================
☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
Summary
Adds
migrate-chunks-to-nar, the reverse ofmigrate-nar-to-chunks: it reconstructs CDC-chunked NARs back into whole files so a deployment can exit CDC. Previously the forward migration was one-way (withdelete-delaythe whole files are GC'd), so once chunked there was no supported path back to whole-file storage.Cache —
Cache.MigrateChunksToNar(ctx, narURL, forceReclaim)TryLock("migration-to-nar:"+hash), mirroring the forward migration.getNarFromChunks), verifies the assembled SHA-256 against the linked narinfo'sNarHash(+ size), and writes the whole file vianarStore.PutNar(bypassingc.PutNarso CDC does not re-chunk it). Verified-or-nothing — a NAR is never de-chunked unless it verifies.--force-reclaimopts into immediate, dedup-safe reclamation for drained/maintenance-window runs.ErrNarAlreadyWholeFile,ErrNoNarHashToVerify(noNarHash→ left chunked, not de-chunked unverified),ErrNarHashMismatch.CLI —
ncps migrate-chunks-to-narMirrors
migrate-nar-to-chunks(storage/db/lock flags,errgroupconcurrency,--dry-run). Adds--force-reclaim. Per-NAR failures are isolated (the batch continues) and the command exits non-zero if any NAR failed. Registered in the root command.Helm chart
Opt-in
migrate-chunks-to-narJob (post-install/post-upgradehook) withmigrateChunksToNar.{enabled,dryRun,forceReclaim,concurrency}, reusing the deployment's db/storage/redis config.Docs
New "Operations / Chunks to NAR Migration" page (CLI,
--dry-run,--force-reclaimwith the in-flight-serve safety note, the Helm Job, verification/skip behavior, failure isolation); linked from the Operations index and the CDC feature page;--cache-cdc-chunk-wait-timeoutdocumented in the CDC flags table.openspec
New
chunks-to-nar-migrationcapability (proposal/design/specs/tasks), archived and synced.Test plan
-race: reconstruct+verify+store, record flip, default-leaves-chunks-for-GC, force-reclaim-deletes-orphans, force-reclaim-retains-shared.task fmt/task lint(0 issues) /task testgreen; 146 helm unittests pass.nix flake check